Q: TensorFlow Probability: how to do sample weighting with log_prob loss function? I'm using TensorFlow probability to train a model whose output is a tfp.distributions.Independent object for probabilistic regression. My problem is that I'm unsure how to implement sample weighting in the negative log likelihood (NLL) loss function.
I have the following loss function which I believe does not use the sample_weight third argument:
class NLL(tf.keras.losses.Loss):
    ''' Custom keras loss/metric for negative log likelihood '''

    def __call__(self, y_true, y_pred, sample_weight=None):
        return -y_pred.log_prob(y_true)

With standard TensorFlow loss functions and a dataset containing (X, y, sample_weight) tuples, the use of sample_weight in the loss reductions summations is handled under the hood. How can I make the sum in y_pred.log_prob use the weights in the sample_weight tensor?

A: I found a solution to my problem as posted in this GitHub issue.
My problem was caused by the fact that my model outputs a tfp.Independent distribution, which means the log_prob is returned as a scalar sum over individual log_probs for each element of the tensor. This prevents weighting individual elements of the loss function. You can get the underlying tensor of log_prob values by accessing the .distribution attribute of the tfp.Independent object - this underlying distribution object treats each element of the loss as an independent random variable, rather than a single random variable with multiple values. By writing a loss function that inherits from tf.keras.losses.Loss, the resulting weighted tensor is implicitly reduced, returning the weighted mean of log_prob values rather than the sum, e.g.:
class NLL(tf.keras.losses.Loss):
    ''' Custom keras loss/metric for weighted negative log likelihood '''

    def __call__(self, y_true, y_pred, sample_weight=None):

        # This tensor is implicitly reduced by TensorFlow
        #     by taking the mean over all weighted elements
        return -y_pred.distribution.log_prob(y_true) * sample_weight


Q: BoxFit.cover does not work with CachedNetworkImage plus PhotoView In this scenario I can not make to work the fit property with BoxFit.cover.
There is always borders on screen. How can I do it?
Scaffold(
  appBar: AppBar(),
  body: CachedNetworkImage(
    height: double.infinity,
    width: double.infinity,
    fit: BoxFit.cover, // does not work
    imageUrl: _imageUrl,
    imageBuilder: (context, imageProvider) => PhotoView(
      imageProvider: imageProvider,
    ),
  ),
);

A:        Container(
        child: CachedNetworkImage(
          imageUrl: _imageUrl,
          imageBuilder: (context, imageProvider)=>PhotoView(
            minScale: 1.0,
            imageProvider: imageProvider,
          ),
        ),
      ),

A: For the future searchers, there is an another solution which seems perfectly fits the desired behaviour.
https://stackoverflow.com/a/58200356/5829191

A: This work for me. Since I have a Container with the same borderRadius as the Catched Image. Without the BoxDecoration it failed med too!
    Container( decoration: BoxDecoration(borderRadius:
BorderRadius.circular(10),),child:CachedNetworkImage(imageUrl: ("UrlToImage"),imageBuilder: (context, imageProvider) => Container(decoration: BoxDecoration(borderRadius: BorderRadius.circular(10),image: DecorationImage(image: imageProvider,
                                            fit: BoxFit.cover,
                                            )),),placeholder: (context, url) => CircularProgressIndicator(),errorWidget: (context, url, error) => Image.asset("PathToImage")
                                  ),


Q: Using _e() on text inside video tags prints that text, instead of only showing when html5  element is not supported I'm creating a wordpress theme in which I'm creating a shortcode for a video. Part of the output of this shortcode is something like this:
   $result .= '<video class="fullWidth" width="auto" height="auto" loop muted preload>';
    $result .= '<source src="'.$mp4.'" type="video/mp4" />';
    $result .= '<source src="'.$webm.'" type="video/webm" />';
    $result .= '<source src="'.$ogv.'" type="video/ogv" />';
    $result .= _e('Video tag is not supported in your browser.', 'my-theme-framework');
   $result .= '</video>';

Now the video is working but the text 'Vide tag is ...' is getting echoed out, but when I remove the text from the function, it gets hidden. So I believe it is because of the _e() function and I do not know what to do. I need that to make the text translation ready, should I remove it?
I've searched around for this, but I'm getting no relevant results. Please tell me if you know what I should do here.
Thank you.

A: _e() echoes the translated string, which will not work in variable assignment. You need to use __(), which returns the translated string.


Q: Awful looking custom transition I have a problem with custom transition between controllers. I have two view controllers. First is a table view controller and initiate controller is the second one. It has a button on it's top left corner which, when it is pressed, first navigation controller is called. There should be slide animation, but from left to right, not from right to left. I made my own transition but when the button is pressed, transition looks very awful. Transition code:
CATransition *transition = [CATransition animation];
transition.duration = 0.45;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault];
transition.type = kCATransitionFromLeft;
[transition setType:kCATransitionPush];
transition.subtype = kCATransitionFromLeft;
transition.delegate = self;
[self.navigationController.view.layer addAnimation:transition forKey:nil];
[self.navigationController pushViewController:controller animated:NO];

This is a screenshot, how the transition looks like:


Q: put part of the method which returns null in other method The method storeData works fine, but I am trying to put a part of my method in another method samePosition to minimize it, but I have the problem that some of its part returns null.
I put it in the other method names samePosition with return values Integer but then I received this error message:

This method must return a result of type Integer

How can I solve this problem?
storeData method before minimization:
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response storeData(Data data) {

    String macD = data.getMac();
    int routeD = data.getRoute();
    float latD = data.getLatitude();
    float longD = data.getLongitude();

    // Add the lat and Long to the ArrayList.
    latLongList.add(new LatLong(latD, longD));

////////////I want to put this part in seperate method "samePosition" //////////////
    int size = latLongList.size();
    if (size > 1) {
        ArrayList<Double> array = new ArrayList<>();

        for (int i = 0; i < latLongList.size() - 1; i++) {
            LatLong last = latLongList.get(latLongList.size() - 1);

            double distance = haversineDistance(latLongList.get(i), last);
            array.add(distance);

        }

        ArrayList<Double> distanceRange = new ArrayList<>();

        for (int j = 0; j < array.size(); j++) {

            // Store request in the circumcircle of 4 meter into ArrayList.
            if (array.get(j) < 4) {

                distanceRange.add(array.get(j));
            }
        }

        if (distanceRange.size() == 0) {
            processData(macD, routeD, latD, longD);
        } else {
            return null;
        }

    } else {

        processData(macD, routeD, latD, longD);
    }
//////////////////////until here/////////////////////////
    return Response.status(201).build();
}

Edit:
storeData:
public Response storeData(Data data) {

        String macD = data.getMac();
        int routeD = data.getRoute();
        float latD = data.getLatitude();
        float longD = data.getLongitude();

        // Add the lat and Long to the ArrayList.
        latLongList.add(new LatLong(latD, longD));

        System.out.println("latLondList size: " + latLongList.size());

         int valueReturned =   samePosition(macD, routeD, latD, longD);

        if (valueReturned == -1) {
            return null;
            } else {
                return Response.status(201).build();
            }
    }

samePosition method:
private int samePosition(String macD, int routeD, float latD, float longD) {
        int size = latLongList.size();
        if (size > 1) {
            ArrayList<Double> array = new ArrayList<>();

            for (int i = 0; i < latLongList.size() - 1; i++) {
                LatLong last = latLongList.get(latLongList.size() - 1);

                double distance = haversineDistance(latLongList.get(i), last);
                array.add(distance);

            }

            ArrayList<Double> distanceRange = new ArrayList<>();

            for (int j = 0; j < array.size(); j++) {

                // Store request in the circumcircle of 4 meter into ArrayList.
                if (array.get(j) < 4) {

                    distanceRange.add(array.get(j));
                }
            }

            if (distanceRange.size() == 0) {
                processData(macD, routeD, latD, longD);
            } else {
                return -1;
            }

        } else {

            processData(macD, routeD, latD, longD);
        }
    }

A: Instead of returning null you could return -1 and then check for the value you return being -1.
if (valueReturned == -1) {
return null;
} else {
    //continue with method
}

The samePosition() method should return always an integer:
private int samePosition(String macD, int routeD, float latD, float longD) {
    int size = latLongList.size();
    if (size > 1) {
        ArrayList<Double> array = new ArrayList<>();

        for (int i = 0; i < latLongList.size() - 1; i++) {
            LatLong last = latLongList.get(latLongList.size() - 1);

            double distance = haversineDistance(latLongList.get(i), last);
            array.add(distance);

        }

        ArrayList<Double> distanceRange = new ArrayList<>();

        for (int j = 0; j < array.size(); j++) {

            // Store request in the circumcircle of 4 meter into ArrayList.
            if (array.get(j) < 4) {

                distanceRange.add(array.get(j));
            }
        }

        if (distanceRange.size() == 0) {
            processData(macD, routeD, latD, longD);
            return 0;
        } else {
            return -1;
        }

    } else {
        processData(macD, routeD, latD, longD);
            return 0;
    }
}

A: Check the below and modify as needed. Instead of returning 201 as response in all the cases I preferred to return different status code based on whether you processed the data or not.
In your earlier code, the code segment you are trying to extract is returning null from one point and nothing from last else where you are calling processData(..).
@POST
@Consumes(MediaType.APPLICATION_JSON)
public Response storeData(Data data) {
  ..
  int status = samePosition(..);
  return Response.status(status).build();
}

private int samePosition(..) {
  int status = 201;
  if() {
    ...
    if (distanceRange.size() == 0) {
      processData(macD, routeD, latD, longD);
    } else {
      status = <Preferred HTTP status code to return for not processing>;
    }
  } else {

  }
  return status;
}


Q: Who is Pancakes? During my travels through happy happy pony land, I've came upon a very uncharacteristic background; the grave of Pancakes.
Who is Pancakes, and why is his grave in the land of endless joy, sunshine and dismembered unicorns?

A: Currently, there is no reliable information or source about the tombstone inscription or its meaning.
Some people pointed out that the inscription is an anagram for "A Epic Prank" (however, missing the letter s), which could be seen as a reference to Trolling is a art: The purpose of this phrase is to troll people by getting them to correct it (example).
A collection of additional fun facts/easter eggs regarding Whimsyshire can be found here and here.
A little OT: Blizzard put some stuff into the game where the purpose of is not known by now, e.g. the Black Rock Ledger. There exist long discussions about it. Perhaps the tombstone will also turn out to be another clue to something bigger.


Q: UICollectionViewCompositionLayout with auto-sizing cells containing a fixed ratio UIImageView The goal is to configure a UICollectionViewCompositionalLayout for full-width cells which contain a fixed-aspect ratio UIImageView (plus some other views underneath including variable height UILabels and UIStackViews) and have the cells properly auto-size. My naive attempt doesn't work and I can't figure out why. The simple case I present here gives me a bunch of constraint errors at runtime.
I cribbed the code from this answer, but it looks pretty straightforward:
    override func viewDidLoad() {
        super.viewDidLoad()

        let size = NSCollectionLayoutSize(
            widthDimension: NSCollectionLayoutDimension.fractionalWidth(1),
            heightDimension: NSCollectionLayoutDimension.estimated(100)
        )
        let item = NSCollectionLayoutItem(layoutSize: size)
        let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitem: item, count: 1)

        let section = NSCollectionLayoutSection(group: group)
        section.interGroupSpacing = 10

        let layout = UICollectionViewCompositionalLayout(section: section)

        collectionView.collectionViewLayout = layout
    }

And the constraints look like this:

And as soon as I scroll, I get these constraint errors:
2021-01-21 20:29:18.311491+0100 CompositionalLayoutDynamicHeight[96399:2597528] [LayoutConstraints] Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want.
    Try this:
        (1) look at each constraint and try to figure out which you don't expect;
        (2) find the code that added the unwanted constraint or constraints and fix it.
(
    "<NSLayoutConstraint:0x6000020a82d0 UIImageView:0x138818600.width == 1.33333*UIImageView:0x138818600.height   (active)>",
    "<NSLayoutConstraint:0x6000020a8460 V:|-(0)-[UIImageView:0x138818600]   (active, names: '|':UIView:0x13881c4d0 )>",
    "<NSLayoutConstraint:0x6000020a84b0 H:[UIImageView:0x138818600]-(0)-|   (active, names: '|':UIView:0x13881c4d0 )>",
    "<NSLayoutConstraint:0x6000020a8500 V:[UIImageView:0x138818600]-(0)-|   (active, names: '|':UIView:0x13881c4d0 )>",
    "<NSLayoutConstraint:0x6000020a8550 H:|-(0)-[UIImageView:0x138818600]   (active, names: '|':UIView:0x13881c4d0 )>",
    "<NSLayoutConstraint:0x6000020a85a0 'UIIBSystemGenerated' CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280.leading == UIView:0x13881c4d0.leading   (active)>",
    "<NSLayoutConstraint:0x6000020a85f0 'UIIBSystemGenerated' H:[UIView:0x13881c4d0]-(0)-|   (active, names: '|':CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280 )>",
    "<NSLayoutConstraint:0x6000020a8640 'UIIBSystemGenerated' CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280.top == UIView:0x13881c4d0.top   (active)>",
    "<NSLayoutConstraint:0x6000020a8690 'UIIBSystemGenerated' V:[UIView:0x13881c4d0]-(0)-|   (active, names: '|':CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280 )>",
    "<NSLayoutConstraint:0x6000020a60d0 'UIView-Encapsulated-Layout-Height' CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280.height == 292.667   (active)>",
    "<NSLayoutConstraint:0x6000020a6120 'UIView-Encapsulated-Layout-Width' CompositionalLayoutDynamicHeight.CollectionViewCell:0x13881c280.width == 390   (active)>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x6000020a82d0 UIImageView:0x138818600.width == 1.33333*UIImageView:0x138818600.height   (active)>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.

It seems that AutoLayout is creating that UIView-Encapsulated-Layout-Height constraint which is conflicting with the aspect ratio constraint—but why isn't it just resizing to fit it?

A: Auto-layout makes multiple "passes" when laying out the UI elements for Collection views (and Table views).
Frequently, particularly when using variable-sized cell content, auto-layout will throw warnings as it walks its way through the constraints.
Probably the easiest way to get rid of that warning is to give your Aspect Ratio constraint a Priority of less-than Required.
If you set it to Default High (750), that tells auto-layout it's allowed to "break" it without throwing the warning (but it will still be applied).

A: I had the same issue on a horizontal slider with dynamic item widths. I found the solution in my case which looks like a bug to me.
There are two functions to create a NSCollectionLayoutGroup. Using the other one fixed it for me.
This breaks my constraints:
let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitem: item, count: 1)

This doesnt:
let group = NSCollectionLayoutGroup.horizontal(layoutSize: size, subitems: [item])


Q: Bishop-Gromov for Kähler metrics Let $(M, g)$ be a (complete) Kähler manifold with Ricci curvature $\geq c$.
Is it true that the volume ratio of geodesic balls in $M$ with respect to balls in the corresponding (simply connected) complex space form with Ricci $\equiv c$ is a decreasing function?
I suspect the answer is no. Examples would be nice, also showing why the Riemannian proof breaks would help.
EDIT: A friend made me notice Gang Liu's paper (https://arxiv.org/pdf/1108.4231v1.pdf), where it is shown that, for real analytic metrics, the volume ratio is decreasing for small values of the radius.

A: It looks like the answer is indeed no with the quadric $\mathbb CP^1\times \mathbb CP^1$ a counterexample. Here the corresponding complex model space is $\mathbb CP^2$.
Recall that to get an Einstein metric with coefficient $\lambda=1$ we should choose it is as curvature of the anti-canonical bundle $-K$. Now, for $\mathbb CP^1\times \mathbb CP^1$ we have $-K\cong O(2)\times O(2)$. The diagonal $\mathbb CP^1\subset \mathbb CP^1\times \mathbb CP^1$  is geodesic and $-K$ restricts as $O(4)$ to it. It follows that the diameter of $\mathbb CP^1\times \mathbb CP^1$ is larger than that of $\mathbb CP^2$ (where $-K\cong O(3)$). Inddeed the diameter of the former space is equal to the diameter of its diagonal and the diameter of the latter space is equal to the diameter of any line in it.
As for where the usual proof breaks down, I don't know.


Q: has anyone undergone certification of PCI-DSS using general purpose HSM (and not payshield)? can we utilise a general purpose HSM for EMV related work ? like ARQC/ARPC ? PCI guidelines do not specifically prohibit general purpose HSM from being used. There are certain constraints (e.g. disallow trnslation of ISO Type 0 to Type 1), etc.
But im generally curious - has anyone passed certification of a EMV switch using a general purpose HSM ?
Here's why I think it is possible:
ISO 9564 and TR-31 standards mandate that a few common things like

b) It must prevent the determination of key length for variable length
keys.
c) It must ensure that the key can only be used for a specific
algorithm (such as TDES or AES, but not both).
d) It must ensure a modified key or key block can be rejected prior to use, regardless of the utility of the key after modification. Modification includes changing any bits of the key, as well as the reordering or manipulation of individual single DES keys within a TDES key block

In forthcoming TR-31 regulations, I see that AWS KMS is compliant at the "at-rest integrity checks" using stuff like  EncryptionContext and Policy Constraints
so im generally wondering what prevents us from using KMS for this purpose ?


Q: Performing a WHERE - IN query in CouchDB I would like to query for a list of particular documents with one call to CouchDB.
With SQL I would do something like
SELECT *
FROM database.table
WHERE database.table.id
IN (2,4,56);

What is a recipe for doing this in CouchDB by either _id or another field?

A: You need to use views keys query parameter to get records with keys in specified set.
function(doc){
    emit(doc.table.id, null);
}

And then
GET /db/_design/ddoc_name/_view/by_table_id?keys=[2,4,56]

To retrieve document content in same time just add include_docs=True query parameter to your request.
UPD: Probably, you might be interested to retrieve documents by this reference ids (2,4,56). By default CouchDB views "maps" emitted keys with documents they belongs to. To tweak this behaviour you could use linked documents trick:
function(doc){
    emit(doc.table.id, {'_id': doc.table.id});
}

And now request
GET /db/_design/ddoc_name/_view/by_table_id?keys=[2,4,56]&include_docs=True

will return rows with id field that points to document that holds 2,4 and 56 keys and doc one that contains referenced document content.

A: In CouchDB Bulk document APi is used for this:
curl -d '{"keys":["2","4", "56"]}' -X POST http://127.0.0.1:5984/foo/_all_docs?include_docs=true

http://wiki.apache.org/couchdb/HTTP_Bulk_Document_API


Q: Qt SDK download for MingW I´m looking for Qt SDK for windows that uses MingW as the compiler. Unfortunately, on the official download sites, I can only find the one that uses MSVC. Or just the library instead of the whole SDK.
Can anybody tell me where I can find the version I am looking for, or explain what I should do if I download QT library, QT creator and MingW seperately?

A: Here you can find pre-release builds using MinGW 4.7.
http://releases.qt-project.org/digia/5.0.1/latest/
They work well with the MinGW builds distributed here:
http://sourceforge.net/projects/mingwbuilds/
The Qt builds come with Qt Creator, so you can install it and should be good to go after setting up your kits.

A: You can find binaries here:
http://qt-project.org/forums/viewthread/23002/
But then you ought to reconfigure installation manual or you may use this utility.
Some guy from Digia promised MinGW builds by the end of January, so you can wait instead.


Q: How to add into map in range loop package main

import (
    "fmt"
)

func main() {
    m := make(map[int]int, 4)
    m[1] = 0
    m[2] = 0
    for k, _ := range m {
        i := 10 + k
        m[i] = 0
    }
    fmt.Println(m)
    fmt.Println("len:", len(m))
}

This code returns: 8 or 10 or 6 as length of map after loop.
Video is here, playgroud here.
I see that new added elements go into range, but can't explain why this loop stops randomly?

A: Spec: For statements:

The iteration order over maps is not specified and is not guaranteed to be the same from one iteration to the next. If a map entry that has not yet been reached is removed during iteration, the corresponding iteration value will not be produced. If a map entry is created during iteration, that entry may be produced during the iteration or may be skipped. The choice may vary for each entry created and from one iteration to the next. If the map is nil, the number of iterations is 0.

The spec states that if you add entries to the map you are ranging over, the elements you add may or may not be visited by the loop, and moreover, which is visited is not even deterministic (may change when doing it again).

A: You are modifying map you are iterating over. This is the cause.


Q: IOS Charts Labels not centered to data points. Charts Library I am currently using IOS Charts to for a line chart.
This is the link to it: Link
It is horribly documented and I am having trouble centering my X-Axis labels to the plots on my chart.
I have already enabled granularity and set it to 1. - This ensures the labels do not get repeated
Here is what my chart looks like now:

Here is what I want it to look like:
I know the spacing of the points is different, but my main focus is how to get the labels centered to the correct data points.
My Code:
`import UIKit
import Charts
class ReviewDetailVC: UIViewController, ChartViewDelegate {
@IBOutlet weak var chartView: LineChartView!

var yValues =  [Double]()
var months = [String]()
var xValues = [String]()
let red = UIColor(hue: 0.9639, saturation: 0.62, brightness: 0.93, alpha: 1.0)
let black = UIColor(red:0.29, green:0.29, blue:0.29, alpha:1.0)
let grey = UIColor(red:0.81, green:0.81, blue:0.81, alpha:1.0)

let avenirDemi =  UIFont(name: "AvenirNext-DemiBold", size: 14)
override func viewDidLoad() {
    super.viewDidLoad()

    chartView.delegate = self
    // Chart Ui Settings
    chartView.xAxis.axisMinimum = 1
    chartView.leftAxis.axisMaximum = 5
    chartView.leftAxis.axisMinimum = 0.0
    chartView.chartDescription?.text = ""
    chartView.xAxis.labelPosition = .bottom
    chartView.legend.enabled = false
    chartView.scaleYEnabled = false
    chartView.scaleXEnabled = true
    chartView.doubleTapToZoomEnabled = false
    chartView.highlighter = nil
    chartView.rightAxis.enabled = false
    chartView.xAxis.drawGridLinesEnabled = false
    chartView.dragEnabled = true
    chartView.scaleXEnabled = false
    chartView.scaleYEnabled = false
    chartView.zoom(scaleX: 4, scaleY: 1, x: 0, y: CGFloat(AxisDependency.left.rawValue))
    chartView.xAxis.labelFont = avenirDemi!
    chartView.xAxis.labelTextColor = grey
    chartView.leftAxis.labelFont = avenirDemi!
    chartView.leftAxis.labelTextColor = black
    chartView.xAxis.axisLineWidth = 0
    chartView.leftAxis.axisLineWidth = 0
    //chartView.xAxis.avoidFirstLastClippingEnabled = true
    chartView.xAxis.granularityEnabled = true
    chartView.xAxis.granularity = 1
    chartView.leftAxis.gridColor = grey
    chartView.leftAxis.gridLineDashLengths = [4]
    chartView.leftAxis.gridLineWidth = 1.5
    chartView.xAxis.centerAxisLabelsEnabled = true
    chartView.noDataText = "This person has not reviewed your business."

    //**MARK:: DATA SHIT

    let sales = DataGenerator.data()

    xValues = ["MAR 10"," MAR 15", "APR 7", "APR 8", "APR 15", "APR 30", "MAY 14", "MAY 21","MAY 31", "MAY 31"]
    yValues = [4,2,4,5,3,4,2,4,5]

    var salesEntries = [ChartDataEntry]()

    var salesMonths = [String]()

    var i = 0

    for sale in sales {
        // Create single chart data entry and append it to the array
        let saleEntry = ChartDataEntry(x: Double(i), y: sale.value)
        salesEntries.append(saleEntry)

        // Append the month to the array
        salesMonths.append(sale.date)

        i += 1
    }

    // Create bar chart data set containing salesEntries
    let chartDataSet = LineChartDataSet(values: salesEntries, label: "Profit")

    // Create bar chart data with data set and array with values for x axis

    let chartData = LineChartData(dataSets: [chartDataSet])

    //setChart(dataPoints: xValues, values: yValues)

    //let formatter = CustomLabelsAxisValueFormatter(miniTime: 0.0)
    //formatter.labels = xValues
    chartView.xAxis.valueFormatter = CustomLabelsAxisValueFormatter(miniTime: 0.0)

    //**MARK:: END DATA SHIT

    chartDataSet.colors = [red]
    chartDataSet.drawCirclesEnabled = true
    chartDataSet.circleRadius = 16
    chartDataSet.circleColors = [red]
    chartDataSet.circleHoleRadius = 12
    chartDataSet.circleHoleColor = UIColor.white
    chartDataSet.lineWidth = 4
    chartDataSet.drawValuesEnabled = false

    chartView.animate(yAxisDuration: 1)

    chartView.setVisibleXRangeMaximum(4)

    // Set bar chart data
        chartView.data = chartData
   setChart(dataPoints: xValues, values: yValues)

}

func setChart(dataPoints: [String], values: [Double]) {
    chartView.noDataText = "You need to provide data for the chart."

    var dataEntries: [ChartDataEntry] = []

    for i in 0..<dataPoints.count {
        let dataEntry = ChartDataEntry(x: Double(i), y: values[i])
        dataEntries.append(dataEntry)
    }

    let chartDataSet = LineChartDataSet(values: dataEntries, label: "")
    let chartData = LineChartData(dataSets: [chartDataSet])

    chartDataSet.colors = [red]
    chartDataSet.drawCirclesEnabled = true
    chartDataSet.circleRadius = 16
    chartDataSet.circleColors = [red]
    chartDataSet.circleHoleRadius = 12
    chartDataSet.circleHoleColor = UIColor.white
    chartDataSet.lineWidth = 4

    chartView.data = chartData

}

        }`

A: You can change your setChart method to this:
 func setChart(dataPoints: [String], values: [Double]) {
    chartView.noDataText = "You need to provide data for the chart."

    var dataEntries: [ChartDataEntry] = []

    for i in 0..<dataPoints.count {
        let dataEntry = ChartDataEntry(x: Double(i)+0.5, y: values[i])
        dataEntries.append(dataEntry)
    }

    let chartDataSet = LineChartDataSet(values: dataEntries, label: "")
    let chartData = LineChartData(dataSets: [chartDataSet])

    chartDataSet.colors = [red]
    chartDataSet.drawCirclesEnabled = true
    chartDataSet.circleRadius = 16
    chartDataSet.circleColors = [red]
    chartDataSet.circleHoleRadius = 12
    chartDataSet.circleHoleColor = UIColor.white
    chartDataSet.lineWidth = 4

    chartView.data = chartData

}

Result:
update:
chartView.xAxis.axisMinimum = 0.0 //I changed this from 1 to 0
let xvalues = ["MAR 10"," MAR 15", "APR 7", "APR 8", "APR 15", "APR 30", "MAY 14", "MAY 21","MAY 31", "MAY 31"]

chartView.xAxis.valueFormatter = IndexAxisValueFormatter(values: xvalues)

class MyIndexFormatter: IndexAxisValueFormatter {

open override func stringForValue(_ value: Double, axis: AxisBase?) -> String
{
        return "\(value)"
}

}


Q: Error when trying to push code to nexus maven I have found out that in order to add my code to my nexus repo I have to use mvn deploy
When ran I get this error:
https://hastebin.com/wikisohuni.pas
I have searhced ALL over stackoverflow and online guides, but NOTHING has worked!
settings.xml:
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/settings-1.0.0.xsd">
  <mirrors>
    <mirror>
      <id>nexus</id>
      <mirrorOf>*</mirrorOf>
      <url>http://192.168.0.145/nexus/content/groups/public</url>
    </mirror>
  </mirrors>
  <proxies></proxies>
  <pluginGroups>
    <pluginGroup>org.codehaus.modello</pluginGroup>
  </pluginGroups>
  <profiles>
    <profile>
      <id>nexus</id>
      <!--Enable snapshots for the built in central repo to direct -->
      <!--all requests to nexus via the mirror -->
      <repositories>
        <repository>
          <id>central</id>
          <url>http://central</url>
          <releases><enabled>true</enabled></releases>
          <snapshots><enabled>true</enabled></snapshots>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <id>central</id>
          <url>http://central</url>
          <releases><enabled>true</enabled></releases>
          <snapshots><enabled>true</enabled></snapshots>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>
  <activeProfiles>
    <activeProfile>nexus</activeProfile>
  </activeProfiles>
  <servers>
    <server>
      <id>nexus</id>
      <username>admin</username>
      <password>removed</password>
    </server>
  </servers>
</settings>

My pom can be found at: https://github.com/PhanaticGames/PhanaticSpigotCore/blob/master/pom.xml
EDIT: I edited my settings a bit and got that error to go away, however, I now get this error: https://hastebin.com/ohukowohud.sql
However, these are what run my jar. I am making a central API for other plugins ran by these jars.


Q: unicorn: do I need to disconnect from database in before_fork block? There is a comment that explains why you don't need to (and shouldn't) disconnect from DB and Redis in before_fork:

By disconnecting in before_fork, you are closing the connection at the parent process every time you spawn a child, which is only needed once - you're beating a dead horse. Connection handling is a child's concern (after_fork) rather than a parent's concern (before_fork).
ActiveRecord's connection pool is now keyed by Process.pid, so it's always safe to call ActiveRecord::Base.establish_connection in after_fork - the connection will never be shared with the parent, no need to disconnect at the master anyway.
On Unicorn, the master process is a singleton and can be used in many ways - spawn a thread and run EventMachine loop inside it to run scheduled / background jobs, etc. And there it's useful to keep the AR connection open. Only main thread will be inherited to a child (on linux systems at least) so it's safe to have threads.

Is that true?

A: It definitely isn't required, but I prefer to do it anyway - we run a ton of application servers and if we didn't disconnect the master process from the DB we'd be holding a lot of connections open for no reason.


Q: How to Set A Methods For A Class In Vue.js you know that we can use on events for a class in JQuery.
for instance
$(".example").click(function(){
//the process
})

I am new on Vue.js and I am working on methods in vue.js
Vue use v-on attr to set a method for a element. But I dont want to define attr for all elements whichs use same function.
For Example

Menu 1

Menu 1

Menu 2

You must saw, I used v-on attr for all li elements. For li elements it is not problem, I can solve it v-repeat but for some cases, I have to set same function for lots of divs or form. I want to set a class for a function and set a method for the class.
Is there any solution for it?

A: David's answer is good. But if you don't want to use Jquery, you can use document.querySelectorAll instead of $(this.el).find("li") and then add the click handlers with addEventListener in the directive.
Having said that, you don't have to add event listeners to all the elements in a directive (even though a directive might be the best solution for this). Another approach would be to do what you suggest, put the handlers on the parent elements, and then implement some logic depending on which element the function was called from. Example:
https://jsfiddle.net/q7xcbuxd/33/

Menu 1 item 1

Menu 2 item 1

Menu 2 item 2

Menu 2 item 3

    lots

    of

    items

var vue = new Vue({
    el: '#app',

    methods: {
        Menu: function(id){
            console.log('You invoked function Menu' + id + ' ' +
                        'by clicking on ' + event.path[0].innerHTML + ' ' +
                        'which is of type ' + event.srcElement.nodeName + '.\n' +
                        'The parent element\'s class name is \'' + event.srcElement.parentElement.className + '\' ' +
                        'which is of type ' + event.srcElement.parentElement.nodeName + '.');
        }
    }
});

A: I would write a directive for
 and
 that adds click handlers for all
 children.
Something like:
Vue.directive('menu', {
    bind: function () {
        $(this.el).find("li").on("click", function (event) {
            this.menu_click(event);
        });
    },
    update: function (value) {
        this.menu_click = value;
    },
    unbind: function () {
        $(this.el).find("li").off("click", this.menu_click);
    }
})

And use it like this:

Menu 1

Menu 1

Menu 2


Q: How to deploy Angular cli 7 app on Azure using Visual Studio code? I created an Angular app using angular-cli(node 8.12) and build it:
npm install -g @angular/cli7

ng new my-app

ng build --prod  //inside folder

i connect my visual studio code to my azure account then i create the service app and then just right click on my project and select Publish Web App then select my dist folder and deploy it.
VS say that all is completed and i see my dist folder but if i browse there i see the default page.
how can I solve this?


Q: vc++ 6.0 testing an unlicensed Activex ctrl by dlg application I am using vc++ 6.0. I Have made an unlicensed activex ctrl application from app wizard (MFC activeX ctrl wizard for generating random drawing). When I am testing this Activex by ActiveX control test container,  all functions are working fine, but when I am testing it with dialog application, On calling any method of ActiveX it is giving error debug assertion failed.
Program ......
File: winocc.cpp;
line: 345
I am making an object of this ActiveX ctrl wrapper class in my testing dialog application and then calling method defined in this ActiveX ctrl.
My code:
CNewSquiggleAcX m_ClNewSquigg;
CFileDialog m_ldFile(TRUE);
    // Show the File open dialog and capture the result
    if(m_ldFile.DoModal()== IDOK)
    {
        CString m_sResults;
        m_sResults = m_ldFile.GetFileName();
        //m_ClNewSquigg.GetSquiggleLength();
        m_ClNewSquigg.LoadDrawing(m_sResults); // Error comes in this line
                                                          calling any activex function
    }

Please help me thanks in advance

A: The control needs to be instanciated. If you placed it on a dialog template then opening the dialog will create the control. The other approach is to call the CreateControl method, which you can find in the h file of the control's wrapper class.


Q: Refreshing the Cursor from SQLiteCursorLoader My project uses the SQLiteCursorLoader library from commonsguy to load data from a database into a ListView. Among that data is a simple boolean (as so far as SQLite supports booleans... that is, a number that only ever is 0 or 1) that tells the state of a checkbox. If I change the state of a checkbox in a list and then scroll the item off the list, the list item returns to the state it has when the cursor was passed in, despite the fact that the underlying database has changed. If I change the state of a bunch of checkboxes and then activate the list's MultiChoiceMode, all the items displayed will revert back to the state they were in when the cursor was originally passed in, despite the fact that the underlying database has changed.
Is there a way to refresh the cursor? Cursor.requery() is deprecated, and I don't want to have to create a new Cursor each time a checkbox is checked, which happens a lot. I'm also unsure of how calling restartLoader() several times would work, performance-wise, especially since I use onLoadFinish() to perform some animations.

A:
Is there a way to refresh the cursor?

Call restartLoader() to have it reload the data.

I don't want to have to create a new Cursor each time a checkbox is checked, which happens a lot

Used properly, a ListView maintains the checked state for you. You would do this via android:choiceMode="multipleChoice" and row Views that implement Checkable. The objective is to not modify the database until the user has indicated they are done messing with the checklist by one means or another (e.g., "Save" action bar item).

I'm also unsure of how calling restartLoader() several times would work, performance-wise, especially since I use onLoadFinish() to perform some animations.

Don't call it several times. Ideally, call it zero times, by not updating the database until the user is done, at which point you are probably transitioning to some other portion of your UI. Or, call it just once per requested database I/O (e.g., at the point of clicking "Save"). Or, switch from using a CursorAdapter to something else, such as an ArrayAdapter on a set of POJOs you populate from the Cursor, so that the in-memory representation is modifiable in addition to being separately persistable.


Q: UIButton not working on the first tap I made a custom switch to turn on and off sound effects in my game Optic Combat, but for some reason the button that when tapped, animates the switch moving to a different position, is not working on the first tap. Subsequent taps work, just not the first one.
In the IBAction for the button I have:
- (IBAction)theSwitch:(id)sender {
NSUserDefaults *toggle = [NSUserDefaults standardUserDefaults];

if (_toggle == 1) {

    [UIView animateWithDuration:0.3 animations:^{
        audioToggle.frame = CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
    }];

    _toggle ++;
    [toggle setInteger:_toggle forKey:@"toggleState"];
    [toggle synchronize];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"audioOn"];

}

else {

    [UIView animateWithDuration:0.3 animations:^{
        audioToggle.frame = CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
    }];

    _toggle --;
    [toggle setInteger:_toggle forKey:@"toggleState"];
    [toggle synchronize];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"audioOn"];

}
}

And in the viewDidLoad, checking the state of the switch and adjusting it to show the correct position (on or off):
- (void)viewDidLoad
{
[super viewDidLoad];

if ([[NSUserDefaults standardUserDefaults] boolForKey:@"audioOn"]) {
    [audioToggle setFrame:CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height)];
    _toggle = 2;
}
else {
    [audioToggle setFrame:CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height)];
    _toggle = 1;
}

Edit: I used this to solve my problem, in the IBAction for the button:
if ([[NSUserDefaults standardUserDefaults] boolForKey:@"audioOn"]) {
    [UIView animateWithDuration:0.3 animations:^{
    audioToggle.frame = CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
    }];
    [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"audioOn"];
}
else {
    [UIView animateWithDuration:0.3 animations:^{
    audioToggle.frame = CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
    }];
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"audioOn"];
}

A: In your viewDidLoad
 if _toggle = 2;
 frame = CGRectMake(924.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height)

and
if _toggle = 1;
 frame = CGRectMake(985.0f, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height)

But in your buttonAction it is different. Interchange in viewDidLoad if buttonAction is correct.

A: I suspect Anusha got it. But I also suspect you would easily have found it yourself if you'd chosen a slightly different style. The toggle is either on or off, in other words a perfect match for a boolean. If you had a BOOL named swicthedOn you'd have checks reading if (switchedOn) which would improve readability a lot.
Something like this perhaps:
- (IBAction)theSwitch:(id)sender { // Not using the sender for anything (?)
    NSUserDefaults *toggle = [NSUserDefaults standardUserDefaults];
    BOOL audioOn = NO;
    float toggleX = 924.0f;

    if (_switchIsOn) {
        toggleX = 985.0f;
        audioOn = NO; // not strictly necessary but improves readability
    }
    else {
        toggleX = 924.0f; // not strictly necessary but improves readability
        audioOn = YES;
    }

    _switchIsOn = audioOn;
    [UIView animateWithDuration:0.3 animations:^{
        audioToggle.frame = CGRectMake(toggleX, 59.0f, audioToggle.frame.size.width, audioToggle.frame.size.height);
    }];

    [toggle setBool:_switchIsOn forKey:@"toggleState"];
    [toggle synchronize];
    [[NSUserDefaults standardUserDefaults] setBool:audioOn forKey:@"audioOn"]; // Not being synchronized
}

Yes, I refactored it (and probably introduced a couple of new bugs). Sorry, couldn't help myself...


Q: What's the path to global node_modules folder in Travis CI I need to pass the path for the node_modules global installation folder to the mink-zombie-driver, but I can't find anywhere in the docs what's the path for it.
MinkExtension requires you to pass the node_modules folder in the configuration file for Behat.


Q: Column-image hover text Hello everybody out there reading my question :)
I am currently working on website with a "Masonry-lookalike" home screen.
There are 4x4 images with 2 different sizes and 1 image in every column is hidden.
So far it went pretty good but now I am stuck on the text-effect when hovering one of the images.
When the cursor is hovering over an image, a small text-box should appear on the bottom of it.

*

*How do i get them one above the other without ruining the Masonry?

*Where do i place the Text in the html code?
Sorry for my English, its not the best since I am from Austria ;)
HTML:
<!DOCTYPE html>

    <link href="style.css" rel="stylesheet" type="text/css" />

    <meta charset="utf-8">

CSS:
body {
    margin: 0;
    padding: 0;
}
#img-container {
    width: 1200px;
    margin: 0 auto;
    font-size: 0;
}
#content {
    column-count: 4;
    column-gap: 10px;
}
#content li img {
    margin-bottom: 10px;
    width: 100%;
    display: block;
}
/* ---------------------  HOVER EFFECTS  --------------------- */

.img_a:hover {
    opacity: 0.5;
}
.img_b:hover {
    opacity: 0.5;
}
.img_c:hover {
    opacity: 0.5;
}

I will append some zip.-file with .css .html and images.
Link to Dropbox

A: The following writeup might help you:
http://geekgirllife.com/place-text-over-images-on-hover-without-javascript/
It is one of the simplest methods I came across. Place the div tag containing text right below the img tag.


Q: AS3 undefined property stageVideos I have an AS3 Mobile AIR project targeting iOS and Android. For some reason when I try to access stageVideos i.e. stage.stageVideos[0]...there is NO stageVideos property available on stage?? Very strange as I've done it before. My app is using Starling and Features UI framework, and my class is extending Screen. I'm fairly new to both frameworks but have been AS veteren. Thanks!

A: Should be hardware problem. When StageVideo is not available on particular device stage.stageVideos property is empty, so to make sure you should make check like this.
var stageVideo:StageVideo;

if ( stage.stageVideos.length >= 1 ) {
    stageVideo = stage.stageVideos[0];
}

or register  StageVideoAvailabilityEvent on stage
stage.addEventListener(StageVideoAvailabilityEvent.STAGE_VIDEO_AVAILABILITY, stageVideoChange);

private function stageVideoChange(e:StageVideoAvailabilityEvent):void
{
    if(e.availability == AVAILABLE)
    {
         // (stage.stageVideos.length >= 1) is TRUE so we can use stageVideo[0]
    }
    else
    {
         // StageVideo become unavailable for example after going from fullscreen
         // back to wmode=normal, wmode=opaque, or wmode=transparent
    }
}

Of course second approach is more acceptable because you are notified every time StageVideo becomes available or negative. Note if stage video is available at the moment of registering Listener on StageVideoAvailabilityEvent then listener function (stageVideoChange) is called immediately.

A: Turns out Starling runs on Stage3D on TOP of the actual flash display stage. So in order to do this, you need to hide the Starling Stage3D first:
Starling.current.stage3D.visible = false

Then you can access and show...etc stageVideos and add to the flash display stage:
_stageVideo = Starling.current.nativeStage.stageVideos[0];

So basically, the native flash display stage is on the Starling.current.nativeStage property, however, can not be visible unless you first hide the Starling.current.stage3D FIRST.
Thanks for the responses! Hope this helps anyone else with the same problem.


Q: regex breaks when I use a colon(:) I just started working with elastic search. By started working I mean I have to query an already running elastic database.  Is there a good documentation of the regex they follow. I know about the one on their official site, but its not very helpful.
The more specific problem is that I want to query for lines of the sort:
10:02:37:623421|0098-TSOT {TRANSITION} {ID} {1619245525} {securityID} {} {fromStatus} {NOT_PRESENT} {toStatus} {WAITING}
or
01:01:36:832516|0058-CT {ADD} {0} {3137TTDR7} {23} {COM} {New} {0} {0} {52} {1}
and more of a similar structure. I don't want a generalized regex. If possible, could someone give me a regex expression for each of these that would run with elastic?
I noticed that it matches if the regexp matches with a substring too when I ran with:
query = {"query":
             {"regexp":
                  {
                      "message": "[0-9]{2}"
                  }
              },
         "sort":
             [
                 {"@timestamp":"asc"}
             ]
         }

But it wont match anything if I use:
query = {"query":
             {"regexp":
                  {
                      "message": "[0-9]{2}:.*"
                  }
              },
         "sort":
             [
                 {"@timestamp":"asc"}
             ]
         }

I want to write regex that are more specific and that are different for the two examples given near the top.

A: turns out my message is present in the tokenized form instead of the raw form, and : is one of the default delimiters of the tokenizer, in elastic. And as a reason, I can't use regexp query on the whole message because it matches it with each token individually.


Q: How to add groups to asp.net dropdownlist control? I have to implement groups in asp.net dropdownlist.
eg: I have a classname as dropdownlist group and students in the class as its options.
How can I implement this using  JqueryUI Multiselect.


Q: Select-Object with output from 2 cmdlets Suppose I have the following PowerShell script:
Get-WmiObject -Class Win32_Service |
Select DisplayName,@{Name="PID";Expression={$_.ProcessID}} |
Get-Process |
Select Name,CPU

This will:
Line 1: Get all services on the local machine
Line 2: Create a new object with the DisplayName and PID.
Line 3: Call Get-Process for information about each of the services.
Line 4: Create a new object with the Process Name and CPU usage.
However, in Line 4 I want to also have the DisplayName that I obtained in Line 2 - is this possible?

A: One way to do this is to output a custom object after collecting the properties you want. Example:
Get-WmiObject -Class Win32_Service | foreach-object {
  $displayName = $_.DisplayName
  $processID = $_.ProcessID
  $process = Get-Process -Id $processID
  new-object PSObject -property @{
    "DisplayName" = $displayName
    "Name" = $process.Name
    "CPU" = $process.CPU
  }
}

A: A couple of other ways to achieve this:
Add a note property to the object returned by Get-Process:
Get-WmiObject -Class Win32_Service |
Select DisplayName,@{Name="PID";Expression={$_.ProcessID}} |
% {
    $displayName = $_.DisplayName;
    $gp = Get-Process;
    $gp | Add-Member -type NoteProperty -name DisplayName -value $displayName;
    Write-Output $gp
} |
Select DisplayName, Name,CPU

Set a script scoped variable at one point in the pipeline, and use it at a later point in the pipeline:
Get-WmiObject -Class Win32_Service |
Select @{n='DisplayName';e={($script:displayName =  $_.DisplayName)}},
       @{Name="PID";Expression={$_.ProcessID}} |
Get-Process |
Select @{n='DisplayName';e={$script:displayName}}, Name,CPU

A: Using a pipelinevariable:
Get-CimInstance -ClassName Win32_Service -PipelineVariable service |
Select @{Name="PID";Expression={$_.ProcessID}} |
Get-Process |
Select Name,CPU,@{Name='DisplayName';Expression={$service.DisplayName}}


Q: How to insert a existing json data into new object? I have a json data is in this form
[ { id: '1', name: 'Plant Director', parentJobID: -1 },
  { id: '19', name: 'Operations Director', parentJobID: 1 },
  { id: '16',
    name: 'Financial planning and costs Manager',
    parentJobID: 19 },
  { id: '14', name: 'Cost Analyst', parentJobID: 16 },
  { id: '15', name: 'Head of Costs', parentJobID: 16 },
  { id: '17', name: 'Manufacturing Manager', parentJobID: 19 },
  { id: '2', name: 'Head of Security', parentJobID: 17 },
  { id: '3', name: 'Asistente Ejecutiva', parentJobID: 2 },
  { id: '8', name: 'Jefe de Mantenimiento', parentJobID: 2 },
  { id: '27',
    name: 'Jefe Aseguramiento de Calidad',
    parentJobID: 2 },
  { id: '28', name: 'Jefe Seguridad Alimentaria', parentJobID: 27 },
  { id: '33', name: 'Operario Fabricación A (2)', parentJobID: 28 },
  { id: '34', name: 'Operario Fabricación B (2)', parentJobID: 28 },
  { id: '29',
    name: 'Especialista Aseguramiento de Calidad',
    parentJobID: 27 },
  { id: '30',
    name: 'Especialista en Microbiología',
    parentJobID: 27 },
  { id: '31',
    name: 'Especialista en Evaluación Sensorial',
    parentJobID: 27 },
  { id: '32',
    name: 'Técnico Aseguramiento de Calidad',
    parentJobID: 27 },
  { id: '4', name: 'Production Manager', parentJobID: 17 },
  { id: '5', name: 'Head of Maintenance', parentJobID: 17 },
  { id: '6', name: 'Quality Control Manager', parentJobID: 17 },
  { id: '7', name: 'Técnico Medio Ambiente', parentJobID: 6 },
  { id: '23',
    name: 'Quality Control Technician 1',
    parentJobID: 6 },
  { id: '25', name: 'Operario Fabricación B', parentJobID: 23 },
  { id: '26', name: 'Operario Fabricación D', parentJobID: 23 },
  { id: '24',
    name: 'Quality Control Technician 2',
    parentJobID: 6 },
  { id: '9', name: 'Warehouse Manager', parentJobID: 17 },
  { id: '10', name: 'Head of Planning', parentJobID: 17 },
  { id: '20', name: 'Operario Mtto A (2)', parentJobID: 10 },
  { id: '11',
    name: 'Head of Continuous Improvement',
    parentJobID: 17 },
  { id: '21', name: 'Operario Servicios A (2)', parentJobID: 11 },
  { id: '12', name: 'Head of Supplies', parentJobID: 17 },
  { id: '13', name: 'Process Manager', parentJobID: 17 },
  { id: '18', name: 'IT Manager', parentJobID: 17 },
  { id: '35', name: '[ LINEA DE PRODUCCION ]', parentJobID: 1 },
  { id: '22', name: 'Extrusion Area', parentJobID: -1 } ]

then i change it into hierarchy form like:
[ { id: '1',
    name: 'Plant Director',
    parentJobID: -1,
    children: [ [Object], [Object] ] },
  { id: '22',
    name: 'Extrusion Area',
    parentJobID: -1,
    children: [] } ]

i want to show like this
  http://www.jqueryscript.net/demo/jQuery-Plugin-To-Create-Checkbox-Tree-View-highchecktree/
but in this they used item label which is not in my response  i need to change the josn in this form

 item:{
                id: '1',
                label: 'Plant Director',
                checked: false
            },
            children: [{
               item:{
                    id: '19',
                    label: 'Operations Director',
                    checked: false
                }
            },{
               item:{
                    id: '35',
                    label: '[ LINEA DE PRODUCCION ]',
                    checked: false
                }
            }
            }]


Q: TypeError: Cannot interpret feed_dict key as Tensor, need to understand sessions and graphs I'm new to tensorflow and posting this using mobile. I actually wanted the session to alive so used the following way of coding. However,  in one place I can see Placeholder node existing,  but error comes up saying the node doesn't exist. I doubt on the same graph being used.
class Model(object):

    def __init__(self, model_path):
        self.sess = tf.Session()
        self.graph = tf.Graph()
        self.graph_def = tf.GraphDef()

        with open(model_path, "rb") as f:
            self.graph_def.ParseFromString(f.read())

        with tf.Graph().as_default() as self.graph:
            tf.import_graph_def(self.graph_def)

        self.input_operation = self.graph.get_operation_by_name('import/Placeholder')
        self.output_operation = self.graph.get_operation_by_name('import/final_result')

    def predict(self, images):
        dims_expander = tf.expand_dims(images, 0)
        resized = tf.image.resize_bilinear(dims_expander, [299, 299])
        normalized = tf.divide(tf.subtract(resized, [0]), [255])
        print(normalized)
        for op in self.graph.get_operations():
            print(op.name)
            results = self.sess.run(self.output_operation.outputs[0], {self.input_operation.outputs[0]: self.sess.run(normalized)})
        results = np.squeeze(results)
        top_k = results.argsort()[-5:][::-1]
        labels = ['1','0']
        print(labels[top_k[0]], results[top_k[0]])

And then making an object.
model = Model('identification_model.pb').predict(img_from_openCV)

The following is the output error including the print statement that printed the first node to be import/Placeholder
Tensor("truediv_13:0", shape=(1, 299, 299, 3), dtype=float32)
import/Placeholder
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1091             subfeed_t = self.graph.as_graph_element(
-> 1092                 subfeed, allow_tensor=True, allow_operation=False)
   1093           except Exception as e:

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in as_graph_element(self, obj, allow_tensor, allow_operation)
   3489     with self._lock:
-> 3490       return self._as_graph_element_locked(obj, allow_tensor, allow_operation)
   3491

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\framework\ops.py in _as_graph_element_locked(self, obj, allow_tensor, allow_operation)
   3568       if obj.graph is not self:
-> 3569         raise ValueError("Tensor %s is not an element of this graph." % obj)
   3570       return obj

ValueError: Tensor Tensor("import/Placeholder:0", shape=(?, 299, 299, 3), dtype=float32) is not an element of this graph.

During handling of the above exception, another exception occurred:

TypeError                                 Traceback (most recent call last)

----> 1 model = Model('identification_model.pb').predict(img)

     32         for op in self.graph.get_operations():
     33             print(op.name)
---> 34             results = self.sess.run(self.output_operation.outputs[0], {self.input_operation.outputs[0]: self.sess.run(normalized)})
     35         results = np.squeeze(results)
     36         top_k = results.argsort()[-5:][::-1]

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in run(self, fetches, feed_dict, options, run_metadata)
    927     try:
    928       result = self._run(None, fetches, feed_dict, options_ptr,
--> 929                          run_metadata_ptr)
    930       if run_metadata:
    931         proto_data = tf_session.TF_GetBuffer(run_metadata_ptr)

C:\ProgramData\Anaconda3\lib\site-packages\tensorflow\python\client\session.py in _run(self, handle, fetches, feed_dict, options, run_metadata)
   1093           except Exception as e:
   1094             raise TypeError(
-> 1095                 'Cannot interpret feed_dict key as Tensor: ' + e.args[0])
   1096
   1097           if isinstance(subfeed_val, ops.Tensor):

TypeError: Cannot interpret feed_dict key as Tensor: Tensor Tensor("import/Placeholder:0", shape=(?, 299, 299, 3), dtype=float32) is not an element of this graph.

A: When you create the session, the default graph is launched by default, which does not contain the operations you are looking for (they are all in self.graph). You should do something like this:
with tf.Session(self.graph) as sess:
    sess.run(...)

Now, sess will have access to self.input_operation and self.output_operation. In your code, this means you should create the session after you create self.graph. By the way, most of the time it is more convenient to just use the default graph (exactly to avoid problems like these). May be this post will also help you in this regard.


Q: Fragment crash: IndexOutOfBoundsException: Invalid index x, size is x after updating my database Im making an app where i download the data from an api. The data is downloaded every X minutes. When the data has been downloaded, it is stored in my DB. However, the problem i have is that whenever i update the db, the generateData() method in FragmentTrend crashes when i switch to another tab and comeback again. I get the the index out of bound exception as seen below. It crashes at line:
int y = Integer.parseInt(listDatastream.get(i).getCurrent_value());

Ive tried to test out that whenever the count != getNumberOfElementsInDatabase() then just return the value to see whether or not it would help, however, i end up with another error which is similar to this thread: DB error code 14
Any help would be appreciated! Ive been stuck with this problem for more than 3 days now! Thank you!
Additional information: I have 4 tabs and use FragmentStatePagerAdapter to navigate. Ive noticed one thing while navigating. Whenever i navigate to the neighboring tab (such as tab1 to tab2), the previous tab is not terminated. It is still on the run. I found this out by printing an endless forloop with text. The for loop stops only when im 2 tabs away (such as from tab1 to tab3 / tab4 or tab 2 to tab4 etc). So the app crashes only when i select tab3 or tab4 then reselect tab1 or tab2 respectively.
Error:
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: FATAL EXCEPTION: main
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: Process: com.thesis.dell.MaterialTest2, PID: 2618
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime: java.lang.IndexOutOfBoundsException: Invalid index 166, size is 166
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at java.util.ArrayList.get(ArrayList.java:308)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at com.thesis.dell.MaterialTest2.fragments.FragmentTrend.generateData(FragmentTrend.java:166)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at com.thesis.dell.MaterialTest2.fragments.FragmentTrend.drawGraphVolt(FragmentTrend.java:112)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at com.thesis.dell.MaterialTest2.fragments.FragmentTrend.onCreateView(FragmentTrend.java:86)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at android.support.v4.app.Fragment.performCreateView(Fragment.java:1786)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:947)
10-29 19:37:09.693 2618-2618/? E/AndroidRuntime:     at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1126)

FragmentTrend.java
package com.thesis.dell.MaterialTest2.fragments;

import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.LegendRenderer;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;
import com.thesis.dell.MaterialTest2.MyApplication;
import com.thesis.dell.MaterialTest2.R;
import com.thesis.dell.MaterialTest2.log.L;
import com.thesis.dell.MaterialTest2.pojo.Datastream;

import java.util.ArrayList;

public class FragmentTrend extends Fragment {

private static final String STATE_DATASTREAM2 = "state_datastream2";
private ArrayList<Datastream> listDatastream = new ArrayList<>();
//private SwipeRefreshLayout mSwipeRefreshLayout;
private View view;
private LineGraphSeries<DataPoint> mVolt;
private int count;

public FragmentTrend() {
    // Required empty public constructor
}

public static FragmentTrend newInstance(String param1, String param2) {
    FragmentTrend fragment = new FragmentTrend();
    Bundle args = new Bundle();
    //put any extra arguments that you may want to supply to this fragment
    fragment.setArguments(args);
    return fragment;
}

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.tab_trend,container,false);

    count = getNumberOfElementsInDatabase();
    //setupSwipe();
    //printAllValuesInDatastream();

    if (savedInstanceState != null) {
        //if this fragment starts after a rotation or configuration change,
        // load the existing data from a parcelable
        L.t(getActivity(), "savedInstanceState not null");
        listDatastream = savedInstanceState.getParcelableArrayList(STATE_DATASTREAM2);
    }
    else {
        //if this fragment starts for the first time, load the list of data from a database
        //get a reference to our DB running on our main thread
        L.t(getActivity(), "savedInstanceState is null");
        listDatastream = MyApplication.getWritableDatabase().readDatastreams();
    }
    if (listDatastream != null && !listDatastream.isEmpty()) {
        drawGraphVolt();
    }

    return view;
}

public void drawGraphVolt () {
    // Setting up and drawing volt graph
    GraphView graph = (GraphView) view.findViewById(R.id.graph);

    mVolt = new LineGraphSeries<>(generateData());
    graph.addSeries(mVolt);

    // styling grid/labels
    graph.getGridLabelRenderer().setGridColor(getResources().getColor(R.color.colorGraphGrid));
    graph.getGridLabelRenderer().setHorizontalLabelsColor(getResources().getColor(R.color.colorGraphText));
    graph.getGridLabelRenderer().setVerticalLabelsColor(getResources().getColor(R.color.colorGraphText));
    graph.getGridLabelRenderer().setTextSize(45);
    graph.getGridLabelRenderer().reloadStyles();

    // styling series
    mVolt.setColor(getResources().getColor(R.color.colorAccent));
    mVolt.setThickness(4);
    //series.setDrawBackground(true);
    //series.setBackgroundColor(getResources().getColor(R.color.gridGraphColor));

    graph.getViewport().setYAxisBoundsManual(true);
    graph.getViewport().setMinY(graph.getViewport().getMinY(false));
    graph.getViewport().setMaxY(graph.getViewport().getMaxY(false));

    graph.getViewport().setXAxisBoundsManual(true);
    graph.getViewport().setMinX(graph.getViewport().getMinX(true));
    graph.getViewport().setMaxX(graph.getViewport().getMaxX(true));

    mVolt.setTitle("Volt");
    graph.getLegendRenderer().setVisible(true);
    graph.getLegendRenderer().setAlign(LegendRenderer.LegendAlign.TOP);
    graph.getLegendRenderer().setTextSize(45);
    graph.getLegendRenderer().setBackgroundColor(getResources().getColor(R.color.colorPrimary));
    graph.getLegendRenderer().setTextColor(getResources().getColor(R.color.colorPrimaryText));
    graph.getLegendRenderer().setPadding(15);
    graph.getLegendRenderer().setMargin(0);

    graph.getViewport().setScrollable(true);
}

private DataPoint[] generateData() {

    DataPoint[] values = new DataPoint[count];
    for (int i = 0; i < count; i++) {
//            if (count != getNumberOfElementsInDatabase()) {
//
//                return values;
//            }

        int x = i;
        int y = Integer.parseInt(listDatastream.get(i).getCurrent_value());
        DataPoint v = new DataPoint(x, y);
        values[i] = v
    }
    return values;
}

@Override
public void onPause() {
    super.onPause();
}

@Override
public void onResume() {
    super.onResume();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putParcelableArrayList(STATE_DATASTREAM2, listDatastream);
}

public int getNumberOfElementsInDatabase() {
    int countListDatastream = MyApplication.getWritableDatabase().getTotalNumberOfElements();
    return countListDatastream;
}

}
My Database:
package com.thesis.dell.MaterialTest2.database;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteStatement;

import com.thesis.dell.MaterialTest2.pojo.Datastream;
import com.thesis.dell.MaterialTest2.log.L;

import java.util.ArrayList;
import java.util.Date;

public class MyDatabase {

private MyHelper mHelper;
private SQLiteDatabase mDatabase;

public MyDatabase(Context context) {
    mHelper = new MyHelper(context);
    mDatabase = mHelper.getWritableDatabase();
    //mDatabase.close();
}

public void insertValues(ArrayList<Datastream> listValues, boolean clearPrevious) {
    if (clearPrevious) {
        deleteData();
    }
    //beginTransaction(null /* transactionStatusCallback */, true); allowed to comment like this?
    //create a sql prepared statement
    String sql = "INSERT INTO " + MyHelper.TABLE_NAME + " VALUES (?,?,?);";
    //compile the statement and start a transaction
    SQLiteStatement statement = mDatabase.compileStatement(sql);
    mDatabase.beginTransaction();
    for (int i = 0; i < listValues.size(); i++) {
        Datastream currentData = listValues.get(i);
        statement.clearBindings();
        //for a given column index, simply bind the data to be put inside that index
        statement.bindString(2, currentData.getCurrent_value());
        statement.bindLong(3, currentData.getCurrent_valueAt() == null ? -1 : currentData.getCurrent_valueAt().getTime());
        L.m("Inserting entry " +i);
        statement.execute();
    }
    //set the transaction as successful and end the transaction
    mDatabase.setTransactionSuccessful();
    mDatabase.endTransaction();
}

public int getTotalNumberOfElements() {

    int numberOfElements = -1;
    //get a list of columns to be retrieved, we need all of them
    String[] columns = {MyHelper.COLUMN_VALUE, MyHelper.COLUMN_DATE_AT};
    //make a simple query with dbname, columns and all other params as null
    Cursor cursor = mDatabase.query(MyHelper.TABLE_NAME, columns, null, null, null, null, null);
    if (cursor != null && cursor.moveToFirst()) {
        numberOfElements = cursor.getCount();
        return numberOfElements;
    }
    return numberOfElements;
}
public ArrayList<Datastream> readDatastreams()
{
    //init an empty array list
    ArrayList<Datastream> listDatastream = new ArrayList<>();

    //get a list of columns to be retrieved, we need all of them
    String[] columns = {MyHelper.COLUMN_VALUE, MyHelper.COLUMN_DATE_AT};
    //make a simple query with dbname, columns and all other params as null
    Cursor cursor = mDatabase.query(MyHelper.TABLE_NAME, columns, null, null, null, null, null);
    if (cursor != null && cursor.moveToFirst()) {
        do {
            //create a new Datastream object and retrieve the data from the cursor to be stored in this Datastream object
            Datastream datastream = new Datastream();
            //each step is a 2 part process, find the index of the column first, find the data of that column using
            //that index and finally set our blank Datastream object to contain our data
            datastream.setCurrent_value(cursor.getString(cursor.getColumnIndex(MyHelper.COLUMN_VALUE)));
            long valueAtMilliseconds = cursor.getLong(cursor.getColumnIndex(MyHelper.COLUMN_DATE_AT));
            datastream.setCurrent_valueAt(valueAtMilliseconds != -1 ? new Date(valueAtMilliseconds) : null);
            //add the datastream to the list of datastream objects which we plan to return
            listDatastream.add(datastream);
        }
        while (cursor.moveToNext());
    }
    return listDatastream;
}

//delete all rows from our table
public void deleteData() {
    mDatabase.delete(MyHelper.TABLE_NAME, null, null);
}

public long insertData(String value, String valueDate) {
    SQLiteDatabase db = mHelper.getWritableDatabase();
    ContentValues cv = new ContentValues();
    cv.put(MyHelper.COLUMN_VALUE, value);
    cv.put(MyHelper.COLUMN_DATE_AT, valueDate);
    //ID indicates the row id that was inserted if successfull
    long id = db.insert(MyHelper.TABLE_NAME, null, cv);
    return id;
}

public String getColumnValueLast() {
    SQLiteDatabase db = mHelper.getWritableDatabase();
    String[] columns = {MyHelper.COLUMN_VALUE};
    Cursor cursor = db.query(MyHelper.TABLE_NAME, columns, null, null, null, null, null );

    String lastValue = "-1";
    if (cursor.moveToLast()) {
        int index1 = cursor.getColumnIndex(MyHelper.COLUMN_VALUE);
        String value = cursor.getString(index1);
        lastValue = value;
    }
    return lastValue;
}

static class MyHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "MyDB";
    private static final String TABLE_NAME = "TableValue";
    private static final int DB_VERSION = 2;
    private static final String COLUMN_UID = "_id";
    private static final String COLUMN_VALUE = "current_value";
    private static final String COLUMN_DATE_AT = "at";
    private static final String CREATE_TABLE = "CREATE TABLE "
            + TABLE_NAME
            + " ("
            + COLUMN_UID
            + " INTEGER PRIMARY KEY AUTOINCREMENT, "
            + COLUMN_VALUE
            + " VARCHAR(100), "
            + COLUMN_DATE_AT
            + " VARCHAR(100));";
    private static final String DROP_TABLE = "DROP TABLE IF EXISTS " + TABLE_NAME;
    private Context context; //mContext;

    public MyHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
        // or mContext = context
        this.context = context;
        L.t(context, "constructor called");
    }

    @Override
    public void onCreate(SQLiteDatabase db) {

        try {
            db.execSQL(CREATE_TABLE);
            L.t(context, "onCreate called");
        } catch (SQLException e) {
            L.t(context, "" + e);
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        try {
            L.t(context, "onUpgrade called");
            db.execSQL(DROP_TABLE);
            onCreate(db);
        } catch (SQLException e) {
            L.t(context, "" + e);
        }
    }
}

}


Q: why the output of the expression --- 'a' and 'e' and 'i' and 'o' and 'u' in 'eiou' --- is true? 'a' and 'e' and 'i' and 'o' and 'u' in 'eiou'
true

However,
'a' and 'e' and 'i' and 'o' and 'u' in 'aeio'
false

what is the problem?

A: if 'a' and 'e' and 'i' and 'o' and 'u' in 'eiou'

is equivalent to
if ('a') and ('b') and ('i') and ('o') and ('u' in 'eiou')

in which all the first 4 expressions 'a', 'b', 'i' and 'o' evaluate to True.
The final expression ('u' in 'eiou') is True for the first statement, whereas 'u' in 'aeio' is False

A: emm... It is the way python evaluates conditional expressions. This is how it works:
'a' and 'e' and 'i' and 'o' and 'u' in 'eiou'
'a' -> a non-empty string always evaluates to True, so we got True.
and -> if the expression before 'and' evaluates to True, evaluate the next expression.
'e' -> True
and -> continue evaluation
'i' -> True
and -> continue evaluation
'o' -> True
and -> continue evaluation
'u' in 'eiou' -> True
So you got True.
The next expression:
'a' and 'e' and 'i' and 'o' and 'u' in 'aeio'
'a' -> True
and -> continue evaluation
'e' -> True
and -> continue evaluation
'i' -> True
and -> continue evaluation
'o' -> True
and -> continue evaluation
'u' in 'aeio' -> False
so you got a False.
If what you want is to check if all letters are in the string, you either 'a' in 'aeio' and 'e' in 'aeio' and ... or more efficiently: if set('aeiou').issuperset(('a', 'e', 'i', 'o', ...)).


Q: @register.filter in my code from django import template

register = template.Library()

class_converter = {
    "textinput":"textinput textInput",
    "fileinput":"fileinput fileUpload"
}

@register.filter#<--------
def is_checkbox(field):
    return field.field.widget.__class__.__name__.lower() == "checkboxinput"

@register.filter#<--------
def with_class(field):
    class_name = field.field.widget.__class__.__name__.lower()
    class_name = class_converter.get(class_name, class_name)
    if "class" in field.field.widget.attrs:
        field.field.widget.attrs['class'] += " %s" % class_name
    else:
        field.field.widget.attrs['class'] = class_name
    return unicode(field)

and register.filter  function is:
def filter(self, name=None, filter_func=None):
        if name == None and filter_func == None:
            # @register.filter()
            return self.filter_function
        elif filter_func == None:
            if(callable(name)):
                # @register.filter
                return self.filter_function(name)
            else:
                # @register.filter('somename') or @register.filter(name='somename')
                def dec(func):
                    return self.filter(name, func)
                return dec
        elif name != None and filter_func != None:
            # register.filter('somename', somefunc)
            self.filters[name] = filter_func
            return filter_func
        else:
            raise InvalidTemplateLibrary("Unsupported arguments to Library.filter: (%r, %r)", (name, filter_func))

so
@register.filter
def a():
    pass

is Equal
register.filter(name=None,filter_func=a)

yes??

A: Not exactly. The decorator syntax:
@register.filter
def a():
   pass

is syntactic sugar for:
def a():
    pass
a = register.filter(a)

So register.filter in this case will be called with the first positional argument, 'name' being your function. The django register.filter function handles that usage however and returns the right thing even if the filter is sent as the first argument (see the if callable(name) branch)
It's more common to make decorators that can take multiple arguments do so with the function to be decorated being the first positional argument (or alternately being function factories/closures), but I have a feeling the reason django did it this way was for backwards-compatibility. Actually I vaguely remember it not being a decorator in the past, and then becoming a decorator in a later django version.

A: No. Simple decorators take the function they decorate as a parameter, and return a new function.
a = register.filter(a)


Q: How to create a dialog with custom content like android in Zebble for Xamarin? I want to create a dialog for editing some field and I need to make custom content for dialog and get the response from it to reload the Data. So, I read all content about dialog and popup in link below
http://zebble.net/docs/alerts-and-dialogs
And then I test this code:
In another page I want to show the popup:
await Nav.ShowPopUp<CustomeDialogPage>();

My custom Zebble page:
<z-Component z-type="CustomeDialogPage"
         z-base="Page"
         z-namespace="UI.Pages"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:noNamespaceSchemaLocation="../.zebble-schema.xml">

  <Stack CssClass="customedialog">
     <Button Text="OK" />
  </Stack>

  </z-Component>

And then I create stylesheet for that
.customedialog {
    width: 300px;
    height: 100px;
    background: #ffffff;
    border: 2px;
    padding: 5px;
    margin-top: 100px;
}

but, I could not able to close the popup or add a title section for it and I do not know how I can get the result of it.
And it is a sample dialog I want to use it like below:

A: Zebble provides you with other overloads of the Nav pop-up methods to help you achieve that.
Host page:
var result = await Nav.ShowPopup<TargetPage, SomeType>();
// Now you can use "result".

Pop-up page's close button:
...
await Nav.HidePopup(someResultValue);

Notes:

*

*"SomeType" can be a simple type such as boolean or string, or it can be a complex class.

*The type of the object returned by the pop-up must match the one expected by the host parent page.
You can check out the full spec here: http://zebble.net/docs/showing-popup-pages


Q: How to double click any where on web page? Actions actions = new Actions(getDriver());

actions.moveByOffset(700,700);
actions.click().build().perform();

actions.moveByOffset(40,0);
actions.click().build().perform();

actions.moveByOffset(0,40);
actions.click().build().perform();

actions.moveByOffset(0,0);
actions.doubleClick().build().perform();

I can make it click but can't make it double click.
Do you have any idea ? How can i change this part of code .I need to double click any where on web page. Just a double click action .
actions.moveByOffset(0,0);
actions.doubleClick().build().perform();

A: As per the Java Docs of current build of Selenium Java Client v3.8.1 you cannot use public Actions doubleClick() as the documentation clearly mentions that DoubleClickAction is Deprecated. Here is the snapshot :

Hence you may not be able to invoke doubleClick() from Package org.openqa.selenium.interactions
Solution :
If you need to execute doubleClick() two possible solutions are available as follows :

*

*Use Actions.doubleClick(WebElement)

*Use JavascriptExecutor to inject a script defining doubleClick().

A: You have to pass element argument to doubleClick() menthod.
actions.doubleClick(anyClickableWebElement).build().perform();


Q: how to detect the cases that fulfill A ∈ B, but B ∉ A I have a dataset that looks like this:

It show the relationship among the dataset.
1). for col1, it means: all the variables in cy1.CSV are also in the dataset "cy1.CSV", "cy24.CSV", "cy6.CSV".
2) dov.CSV: all the variables in dov.CSV are also in the dataset "dov.CSV", "dov_1.CSV"
2) dov_1.CSV: all the variables in dov_1.CSV can only be found in the dataset "dov_1.CSV"
df<-structure(list(cy1.CSV = c("cy1.CSV", "cy24.CSV", "cy6.CSV"),
    cy2.CSV = c("cy2.CSV", NA, NA), cy24.CSV = c("cy1.CSV", "cy24.CSV",
    "cy6.CSV"), cy3.CSV = c("cy3.CSV", NA, NA), cy6.CSV = c("cy1.CSV",
    "cy24.CSV", "cy6.CSV"), dlt.CSV = c("dlt.CSV", NA, NA), dm.CSV = c("dm.CSV",
    NA, NA), dov.CSV = c("dov.CSV", "dov_1.CSV", NA), dov_1.CSV = c("dov_1.CSV",
    NA, NA), ds.CSV = c("ds.CSV", "ds_1.CSV", NA), ds_1.CSV = c("ds.CSV",
    "ds_1.CSV", NA)), row.names = c(NA, -3L), class = c("tbl_df",
"tbl", "data.frame"))

Is it way we can find cases that fulfill: A ∈ B, but B ∉ A, in out example. dov.CSV belong to dov_1.CSV, dov_1.SCV not belong to dov.CSV. Maybe find a way to put what we find into a list or data.frame.

A: We can use the column names of df to check whether each file is %in% each column inside an sapply. This will give us a square matrix which tells us whether each file contains every other file.
This way, it is straightforward to use array indexing to get the files which contain other files:
tab <- `rownames<-`(sapply(df, function(x) names(df) %in% x), names(df))
ind <- which(tab, arr.ind = TRUE)
AinB <- data.frame(item = names(df)[ind[,2]], contains = names(df)[ind[,1]])

AinB
#>         item  contains
#> 1    cy1.CSV   cy1.CSV
#> 2    cy1.CSV  cy24.CSV
#> 3    cy1.CSV   cy6.CSV
#> 4    cy2.CSV   cy2.CSV
#> 5   cy24.CSV   cy1.CSV
#> 6   cy24.CSV  cy24.CSV
#> 7   cy24.CSV   cy6.CSV
#> 8    cy3.CSV   cy3.CSV
#> 9    cy6.CSV   cy1.CSV
#> 10   cy6.CSV  cy24.CSV
#> 11   cy6.CSV   cy6.CSV
#> 12   dlt.CSV   dlt.CSV
#> 13    dm.CSV    dm.CSV
#> 14   dov.CSV   dov.CSV
#> 15   dov.CSV dov_1.CSV
#> 16 dov_1.CSV dov_1.CSV
#> 17    ds.CSV    ds.CSV
#> 18    ds.CSV  ds_1.CSV
#> 19  ds_1.CSV    ds.CSV
#> 20  ds_1.CSV  ds_1.CSV

To find instances in which A is in B but not vice versa, we do the same thing except we are looking for the indices where tab is different from its transpose:
ind2 <- which(tab & !t(tab), arr.ind = TRUE)
AinBnotBinA <- data.frame(item = names(df)[ind2[,2]],
                          contains = names(df)[ind2[,1]])

AinBnotBinA
#>      item  contains
#> 1 dov.CSV dov_1.CSV

Created on 2020-11-25 by the reprex package (v0.3.0)


Q: How to stop Music app from automatically launching when CD is inserted on MacOS Catalina I am presently running MacOS Catalina (10.15.1).

*

*Within System Preferences, I have set CD's to do nothing upon being inserted:

*Within the Music app preferences, there is NO option to disable the app from opening when a CD is inserted:

The only options available in the highlighted dropdown are:

*

*Show CD

*Play CD

*Import CD

*Import CD and eject

*Ask to Import CD.

Why Apple would have one setting that informs the computer not to do something, but another that overrides that confounds me.
My issue is that I don't want the app to start when I insert a CD and I don't know how to resolve this, short of deleting the entire app because it's getting to be very annoying.


Q: WkHtmlToPdf Unreadable Fonts I installed wkhtmltopdf in a VPS/Centos .
But it seems that it cannot find the fonts (I have all type1 and  fonts-75dpi installed).
In php, this is the result of
exec(wkhtmltopdf http://www.google.com test.pdf);

A: This is the solution for Cento6
yum install libXext  libXrender  fontconfig  libfontconfig.so.1
yum install urw-fonts

A: For if anyone interested, I solved my problems by installing true type fonts. After that wkhtmltopdf was able to display these fonts.
Ubuntu (18.04)
apt install fonts-droid-fallback ttf-dejavu fonts-freefont-ttf fonts-liberation ttf-ubuntu-font-family

Alpine Linux (3.9)
apk add ttf-dejavu ttf-droid ttf-freefont ttf-liberation ttf-ubuntu-font-family


Q: Looking for an analogue to "geography" but for man-made spaces Suppose I was walking through a maze-like building complex, I might say,
"The _____ of this place is confounding."
I'm looking for that word. "Geography" doesn't feel right to me since it usually refers to natural spaces. Maybe you can refer to the geography of a city (still sounds a little weird), but of a single building?
I've had two suggestions so far, neither of which I like so much.

*

*"Layout" - this one is close to what I'm talking about, but it's more concrete than I want. When you talk about the layout of a space, you are referring to the relative placement of different elements in that very space. I need something more lofty; something that suggests some kind of conceptual context. I want to draw all of the listener's past experiences in layouts of spaces into her current experience of this one.

*"(Urban) design" - this one has that conceptual context, but not in the direction that I want. When you refer to the design of the space you draw the listener's understanding of the humans behind the space into their experience of the space itself. The conceptual context is the intentionality, unintentionality, and interplay of designs within the process of the space's creation. I'm not interested in that process, only the experience of a person in the space, now.

I understand that what I'm looking for is very specific, and it likely does not exist, but maybe it does. Maybe you know this word, or maybe I need to make it up.

A: How about this:
The architecture of this place is confounding.
IMHO, architecture is a concept that includes anything about human-made structures, from placement of walls and furniture to the color of the carpets and means the process of planning and creating those structures as well as their current state.

A: topography
/təˈpɒɡrəfi,tɒˈpɒɡrəfi/
Oxford Languages describes it as below:
noun: topography
the arrangement of the natural and artificial physical features of an area.
"the topography of the island"
Although it is worth mentioning that even though it has technical connotations in Geography, I think it may be suited to your requirements.

A: Urban Geography
Since much urban growth, especially in earlier times, follows no discernible plan, the term urban geography has emerged to denote the study of urban spaces, both natural and human-made.

The book also focuses on such topics as the locations, spacing, and size of urban settlements. A section of the book discusses the characteristics of capital cities like the city of London. — James H. Johnson, W. B. Fisher, Urban Geography: An Introductory Analysis, 2013.


Q: App icon is not showing in CallKit UI I have configured my Provider Configuration for CallKit iOS. In which I have also set 'iconTemplateImageData' for displaying app icon in CallKit UI. But app icon is not showing. It shows a white square box.

Provider Configuration Code:
    CXProviderConfiguration *configuration = [[CXProviderConfiguration alloc] initWithLocalizedName:[NSString stringWithFormat:@"%@\n", _title]];
    configuration.maximumCallGroups = 1;
    configuration.maximumCallsPerCallGroup = 1;
    UIImage *callkitIcon = [UIImage imageNamed:@"AppIcon"];
    configuration.iconTemplateImageData = UIImagePNGRepresentation(callkitIcon);

    _callKitProvider = [[CXProvider alloc] initWithConfiguration:configuration];
    [_callKitProvider setDelegate:self queue:nil];

    _callKitCallController = [[CXCallController alloc] initWithQueue:dispatch_get_main_queue()];

I have used AppIcon images in 'Images.xcassets' with sizes: -
1x: 40*40, 2x: 80*80, 3x: 120*120
Please help why my app icon is not showing.
Thanks in advance.

A: This is likely because you are using your AppIcon image, which is a fully opaque image, i.e. no part of that image is transparent or has alpha=0.
To get the desired effect, you have to use a different image which is partly (or mostly) transparent. The native in-call UI will only use the alpha channel of the image you provide, so it ignores colors. I suggest following the example in the Speakerbox sample app and providing a secondary PNG image in your image asset catalog with transparency.

A: You need to use below code in order to set app name and app icon for incoming VOIP calls
let localizedName = NSLocalizedString("App-Name", comment: "Name of application")
let providerConfiguration = CXProviderConfiguration(localizedName: localizedName)
providerConfiguration.iconTemplateImageData = UIImage.init(named: "appicon-Name")?.pngData()

Note: Your app icon must be transparent. result will be like in below image


Q: SSIS package fails when run as scheduled job but succeeds if run stand alone I've a Master package which has the scheduling of all the Jobs to run on a daily basis. Couple of my packages are failing when deployed on the server (its a file system deployment). The SSIS packages runs fine on my development machine or if run stand alone on the server., but strangely they fail when run as part of the scheduled job. I've SQL logging enabled and the error is pretty straightforward to interpret and sort out, however when I try to debug in the development environment it runs fine. I have an environment variable which holds the connection string and the SSIS package deployment is a file deployment with SQL logging enabled for all the Jobs. The problem is Im unable to replicate the error on my dev machine as the import takes place without any issue but its only when it runs as part of the scheduled job when it fails. Also it truncates the table fine but while importing the data it fails with data truncation error.
I'm unable to figure out what I'm missing here, any help will be very much appreciated.
SSIS sql error log from dbo.sysssislog table :
Anz_Isis_Cfv_Import_TblRefSDGPLHierarchyBU  2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 Beginning of package execution.
Anz_Isis_Cfv_Import_TblRefSDGPLHierarchyBU  2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 Data conversion failed. The data conversion for column "vcrFlgActive" returned status value 4 and status text "Text was truncated or one or more characters had no match in the target code page.".
Anz_Isis_Cfv_Master 2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 Data conversion failed. The data conversion for column "vcrFlgActive" returned status value 4 and status text "Text was truncated or one or more characters had no match in the target code page.".
Anz_Isis_Cfv_Import_TblRefSDGPLHierarchyBU  2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 The "output column "vcrFlgActive" (71)" failed because truncation occurred, and the truncation row disposition on "output column "vcrFlgActive" (71)" specifies failure on truncation. A truncation error occurred on the specified object of the specified component.
Anz_Isis_Cfv_Master 2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 The "output column "vcrFlgActive" (71)" failed because truncation occurred, and the truncation row disposition on "output column "vcrFlgActive" (71)" specifies failure on truncation. A truncation error occurred on the specified object of the specified component.
Anz_Isis_Cfv_Import_TblRefSDGPLHierarchyBU  2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 An error occurred while processing file "\Svrau530csm02.oceania.corp.anz.com\infra\Markets Finance\CFV IN\tblRefSD_GPL_Hierachy_BU_20141114.csv" on data row 2.
Anz_Isis_Cfv_Master 2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 An error occurred while processing file "\Svrau530csm02.oceania.corp.anz.com\infra\Markets Finance\CFV IN\tblRefSD_GPL_Hierachy_BU_20141114.csv" on data row 2.
Anz_Isis_Cfv_Import_TblRefSDGPLHierarchyBU  2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The PrimeOutput method on component "Flat File Source" (1) returned error code 0xC0202092.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.
Anz_Isis_Cfv_Master 2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 SSIS Error Code DTS_E_PRIMEOUTPUTFAILED.  The PrimeOutput method on component "Flat File Source" (1) returned error code 0xC0202092.  The component returned a failure code when the pipeline engine called PrimeOutput(). The meaning of the failure code is defined by the component, but the error is fatal and the pipeline stopped executing.  There may be error messages posted before this with more information about the failure.
Anz_Isis_Cfv_Import_TblRefSDGPLHierarchyBU  2014-11-14 08:08:33.000 2014-11-14 08:08:33.000 End of package execution.

A: The error message "The data conversion for column "vcrFlgActive" returned status value 4 and status text "Text was truncated or one or more characters had no match in the target code page." would point to a data related problem: I would assume on the server, there is some data that is larger than the target column allows, but this is not there in your development environment.
E. g. a string of length 23 and your column crFlgActive has an SSIS DT_STR data type of length 20.
One way to find the data causing problems would be to configure the destination component to redirect records causing problems instead of failing. The redirection could be to a table, or maybe even just a CSV or Excel file.


Q: mongo join two collections and use aggregation im trying to get only those products for whom no order exists, so each product has an order id, these audit tables were linked to orders, but those orders are now deleted, i need to locate those products with no orders.
I know when doing aggregates if the joining collection has no records its not returning anything as "docs", but how can i get it to return me docs == empty or null only..
db.products.aggregate([

    {
        $match: {
            $and: [
                { "docs": { $exists: false } }
            ]
        }
    },
    {
        $lookup: {
            from: "orders",
            localField: "orderId",
            foreignField: "orderId",
            as: "docs"
        }
    },
   {
        $unwind:
       {
          path: "$docs",
          preserveNullAndEmptyArrays: true
       }
   },
   { $limit: 10 }
]).pretty()

A: db.products.aggregate([

    {
        $lookup: {
            from: "orders",
            localField: "orderId",
            foreignField: "orderId",
            as: "docs"
        }
    },

   { $match: { docs: [] },

   { $limit: 10 }
]).pretty()


Q: Nginx rewrites parent rules with same key in sub-files? Accessing the /etc/nginx/nginx.conf file I have the following rule:
server {}
http {

    access_log   logs/access.log  main;
    error_log    logs/error.log  error;

    include /etc/nginx/conf.d/*.conf;

In another file, called etc/nginx/conf.d/custom.conf, I have the code:
http {
    blablabla …

When NGINX loads the settings, will the HTTP code block that was inside NGINX.CONF be “merged” with the settings included below or will it simply be replaced?
In this scenario for example, will the LOGS continue to be saved in the folder even if CUSTOM.CONF doesn't implement anything about it?
My current issue:
I can't see the logs that should be printed in the error/access.log files, remembering that my application is generating a 500 HTTP error.

A: Even if you can have more then a single http block you should not do it. But having an http block in another http block IS NOT ALLOWED and will raise an error on startup. Just tested this on my instance. So you should check the output of nginx -T and check the configuration.
The NGINX configuration works in an hierarchical order. Means a directive you set in the http context can be overwritten in the server or location context if supported.


Q: Why is a controller not printing to console, when everything is most certainly running properly I have a main ViewController. I then added an extension (custom keyboard), and made a KeyboardViewController. In the viewDidLoad() method, I have tons of functions that are 100% running, and working properly. If I try t print anything to console using print() it doesn't work however, and I am stumped as to why it wouldn't.
Assuming it might have something to do with extension?

A: use (lldb) and po to print or display anything you want to console.

A: In case anyone runs into this, the problem is that the logging is happening from the main app, one solution is to run the extension, and all the print logs work as expected. Otherwise, you can also change debug settings.


Q: wp-admin list only parent posts When admin creates a post with five custom fields I creates 5 posts with post_parent id to main post. But these 5 posts are also showing in posts listing table which I want to hide.
In /wp-admin/edit.php where wordpress shows all posts (parent & child) under All/Publish I want to show only Parent posts having post_type = post because I am using other post types as well but only want to change view where post_type = post.
I knows for this I must need to edit core file, no matter I can. After searching in wp-admin/includes/class-wp-list-table.php I found
    /**
     * Generate the
 part of the table
     *
     * @since 3.1.0
     * @access protected
     */
    function display_rows_or_placeholder() {
        if ( $this->has_items() ) {
            $this->display_rows();
        } else {
            list( $columns, $hidden ) = $this->get_column_info();
            echo '
get_column_count() . '">';
            $this->no_items();
            echo '
';
        }
    }

which creates rows for posts list table but I can not found where to set condition & custom query :
IF (post_type == 'post'){
    // list only parent posts
}else{
    // do default behavior
}

I searched almost 3hrs but no solution found. Okay if it is not possible then can we show same Hierarchy for posts like for Pages parent/child relation.

A: After approx 4hrs research I found wordpress: how to add hierarchy to posts
which seem that wordpress need to implement such feature.