text:
Q: Update X-axis via zoom scale I am trying to create a dynamic x-Axis time scale by checking my current zoom scale.
It works on first load, but if I subsequently try to zoom in or out of the chart, my x-Axis doesn't response although I have declared the variable as a function and expect it to return the appropriate scale and axis every time a zoom action is called.
My code below. Thank you in advance.
d3.csv('data/sample.csv', function (data) {
    // sort out the data we'll be using
    data.forEach(function (d) {
        d.date = new Date(d.dateTime);
        d.Ranking = +d.weight;
    });

    // define the boundaries of the svg canvas
    var margin = {top : 30, right : 45, bottom : 30, left : 45},
    width = window.innerWidth - margin.left - margin.right,
    height = window.innerHeight - margin.top - margin.bottom;

    // define the scale for each axis
    var interval = 'hours';

    var xScale = d3.time.scale()
        .domain([d3.min(data, function (d) {
                    return d.date;
                }), d3.max(data, function (d) {
                    return d.date;
                })])
        .range([0, width])
        .nice();

    var xDaysScale = d3.time.scale()
        .domain([new Date(2014, 7, 1), new Date(2014, 7, 6)])
        .range([0, width])
        .nice();

    var xWeeksScale = d3.time.scale()
        .domain([new Date(2014, 7, 1), new Date(2014, 7, 31)])
        .range([0, width])
        .nice();

    var xMonthsScale = d3.time.scale()
        .domain([new Date(2014, 7, 1), new Date(2015, 0, 1)])
        .range([0, width])
        .nice();

    var yScale = d3.scale.linear().domain([0, 5]).range([height, 0]).nice();

    // define the axes
    var xAxis = d3.svg.axis()
        .scale(xScale)
        .ticks(d3.time.hours, 1)
        .orient('bottom');

    var yAxis = d3.svg.axis().scale(yScale).orient('left');

    // define the zoom behavior
    var zm = d3.behavior.zoom()
        .x(xScale)
        .scaleExtent([.1, 1024])
        .on('zoom', zoom);

    // initialize the tooltip, and append it to the body
    var tooltip = d3.select('body')
        .append('div')
        .attr('class', 'tooltip')
        .attr('id', 'tooltip')
        .style('opacity', 0);

    // initialize the chart
    var svg = d3.select('.graph')
        .attr('width', width + margin.left + margin.right)
        .attr('height', height + margin.top + margin.bottom)
        .append('svg:g')
        .attr('transform', 'translate(' + margin.left + ', ' + margin.top + ')');

    // append the manipulation areas to the chart
    svg.append('rect')
    .attr('class', 'zoom xy')
    .attr('width', width)
    .attr('height', height)
    .call(zm)
    .on('dblclick.zoom', null) // disable the standard shitty doubleclick zoom function
    .on('dblclick', function (d) { // use my own awesome zoom function, that resets the chart
        // reset the main scale
        zm.scale(1);
        zm.translate([0, 0]);

        // let's not forget to update the axes
        svg.select('.x.axis').call(xAxis);
        svg.select('.y.axis').call(yAxis);

        // apply the changes
        update();
    });

    // append the axes to the chart
    svg.append('svg:g')
    .attr('class', 'x axis')
    .attr('transform', 'translate(-' + width + ', ' + height + ')')
    .attr('transform', 'translate(0, ' + height + ')')
    .call(xAxis);

    // create the elements based on the data provided
    var elem = svg.selectAll()
        .data(data)
        .enter()
        .append('g')
        .attr('class', 'element')
        .attr('transform', function (d) {
            return 'translate(' + xScale(d.date) + ', ' + yScale(d.Ranking) + ')';
        });

    // we append the full text description as a HTML element, because, a text element is more expensive, and doesn't support line breaks
    elem.append('foreignObject')
    .attr('width', 200)
    .attr('height', 1000)
    .append('xhtml:div')
    .attr('class', 'fulltext')
    .html(function (d) {
        return d.content;
    })
    .style('opacity', 0);

    // function::zoom - handles the scaling, translation of the chart elements
    function zoom() {
        //svg.select('.x.axis').call(xAxis);
        //svg.select('.y.axis').call(yAxis);

        //update();

        console.log(interval);

        if (zm.scale() < 1) {
            //console.log('zooming OUT');

            if (interval == 'hours') {
                xAxis = d3.svg.axis().scale(xDaysScale).ticks(d3.time.days, 1).orient("bottom");
                zm.x(xDaysScale);
                interval = 'days';
            }
            else if (interval == 'days') {
                xAxis = d3.svg.axis().scale(xWeeksScale).ticks(d3.time.weeks, 1).orient("bottom");
                zm.x(xWeeksScale);
                interval = 'weeks';
            }
            else if (interval == 'weeks') {
                xAxis = d3.svg.axis().scale(xMonthsScale).ticks(d3.time.months, 1).orient("bottom");
                zm.x(xMonthsScale);
                interval = 'months';
            }
        }

        else if (zm.scale() > 1) {
            //console.log('zooming IN');

            if (interval == 'months') {
                xAxis = d3.svg.axis().scale(xWeeksScale).ticks(d3.time.weeks, 1).orient("bottom");
                zm.x(xWeeksScale);
                interval = 'weeks';
            }

            else if (interval == 'weeks') {
                xAxis = d3.svg.axis().scale(xDaysScale).ticks(d3.time.days, 1).orient("bottom");
                zm.x(xDaysScale);
                interval = 'days';
            }

            else if (interval == 'days') {
                xAxis = d3.svg.axis().scale(xScale).ticks(d3.time.hours, 1).orient("bottom");
                zm.x(xScale);
                interval = 'hours';
            }
        }

        svg.select('.x.axis').call(xAxis);
        svg.select('.y.axis').call(yAxis);
        update();
    }

    // function::resize - handles the responsive positioning and sizing of elements depending on the size of the viewport
    function resize() {

        // re-get the size of the window
        width = window.innerWidth - margin.left - margin.right,
        height = window.innerHeight - margin.top - margin.bottom;

        // re-set the size of the chart's range
        xScale.range([0, width]).nice();
        yScale.range([height, 0]).nice();

        // configure the chart to the new size
        d3.select('.graph')
        .attr('width', width + margin.left + margin.right)
        .attr('height', height + margin.top + margin.bottom);

        // re-set the size of the manipulation area
        svg.select('rect')
        .attr('width', width)
        .attr('height', height);

        // re-size and re-position the axes
        svg.select('.x.axis')
        .attr('transform', 'translate(0, ' + height + ')')
        .call(xAxis);

        // update the elements according to the resized elements
        update();
    }

    // function::update - handles all redrawing of the chart and checking of dynamic elements
    function update() {
        // re-position individual elements
        svg.selectAll('.element')
        .attr('transform', function (d) {
            if (interval == 'hours') {
                return 'translate(' + xScale(d.date) + ', ' + yScale(d.Ranking) + ')';
            }

            if (interval == 'days') {
                return 'translate(' + xDaysScale(d.date) + ', ' + yScale(d.Ranking) + ')';
            }

            if (interval == 'weeks') {
                return 'translate(' + xWeeksScale(d.date) + ', ' + yScale(d.Ranking) + ')';
            }

            if (interval == 'months') {
                return 'translate(' + xMonthsScale(d.date) + ', ' + yScale(d.Ranking) + ')';
            }

            //return 'translate(' + xScale(d.date) + ', ' + yScale(d.Ranking) + ')';
        });

        d3.selectAll('.fulltext')
        .style('opacity', function (d) {
            // hide or show the full text descriptions based on zoom level
            if (zm.scale() >= 1) {
                return 1;
            } else {
                return 0;
            }
        });
    }

    // add the event handler for resizing
    d3.select(window).on('resize', resize);

    // refresh once to make sure all the processing gets through
    update();
});

A: Declaring
xScale = returnScale()

will just call returnScale once, which doesn't sound like what you want. In your zoom() or update() you need to call returnScale() again, and then do
zm.x(xScale)

A: function zoom() {
    console.log('interval: ' + interval);
    console.log('zoom: ' + zm.scale());

    if (zm.scale() < 1) {
        if (interval == 'hours') {
            //xAxis = xDaysAxis;
            xDaysScale = d3.time.scale().domain([new Date(2014, 7, 1), new Date(2014, 7, 6)]).range([0, width]).nice();
            xAxis = d3.svg.axis().scale(xDaysScale).ticks(d3.time.days, 1).orient("bottom");
            zm.x(xDaysScale);
            interval = 'days';
        }
        else if (interval == 'days') {
            //xAxis = xWeeksAxis;
            xWeeksScale = d3.time.scale().domain([new Date(2014, 7, 1), new Date(2014, 7, 31)]).range([0, width]).nice();
            xAxis = d3.svg.axis().scale(xWeeksScale).ticks(d3.time.weeks, 1).orient("bottom");
            zm.x(xWeeksScale);
            interval = 'weeks';
        }
        else if (interval == 'weeks') {
            //xAxis = xMonthsAxis;
            xMonthsScale = d3.time.scale().domain([new Date(2014, 7, 1), new Date(2015, 0, 1)]).range([0, width]).nice();
            xAxis = d3.svg.axis().scale(xMonthsScale).ticks(d3.time.months, 1).orient("bottom");
            zm.x(xMonthsScale);
            interval = 'months';
        }
        else {
            //zm.x(xMonthsScale);
            //interval = 'months';
        }
    }
    else if (zm.scale() > 1) {
        if (interval == 'months') {
            //xAxis = xWeeksAxis;
            xWeeksScale = d3.time.scale().domain([new Date(2014, 7, 1), new Date(2014, 7, 31)]).range([0, width]).nice();
            xAxis = d3.svg.axis().scale(xWeeksScale).ticks(d3.time.weeks, 1).orient("bottom");
            zm.x(xWeeksScale);
            interval = 'weeks';
        }

        else if (interval == 'weeks') {
            //xAxis = xDaysAxis;
            xDaysScale = d3.time.scale().domain([new Date(2014, 7, 1), new Date(2014, 7, 6)]).range([0, width]).nice();
            xAxis = d3.svg.axis().scale(xDaysScale).ticks(d3.time.days, 1).orient("bottom");
            zm.x(xDaysScale);
            interval = 'days';
        }

        else if (interval == 'days') {
            //xAxis = xHoursAxis;
            xHoursScale = d3.time.scale()
                .domain([
                    //d3.min(data, function (d) { return d.date; }),
                    //d3.max(data, function (d) { return d.date; })
                    mindate, maxdate
                    ])
                .range([0, width])
                .nice();
            xAxis = d3.svg.axis().scale(xHoursScale).ticks(d3.time.hours, 1).orient("bottom");
            zm.x(xHoursScale);
            interval = 'hours';
        }
        else {
            //zm.x(xHoursScale);
            //interval = 'hours';
        }
    }

    svg.select('.x.axis')
        //.attr('transform', 'translate(0, ' + height + ')')
        .call(xAxis);
    svg.select('.y.axis').call(yAxis);

    update();
}


text:
Q: How can I use an UIScrollView in an Multiview-Application? I have:
- an AppDelegate class
- two viewController classes
- three nib files (MainWindow.xib, firstView.xib, secondView.xib)
I want:
The secondView.xib should have an UIScrollView inside, so that I can add a lot of stuff to the view and it can be scrolled down.
Where would I have to conform to the UIScrollViewDelegate protocol now? I feel the AppDelegate class is the wrong place, because its far away from that secondView and not all my views want to use a UIScrollView.

A: since UIScrollView is located in the secondView.xib I assume its functionality is limited to that view.  If you have an instance of UIViewController that serves as the controller for the secondView.xib then the best place to implement UIScrollViewDelegate would be on that UIViewController directly.  You are correct that implementing it on the AppDelegate doesn't make sense if you have a more specific derived controller where it should belong.  Hope this helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Django rest framework get one to many relationship data I have a django model named Event, which references Customer model.
event_name = models.CharField(max_length=200, unique=True)
customer = models.ForeignKey(customer_models.Customer, db_index=True,
    on_delete=models.SET_NULL,
    related_name='customer_events', null=True)
event_location = models.CharField(max_length=200, default='')
event_date = models.DateField()

I need to get the customer list along with the latest event name for each user in the API.
Customer serializers.py file is
class CustomerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Customer
        fields = '__all__'

Customer views.py file is
class CustomerViewSet(viewsets.ModelViewSet):
    queryset = Customer.objects.all()
    serializer_class = CustomerSerializer

How can I accomplish this?

A: In your Customer model you can have a property that returns the latest event name for a Customer instance:
class Customer(models.Model):
    ...

    @property
    def latest_event_name(self):
        """Return latest event name."""

        # self.customer_events.order_by('event_date').last()
        latest_event = self.customer_events.order_by('-event_date').first()

        return latest_event.event_name if latest_event else None

In your serializer you can then add a ReadOnlyField for latest_event_name:
class CustomerSerializer(serializers.ModelSerializer):

    latest_event_name = serializers.ReadOnlyField()

    class Meta:
        model = Customer
        fields = '__all__'


text: Q: Embedding Schwarzschild in FRLW Does there exist an exact metric in the literature for embedding the Schwarzschild metric in the Friedmann–Lemaître–Robertson–Walker metric? If so, please give a good reference. Thanks.


text:
Q: Splitting string into groups I'm trying to 'group' a string into segments, I guess this example would explain it more succintly
scala> val str: String = "aaaabbcddeeeeeeffg"
... (do something)
res0: List("aaaa","bb","c","dd","eeeee","ff","g")

I can thnk of a few ways to do this in an imperative style (with vars and stepping through the string to find groups) but I was wondering if any better functional solution could
 be attained? I've been looking through the Scala API but there doesn't seem to be something that fits my needs.
Any help would be appreciated

A: Make it one-liner:
scala>  val str = "aaaabbcddddeeeeefff"
str: java.lang.String = aaaabbcddddeeeeefff

scala> str.groupBy(identity).map(_._2)
res: scala.collection.immutable.Iterable[String] = List(eeeee, fff, aaaa, bb, c, dddd)

UPDATE:
As @Paul mentioned about the order here is updated version:
scala> str.groupBy(identity).toList.sortBy(_._1).map(_._2)
res: List[String] = List(aaaa, bb, c, dddd, eeeee, fff)

A: You can split the string recursively with span:
def s(x : String) : List[String] = if(x.size == 0) Nil else {
    val (l,r) = x.span(_ == x(0))
    l :: s(r)
}

Tail recursive:
@annotation.tailrec def s(x : String, y : List[String] = Nil) : List[String] = {
    if(x.size == 0) y.reverse
    else {
        val (l,r) = x.span(_ == x(0))
        s(r, l :: y)
    }
}

A: Seems that all other answers are very concentrated on collection operations. But pure string + regex solution is much simpler:
str split """(?<=(\w))(?!\1)""" toList

In this regex I use positive lookbehind and negative lookahead for the captured char

A: def group(s: String): List[String] = s match {
  case "" => Nil
  case s  => s.takeWhile(_==s.head) :: group(s.dropWhile(_==s.head))
}

Edit: Tail recursive version:
def group(s: String, result: List[String] = Nil): List[String] = s match {
  case "" => result reverse
  case s  => group(s.dropWhile(_==s.head), s.takeWhile(_==s.head) :: result)
}

can be used just like the other because the second parameter has a default value and thus doesnt have to be supplied.

A: You could use some helper functions like this:
val str = "aaaabbcddddeeeeefff"

def zame(chars:List[Char]) = chars.partition(_==chars.head)

def q(chars:List[Char]):List[List[Char]] = chars match {
    case Nil => Nil
    case rest =>
        val (thesame,others) = zame(rest)
        thesame :: q(others)
}

q(str.toList) map (_.mkString)

This should do the trick, right? No doubt it can be cleaned up into one-liners even further

A: A functional* solution using fold:
def group(s : String) : Seq[String] = {
  s.tail.foldLeft(Seq(s.head.toString)) { case (carry, elem) =>
    if ( carry.last(0) == elem ) {
      carry.init :+ (carry.last + elem)
    }
    else {
      carry :+ elem.toString
    }
  }
}

There is a lot of cost hidden in all those sequence operations performed on strings (via implicit conversion). I guess the real complexity heavily depends on the kind of Seq strings are converted to.
(*) Afaik all/most operations in the collection library depend in iterators, an imho inherently unfunctional concept. But the code looks functional, at least.

A: Starting Scala 2.13, List is now provided with the unfold builder which can be combined with String::span:
List.unfold("aaaabbaaacdeeffg") {
  case ""   => None
  case rest => Some(rest.span(_ == rest.head))
}
// List[String] = List("aaaa", "bb", "aaa", "c", "d", "ee", "ff", "g")

or alternatively, coupled with Scala 2.13's Option#unless builder:
List.unfold("aaaabbaaacdeeffg") {
  rest => Option.unless(rest.isEmpty)(rest.span(_ == rest.head))
}
// List[String] = List("aaaa", "bb", "aaa", "c", "d", "ee", "ff", "g")

Details:

*

*Unfold (def unfold[A, S](init: S)(f: (S) => Option[(A, S)]): List[A]) is based on an internal state (init) which is initialized in our case with "aaaabbaaacdeeffg".

*For each iteration, we span (def span(p: (Char) => Boolean): (String, String)) this internal state in order to find the prefix containing the same symbol and produce a (String, String) tuple which contains the prefix and the rest of the string. span is very fortunate in this context as it produces exactly what unfold expects: a tuple containing the next element of the list and the new internal state.

*The unfolding stops when the internal state is "" in which case we produce None as expected by unfold to exit.

A: Edit: Have to read more carefully. Below is no functional code.
Sometimes, a little mutable state helps:
def group(s : String) = {
  var tmp = ""
  val b = Seq.newBuilder[String]

  s.foreach { c =>
    if ( tmp != "" && tmp.head != c ) {
      b += tmp
      tmp = ""
    }

    tmp += c
  }
  b += tmp

  b.result
}

Runtime O(n) (if segments have at most constant length) and tmp.+= probably creates the most overhead. Use a string builder instead for strict runtime in O(n).
group("aaaabbcddeeeeeeffg")
> Seq[String] = List(aaaa, bb, c, dd, eeeeee, ff, g)

A: If you want to use scala API you can use the built in function for that:
str.groupBy(c => c).values

Or if you mind it being sorted and in a list:
str.groupBy(c => c).values.toList.sorted


text:
Q: archiving / copying all the values in column A to column C based on date archiving / copying all the values in column A to column C based on date. Also, if the date is change, a new set of values will be copied and the previous value won't be deleted.I was working on a daily schedule of every employee at the same time it will be recorded as their attendance based on the date. Can someone help me?
Example 1
Example 2 : if I change the date, the previous record won't get deleted and will copy a new set of values based on date
If I press the (save button) I want all the the values from column B2:B4 will be copied to column F2:F4 based on the date on column C1
The 2nd screenshot shows if I change the date and press again the (save button) the previous value won't get deleted and a new set of values will be copied based on the actual date on column C1

A: In order to solve your issue I suggest you to use Apps Script and write a script and use this function:
function dateFunction() {
  var sheet = SpreadsheetApp.getActiveSheet();
  var currDate = sheet.getRange("C1").getValue();
  var originRange = sheet.getRange("B2:B4");
  var headers = sheet.getDataRange().getValues()[0];
  var dateFound = false;

  for (var i=5; i<headers.length && !dateFound; i++) {
    if (currDate.toString() == headers[i].toString()) {
      originRange.copyTo(sheet.getRange(2, i + 1, 3));
      dateFound = true;
    }
  }

  if (!dateFound)
    SpreadsheetApp.getUi().alert("Date not found!");
}

The script works by gathering all the dates from your headers and will try to see if there's a match with the date from the C1 cell. If a match has been found, the values will be copied correspondingly, otherwise, an alert prompt will show up specifying that the date has not been found.
Now, you will need to link this function to a button so it will only be executed when you click it.
You can easily do that by inserting a drawing and shape/draw it so it will resemble a button of your liking. You will have to Save and Close it.

Then, when you right click on it the option of Assign a script will appear and you have to put the name of the function from above in there, as shown below:

So now, every time you press the Save button, the script will be executed.
Furthermore, I suggest you read the following links since they might help you:

*

*Apps Script Spreadsheet Service;

*Sheet Class .getDataRange();

*Range Class .copyTo().


text:
Q: Set value to attribute using jquery I want to add value to attribute. I found this one, but my requirments little different. I want to set value in function onclick="add('id', 5)".
onclick="cart.add('<?php echo $product['product_id']; ?>', here i want to set with jQuery);"

Please also view my code

A: A stronger solution:
Set the data-productid to both the input and the test button:

var cart = { // JUST TO TEST
  add : function(productid, val){
    alert(productid +' '+ val);
  }
}

$(function () { // DOM ready

  $('.qtyplus, .qtyminus').on('click',function(){
    var $qty    = $('.featured-shopping-qty');
    var currVal = Math.abs( parseInt($qty.val(), 10) );
    var isPlus  = $(this).hasClass("qtyplus");
    var calc    = currVal + (isPlus? 1 : -1)
    $qty.val( (!isNaN(calc) && calc>=0) ? calc : 0);
  });

  $(document).on("click", ".throwToBasket", function(){
    var productid = $(this).attr("data-productid");
    var val  = parseInt( $("input[data-productid='"+ productid +"']").val() , 10);
    cart.add(productid, val);
  });

});

  <input type="text" name="quantity" value="0" class="qty featured-shopping-qty" data-productid="aaaaa">

<input type="button" value="+" class="qtyplus">

<input type="button" value="-" class="qtyminus">

test


text:
Q: Subsonic foreign key returning collection? I'm just writing my first "Hello World" program using Subsonic, for which I've thrown together a simple little Customer/Invoice/InvoiceItem/Product database.
The connection was successfully made to the DB, and it generated all the right ActiveRecord classes.  But for some reason, the Invoice class has a property called Customers, which returns a collection of Customer objects, even though the Invoice table has a CustomerID field which has a foreign key to the Customer table.  I would have expected a Customer property returning a single Customer object.
Same thing is happening for all of my FKs.  I must be doing something wrong - but what?

A: That is expected behavior.  The first (and only) item in the Invoice.Customers collection will be the foreign key related Customer object.


text:
Q: 'Error converting value' when JSON DeserializeObject I have a piece of code which I can't find the issue in. I'm working with Visual Studio 2008 and developing using .Net CF 3.5.
I receive the following JSON string:
[
  {
    "id": 1,
    "DbServerInstance": "Ej8/Pz9ubnldPx9ePxk=",
    "DbServerUser": "Px4/Ez8/Pz8/DT9OfBo=",
    "DbServerPassword": "TWsYRiQ/PyM/ZT8/PzJZ",
    "DbServerDatabase": "PwVRczpEPz8aPz8/DnRD",
    "UserManualURL": "Pz8rNUd2PxdAPzM/Uxw/Wg==",
    "ApplicationName": "PzwAAm5MTks/Pz0obD9P"
  }
]

I also created the following classes:
public class JSONResponse{
    [JsonProperty(PropertyName = "id")]
    public int id { get; set; }

    [JsonProperty(PropertyName = "DbServerInstance")]
    public string dbServerInstance { get; set; }

    [JsonProperty(PropertyName = "DbServerUser")]
    public string dbServerUser { get; set; }

    [JsonProperty(PropertyName = "DbServerPassword")]
    public string dbServerPassword { get; set; }

    [JsonProperty(PropertyName = "DbServerDatabase")]
    public string dbServerDatabase { get; set; }

    [JsonProperty(PropertyName = "UserManualURL")]
    public string userManualURL { get; set; }

    [JsonProperty(PropertyName = "ApplicationName")]
    public string applicationName { get; set; }
}

public class JSONArray
{
    public IList<JSONResponse> Params { get; set; }
}

I try to deserialize using the following command:
List<JSONResponse> rp = JsonConvert.DeserializeObject<List<JSONResponse>>(returnString);

This give me the error:
{"Error converting value \"[\r\n  {\r\n    \"id\": 1,\r\n    \"DbServerInstance\": \"Ej8/Pz9ubnldPx9ePxk=\",\r\n    \"DbServerUser\": \"Px4/Ez8/Pz8/DT9OfBo=\",\r\n    \"DbServerPassword\": \"TWsYRiQ/PyM/ZT8/PzJZ\",\r\n    \"DbServerDatabase\": \"PwVRczpEPz8aPz8/DnRD\",\r\n    \"UserManualURL\": \"Pz8rNUd2PxdAPzM/Uxw/Wg==\",\r\n    \"ApplicationName\": \"PzwAAm5MTks/Pz0obD9P\"\r\n  }\r\n]\" to type 'System.Collections.Generic.List`1[louisapp.JSONResponse]'."}    System.Exception {Newtonsoft.Json.JsonSerializationException}
I searched, but can't find the issue and as I'm quite new to JSON, my knowledge is limited. Any input would be appreciated.
Edit:
The code which is calling the web api:
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
    request.Method = "GET";
    request.ContentType = @"application/json";
    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
    {
        if (response.StatusCode == HttpStatusCode.OK)
        {
            Stream stream = response.GetResponseStream();
            StreamReader sr = new StreamReader(stream);
            return sr.ReadToEnd();
        }
        else
        {
            return null;
        }
    }

A: Looks like the returnString is not in right json format. Looking at the exception the returnString having additional double quotes at begining and end \"[ ]\"
I have tried the same example and it throws the above exception
string returnString = "\"[\r\n {\r\n \"id\": 1,\r\n \"DbServerInstance\": \"Ej8/Pz9ubnldPx9ePxk=\",\r\n \"DbServerUser\": \"Px4/Ez8/Pz8/DT9OfBo=\",\r\n \"DbServerPassword\": \"TWsYRiQ/PyM/ZT8/PzJZ\",\r\n \"DbServerDatabase\": \"PwVRczpEPz8aPz8/DnRD\",\r\n \"UserManualURL\": \"Pz8rNUd2PxdAPzM/Uxw/Wg==\",\r\n \"ApplicationName\": \"PzwAAm5MTks/Pz0obD9P\"\r\n }\r\n]\"";

List<JSONResponse> rp = JsonConvert.DeserializeObject<List<JSONResponse>>(returnString);

After removing additional quotes, it started working
string returnString = "[\r\n {\r\n \"id\": 1,\r\n \"DbServerInstance\": \"Ej8/Pz9ubnldPx9ePxk=\",\r\n \"DbServerUser\": \"Px4/Ez8/Pz8/DT9OfBo=\",\r\n \"DbServerPassword\": \"TWsYRiQ/PyM/ZT8/PzJZ\",\r\n \"DbServerDatabase\": \"PwVRczpEPz8aPz8/DnRD\",\r\n \"UserManualURL\": \"Pz8rNUd2PxdAPzM/Uxw/Wg==\",\r\n \"ApplicationName\": \"PzwAAm5MTks/Pz0obD9P\"\r\n }\r\n]";

List<JSONResponse> rp = JsonConvert.DeserializeObject<List<JSONResponse>>(returnString);

A: List<JSONResponse> rp =    jserial.Deserialize<List<JSONResponse>>(returnString);

Try this one its working for us fine here


text:
Q: How to block Javascript alert|confirm|promt in UIWebView before render completed? There are multiple questions on SO already addressing similar issues but none answers my exact type of question. Most of the answers involves running a JS snippet and overloading the alert method as such: window.alert = function() {};
The problem I am having is that the webpage loaded (which I have no control over the content) opens an alert before the rendering of the whole page completes.
Because of this I cannot use the: - (void)webViewDidFinishLoad:(UIWebView *)webView delegate method to run the JS snippet. In addition running the same snippet in - (void)webViewDidStartLoad:(UIWebView *)webView won't do me any good since it executes before the DOM is loaded.
Similar questions:

*

*Capture (and prevent) alert() modal in UIWebView

*Can I handle alert inside UIWebViewDelegate?

*UIWebView: Can I disable the javascript alert() inside any web page?
Any pointers on this?

A: After experimenting a bit with the suggested solutions regarding injecting a Javascript I fell back on the native platform.
Since a UIWebView translates all Javascript alerts into native UIAlertViews it is fairly simple to block it on the native end. Looking into UIAlertView.h there is only one public method for showing an alert which is conveniently called: - (void)show;.
This method can easily be either overridden in a subclass or through a category. I ended up using a category since the documentation mentions a warning for subclassing UIAlertView.
@interface UIAlertView (Blocker)
@end

#import "UIAlertView+Blocker.h"

@implementation UIAlertView (Blocker)

- (void)show {
   return;
}
@end

Importing this category in the view controller that holds the UIWebView will block all instances of UIAlertView and in turn also all JS alerts.
I find this solution more robust since it does not rely on injecting Javascripts, changing HTML or using a third party library. It is also unrelated to timing (the JS-alert code can be in the header, body or in some third party lib).

A: It seems that the result may vary based on the rendering engine, there are a few ways, what seemed to work for me what this:
alert("something");
alert = function(){};
alert("awesome");

http://jsfiddle.net/g5S5M/
I know that the V8 engine that chrome uses is not the same as the one that firefox or IE use, so  when making complex web applications one has to really start thinking because not all browsers interpred javascript the sameway.
One thing that you might want to look at is third party libraries that override this function, as in if you tell alert to be blank and right after another script tells it not to be blank, so ether remove that library, change the execution order or modify that library.


text:
Q: Add pseudo class to nth-child with CSS I want to use hover so that the bottom border on odd divs is a different color from #75dcff. However, .card:hover div:nth-child(odd) does not work. Can I apply psuedo classes to nth-child elements?

.card {
  margin: 30px;
  padding: 20px 40px 40px;
  max-width: 500px;
  text-align: left;
  background: #fff;
  border-bottom: 4px solid #ccc;
  border-radius: 6px;
}

.card:hover {
  border-color: #75dcff;
}

.card:hover div:nth-child(odd) {
  border-color: #ff7c5e;
}

A: Your selector is incorrect. .card:hover div:nth-child(odd) is selecting odd-indexed divs that are decendants of a .card, but your structure suggests that these should be the same thing. Adjust your selector to match the odd elements on hover:

.card {
  margin: 30px;
  padding: 20px 40px 40px;
  max-width: 500px;
  text-align: left;
  background: #fff;
  border-bottom: 4px solid #ccc;
  border-radius: 6px;
}

.card:hover {
  border-color: #75dcff;
}

.card:nth-child(odd):hover {
  border-color: #ff7c5e;
}


text:
Q: Selenium CSS selector syntax for checking class and text both Question is for JAVA + Selenium:
My HTML is:

...

                            BART Times
                            Provider

...

...

...

...

...

...

EDIT:
All <section class="standard-component image-sequence-button"... have exact same structure and hierarchy (same attributes for all tags). The only thing that changes are the TEXT values of the tags(e.g. span)
PART1:
I'm looking for various elements inside the second section tag. So, What I'm trying to do is get the  which has a value BART Times because of the business requirement.
I already know how to get it via xpath:
My xpath (verified via firebug):
"//section//div[@class = 'sequence-region']//section[@class = 'standard-component text hide-section-separator-line']//span[@class = 'main-text' and text() = '%s']"

I can get the span tag via checking for %s values (e.g. BART Times).
However, due to design considerations, we've been told to use CSS only. So, I tried to come up with a CSS counterpart for the above xpath but did not find it.
The following CSS
"section div.sequence-region section.standard-component.text.hide-section-separator-line span[class=main-text]"

returns all the span tags under all the section tags.
Question1: How do I get the span tag which has a certain TEXT value (the %s part of xpath)?
Things I've tried for that last span tag which did not worked(according to the firebug):

*

*span.main-text[text='BART Times']
span[class=main-text][text='BART Times']
span.main-text:contains('BART Times')
span[class=main-text]:contains('BART Times')
span.main-text[text="BART Times"]
span[class=main-text][text="BART Times"]
span.main-text[text=\"BART Times\"]
span[class=main-text][text=\"BART Times\"]
span[text="BART Times"]
span[text=\"BART Times\"]
span:contains('BART Times')
span:contains("BART Times")
span:contains(\"BART Times\")
So, basically I want to put a check on BOTH class and TEXT value of the span tag in CSS selector.
Part 2:
Then I want to get the <section class="standard-component image-sequence-button"... element where I found the  and then find other elements inside that specific section tag
Question 2:
Assuming, I found the span tag in question 1 via CSS, how do I get the section tag (which is a super--- parent of the span tag)?
If CSS is not possible, please provide an xpath counterpart for this as a workaround for a while.

A: CSS selectors can't select based on text.  The answers to Is there a CSS selector for elements containing certain text? go into detail on why.
To select based on class and text in xpath: //span[contains(@class, 'main-text') and text() = 'BART Times']

A: Regarding question 1, it is not possible, as stated in the other answer here. This is another thread about the topic : CSS selector based on element text?
Regarding question 2, once again there is no such parent selector in XPath : Is there a CSS parent selector?. Now for the xpath counterpart, you can use parent axis (parent::*) or shortcut notation for the same (..), or put the span selector as predicate for the parent (the third example below) :
....//span[@class = 'main-text' and text() = '%s']/parent::*
....//span[@class = 'main-text' and text() = '%s']/..
....//*[span[@class = 'main-text' and text() = '%s']]

See the following thread for some better (yet more complicated) alternative to match element by CSS class using XPath, just in case you haven't came across link on this topic : How can I find an element by CSS class with XPath?


text:
Q: Why the request size increases 3 times? i am working with angular 8 and nodejs to upload files. i user formdata to transfer the file from angular to node. In node i use multer to parse the formdata(Content-Type is left empty).
The functionality works fine.
My question are:
Why does the request size increases 3 times ? the file is sent just as i receive it from the file input
example:
original file
request sent to node

*Is there a better way to send files between angular and node regarding the request size?


text:
Q: How to insert a set to a table? Let us suppose that I need to insert 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' as values of t1.c1. This is a possibility:
insert into t1(c1, c2, c3)
values
('a', 'c2val', 'c3val'),
('b', 'c2val', 'c3val'),
('c', 'c2val', 'c3val'),
('d', 'c2val', 'c3val'),
('e', 'c2val', 'c3val'),
('f', 'c2val', 'c3val'),
('g', 'c2val', 'c3val'),
('h', 'c2val', 'c3val');

However, if I intend to insert these into the table using an insert-select, then this will throw a syntax error:
insert into t1(c1, c2, c3)
select ('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h') as c1, t2.c2, t2.c3
from t2
where t2.c2 > t2.c3;

Instead, I have(?) to do it individually:
insert into t1(c1, c2, c3)
select 'a' as c1, t2.c2, t2.c3
from t2
where t2.c2 > t2.c3;

insert into t1(c1, c2, c3)
select 'b' as c1, t2.c2, t2.c3
from t2
where t2.c2 > t2.c3;

insert into t1(c1, c2, c3)
select 'c' as c1, t2.c2, t2.c3
from t2
where t2.c2 > t2.c3;

insert into t1(c1, c2, c3)
select 'd' as c1, t2.c2, t2.c3
from t2
where t2.c2 > t2.c3;

insert into t1(c1, c2, c3)
select 'e' as c1, t2.c2, t2.c3
from t2
where t2.c2 > t2.c3;

insert into t1(c1, c2, c3)
select 'f' as c1, t2.c2, t2.c3
from t2
where t2.c2 > t2.c3;

insert into t1(c1, c2, c3)
select 'g' as c1, t2.c2, t2.c3
from t2
where t2.c2 > t2.c3;

insert into t1(c1, c2, c3)
select 'h' as c1, t2.c2, t2.c3
from t2
where t2.c2 > t2.c3;

I had to write a LOT of this kind of stuff today and I wonder whether I could have done better with using the values as a set instead of writing an insert-select for each individual value.
EDIT:
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h' is not my actual data, which is in fact quite ugly and random. The letters were used solely as an example and we should not rely on their particular attributes.

A: This answer uses a CROSS JOIN which creates a Cartesian Product between the user defined data (letter values in this example) and the filtered data from table t2.
DECLARE @inMemTable as TABLE (someValue varchar(10))
INSERT INTO @inMemTable(someValue) values ('A'), ('B'), ('C'), ('D')

INSERT INTO t1(c1, c2, c3)
SELECT letters.someValue as c1, t2.c2, t2.c3
FROM t2 CROSS JOIN @inMemTable as letters
WHERE t2.c2 > t2.c3

A: not really sure what the issue is, would this work?
insert into t1(c1, c2, c3)
select c1, c2, c3
from
  (select
    c2, c3
  from
    t2
  where c2 > c3) cross join
(select 'a' as c1 union
select 'b' union
select 'c' union
select 'd' union
select 'e' union
select 'f' union
select 'g' union
select 'h' ) a

are you asking how to create a set given a bunch of ugly and random values?  If so, you can either put them in a table or just union them together.

A: Wrap your values clause as a derived table.
Select * from (
values
('a', 'c2val', 'c3val'),
('b', 'c2val', 'c3val'),
('c', 'c2val', 'c3val'),
('d', 'c2val', 'c3val'),
('e', 'c2val', 'c3val'),
('f', 'c2val', 'c3val'),
('g', 'c2val', 'c3val'),
('h', 'c2val', 'c3val')
) t(c1,c2,c3)

This will give you your set of value as a table on which you can apply as many conditions as you want.


text:
Q: Calling ACTION_IMAGE_CAPTURE intent inside onActivityResult does not work on Android 5.0.0 I have a button handler that calls ACTION_IMAGE_CAPTURE intent.
  Intent intCamera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
  intCamera.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, getImageUri(IMAGE_PATH));
  startActivityForResult(intCamera, 1);

Inside onActivityResult I also call ACTION_IMAGE_CAPTURE to continue taking pictures.
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    try {
        if(resultCode == Activity.RESULT_OK){
            Intent intCamera = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            intCamera.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, getImageUri(IMAGE_PATH));
            startActivityForResult(intCamera, 1);
        }
    } catch (Exception e){
        // Do something
    }
}

I'm having a problem with ASUS Android ver. 5.0.0
It starts of OK once fired inside the button handler, but once it is fired inside onActivityResult, somehow it will show a black camera screen then automatically stop. and I will receive a resultCode = 0 (Only happens in 5.0.0, I checked with 5.0.1 and it works and also in other succeeding versions).
It works though when I place delay on the intent inside onActivityResult before it is started but I'm not allowed to place a delay, I'm hoping if there is a flag or a method I could use to make this work.
I need to be able to shoot pictures continuously after clicking ok every shot. Bearing in mind that the solution should also support API8.


text:
Q: Do authorization based on path variable in AWS API Gateway I have an AWS API Gateway which uses Cognito User Pool for authentication. I want to implement fine grained control for who can access which endpoints.
This is my requirement:
User making the request charlie:
/api/charlie/board/1   -> Allow
User making the request daisy:
/api/charlie/board/1   -> Deny
charlie and daisy here are the Cognito usernames (which I can extract from the JWT).
I am thinking of 2 ways to achieve this:

*

*By writing a custom Lambda Authorizer (something like this: https://aws.amazon.com/blogs/security/building-fine-grained-authorization-using-amazon-cognito-api-gateway-and-iam/).

*My API Gateway is backed by Lambda function. Should I do this authorization in each of those lambda functions. I can extract the Cognito username from the Bearer token and the requested resource username from the path variable.
I'm leaning towards implementing #2. Is there a better way to do this?

A: My advice would depend on the scale and complexity of the api. I think the main tradeoff is the maintainabiltiy of the authorization logic vs the added latency and complexity of having a lambda authorizer. And there is a small cost element attached to the tradeoff.
For relatively small api's, there is not much added value in centralizing the authorization logic. It will probably only be more complex to add lambda authorizers and you suffer from increased latencies. There are small other benefits like you dont pay the API GW cost for unauthorized requests, but often these are negligible.
For bigger APIs with complex auth logic it might make sense though. And even then it might be even better to include a shared library to all your backend lambdas.
So based on your post I'd recommend either creating a shared auth library and import them into your lambda functions.


text:
Q: Find list in nested list with maximum number of highest numbers I am trying to find the list in nested list, which has the maximum number of highest numbers, as shown bellow:
test_list = [[200,1,100],[50,120,0],[40,300,0]]
desired output = [200,1,100]

[200,1,100] is the winner here, as out of its 3 digits, 2 are higher than the other lists 2 numbers. This would not be sequence sensitive however, for example if:
test_list = [[1,100,200],[1,200,100],[200,1,100],[50,120,0],[40,300,0]]
desired output =  [[1,100,200],[1,200,100],[200,1,100]]

Reason being that here all three constitue the "maximum" lineup of digits. Is there anyway other than creating all permutations and comparing them?
Edit: For further clarification, for the example above, the numbers in the nested list are 300>200>120>100> 50>40>1. So, which list in the nested list has the maxmimum number of highest numbers? [200,1,100]. Does there exist another list in the nested list, with a higher number of highest numbers? No. If [300,200,1] was in the nested list, it would have won.
To provide context, these are scores for a fuzzy match between a series of strings to find closest matches, each providing 3  scores in a list, in term listed in the list of all possible matches. This is my way of closest match between strings, comparing the fuzzy scores and taking the list with the highest possible scores out of the list.

A: Find maxes by defining:

*

*Defining a compare function

*Use the compare function as a key in max

Code
from functools import cmp_to_key

def compare(sublist1, sublist2):
    '''
        Comparator function

        With >, <, = defined to satisfy the
        requirements for comparing sublists
        the function:

        Returns:
            Positive when sublist1 > sublist2
            Negative when sublist1 < sublist2
            0        when sublsit1 == sublist2
    '''
    return sum(1 if x > y else -1 for x, y in zip(sorted(sublist1), sorted(sublist2)) if x != y)

def find_max(lst):
    # find max value in list (using custom compare function)
    # use cmp_to_key to key to convert compare function to key
    m = max(lst, key=cmp_to_key(compare))

    # Use list comprehension to get all values equal
    # max (equal when compare(m, x) == 0)
    return [x for x in lst if compare(m, x)==0]

Test
print(find_max([[200,1,100],[50,120,0],[40,300,0]]))
# Output: [[200, 1, 100]]

print(find_max([[1,100,200],[1,200,100],[200,1,100],[50,120,0],[40,300,0]]))
# Output [[1, 100, 200], [1, 200, 100], [200, 1, 100]]

print(find_max([[9, 9, 0], [1, 1, 1]]))
# Output: [[9, 9, 0]]

print(find_max([[100, 100, 44, 100, 100, 56, 38], [100, 100, 100, 100, 100, 100, 73], [100, 100, 100, 100, 100, 100, 73], [100, 100, 100, 100, 100, 56, 41], [100, 100, 100, 100, 100, 56, 41], [100, 100, 100, 100, 100, 56, 41]] ))
# Output: [[100, 100, 100, 100, 100, 100, 73], [100, 100, 100, 100, 100, 100, 73]]


text:
Q: Timing issue on mySQL INSERT with TRIGGER For an iPad app I have created a web service which creates a new table row in my teams table when the user starts the app. The PHP generates a unique ID and fills some other fields as well.
Additionally I have created a trigger on the teams table in mySQL on insert where a teamnumber is generated automatically depending on the already inserted rows for that specific day, project and group.
Unfortunately I seem to have a timing issue when inserting new rows to my table sometimes. If two apps create a team in the same second (milisecond?) the result of the mySQL trigger will be the same teamnumber for both apps. So instead of having teamnumber 1 and 2 both apps have teamnumber 1.
My teamtable looks something like this:
TeamID | pProject | group | teamnumber | languagecode | created_at

And the trigger for mySQL:
CREATE TRIGGER after_team_insert BEFORE INSERT ON teams

FOR EACH ROW
BEGIN

SELECT COUNT( * ) INTO @counter
FROM teams
WHERE DATE( created_at ) = DATE( NOW( ) )
AND teams.group = NEW.group
AND teams.pProject = NEW.pProject;

SET NEW.teamnumber = CAST(@counter AS UNSIGNED) + 1;

END;

I think my problem has something to do with parallel threads that insert rows into the database and therefor get a wrong count when the trigger is working.
Does anyone have a solution for this problem or do I have to use some kind of queue in PHP to prevent this doubling of teamnumbers?
Thanks in advance,
Carsten.

A: I guess you can use a lock table !
http://dev.mysql.com/doc/refman/5.0/fr/lock-tables.html

A: If, for any reason, you can't lock your table you can try to handle the problem differently:

*

*Add a unique constraint on the columns group / pProject / teamnumber.

*Handle any constraint error in your code, check if the teamnumber is the problem, and then try to reevaluate it.

*Ensure you're teamnumber has been set. If not, try again.

Not that clean, a bit tricky, but it should do the work if you don't mind team number 3 was inserted after team number 4.


text:
Q: Displaying multiple equations I want to display multiple lines of centered equations. Each equation has multiple equalities and inequalities, so aligning is not called for. All I want is display them one line at a time, centered, with not too much space between them. Is the only way to use multiple \begin{equation}\end{equation} environments? Surely there must be a more efficient way, but I can't seem to find any way to do this online. Here is an example:
$$(a_1,\ldots,a_n)M\subset(a_1,\ldots,a_{n+m})M\subsetneq M,$$
$$(a_{n+1},\ldots,a_{n+m})\frac{M}{(a_1,\ldots,a_n)M}\simeq\frac{(a_1,\ldots,a_{n+m})M}{(a_1,\ldots,a_n)M}\subsetneq\frac{M}{(a_1,\ldots,a_n)M}.$$

A: You are already using amssymb I hope. Why not look in to the amsmath manual (texdoc amsldoc from command prompt/line). It provides many environments for typing mathematics. For these two equations, you can use gather* (no number).
\documentclass[11pt,openany]{book}
\usepackage{amsmath,amssymb,showframe}   %% showframe for demo only
\begin{document}
\begin{gather*}
(a_1,\ldots,a_n)M\subset(a_1,\ldots,a_{n+m})M\subsetneq M,\\
(a_{n+1},\ldots,a_{n+m})\frac{M}{(a_1,\ldots,a_n)M}\simeq
  \frac{(a_1,\ldots,a_{n+m})M}{(a_1,\ldots,a_n)M}\subsetneq\frac{M}{(a_1,\ldots,a_n)M}.
\end{gather*}
\end{document}

If you have long equations, then you may even prefer multline environment. If you use mathtools package instead, it will load amsmath by itself along with extended macros.


text:
Q: How to add icons in notification area? How to add icons in notification area?

A: Use the NotifyIcon class in WinForms, or call the Shell_NotifyIcon() function in plain Win32.
EDIT: If you only want to implement a launcher for an installed application, there are hordes of free programs out there that can help you.


text:
Q: Concat arrays of objects I have few arrays with objects and I need to merge them in to one, but next code doesn't works, it return empty array:

let y = [{id:1, value: 'test1'}, {id:2, value: 'test2'}];
let z = [{id:3, value: 'test3'}, {id:4, value: 'test4'}];
let x = [{id:5, value: 'test5'}, {id:6, value: 'test6'}];

let arr = [];

arr.concat(...x,...y,...z);

console.log(arr);

A: Array.prototype.concat()

The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array

let y = [{id:1, value: 'test1'}, {id:2, value: 'test2'}];
let z = [{id:3, value: 'test3'}, {id:4, value: 'test4'}];
let x = [{id:5, value: 'test5'}, {id:6, value: 'test6'}];

let arr = [].concat(...x,...y,...z);

console.log(arr);


text:
Q: How to put space between barcode and text using barcode widget package? as you can see in the image the barcode and data text don't have space and I don't know how to put space in this barcode widget I'm using barcode widget

here is my code and im required to use code39 type of barcode
class Barcode extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
  return Column(
  children: [
    BarcodeWidget(
      barcode: Barcode.code39(),
      data: '0912658792',
      width: size(480),
      height: size(120),
      margin: EdgeInsets.only(
        bottom: size(60),
      ),
    ),
    BarcodeWidget(
      barcode: Barcode.code39(),
      data: '195795296',
      width: size(480),
      height: size(120),
      margin: EdgeInsets.only(bottom: size(60)),
    ),
    BarcodeWidget(
      barcode: Barcode.code39(),
      data: '4952687794',
      width: size(480),
      height: size(120),
      margin: EdgeInsets.only(bottom: size(60)),
    ),
  ],
);
}
}`

I really appreciate if someone help me, or recommend me other barcode package that can put space under the barcode, thank you.

A: Use This:

class Barcode extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
      return Column(
      children: [
        BarcodeWidget(
          barcode: Barcode.code39(),
          data: '\n 0912658792',
          width: size(480),
          height: size(120),
          margin: EdgeInsets.only(
            bottom: size(60),
            top: size(60)
          ),
        ),
        BarcodeWidget(
          barcode: Barcode.code39(),
          data: '\n 195795296',
          width: size(480),
          height: size(120),
          margin: EdgeInsets.only(bottom: size(60),top: size(60)),
        ),
        BarcodeWidget(
          barcode: Barcode.code39(),
          data: '\n 4952687794',
          width: size(480),
          height: size(120),
          margin: EdgeInsets.only(bottom: size(60),top: size(60)),
        ),
      ],
    );
    }
    }`

A: You can use a SizedBox between the different BarcodeWidget instances.
... (your earlier code here)
...
children: [
    BarcodeWidget(
      barcode: Barcode.code39(),
      data: '0912658792',
      width: size(480),
      height: size(120),
      margin: EdgeInsets.only(
        bottom: size(60),
      ),
    ),
    SizedBox(
      height: 40,
    ),
    BarcodeWidget(
      barcode: Barcode.code39(),
      data: '195795296',
      width: size(480),
      height: size(120),
      margin: EdgeInsets.only(bottom: size(60)),
    ),
...
...

A: i figure out the answer
 BarcodeWidget(
  barcode: Barcode.code39(),
  data: '195795296',
  width: size(480),
  height: size(120),
  margin: EdgeInsets.only(bottom: size(60)),
  style: TextStyle(height: 2.0),
),

add style with height to get the space that i want


text:
Q: Can I return null instead of an object when a class fails to be initiated? Is it possible to design a class constructor that destroys the object or sets it to null if it fails to initiate. For example in the code below - if a user isn't found in a database then it could be useful to set the object to Null (A)... or is it better to use a class member flag $found (B)?
<?php
class User {
    private $name = "";
    public  $found = true;

    function __construct($username) {
        if (!db_lookup_user($username)) {
            $this = null;           // A. This won't work - but can I return null instead of an object?
            $this->found = false;   // B. The alternative is to set a flag that indicates that the object is valid
        } else {
            $this->name = $username;
        }
    }
}

$myUser = new User("Donald Duck);
if (is_null($myUser)) { echo "User doesn't exist"; }
   ... or ...
if ($myUser->found == false) { echo "User doesn't exist"; }

A: You can use a Factory Pattern (https://en.wikipedia.org/wiki/Factory_method_pattern) (or something close to that)
<?php

class UserFactory {
    static function createUser($username) {
        if($username == 'something') {
            return new User();
        } else {
            return null;
        }
    }
}

class User {}

$user1 = UserFactory::createUser('something');
$user2 = UserFactory::createUser('somethingElse');
var_dump($user1,$user2);

output
object(User)#1 (0) {}
NULL

A: It's not possible to return null directly from within the __construct() method, but you can write a factory (or factory method) that returns null on failure, as Felippe showed above. But in general it's a dangerous pattern to return nullable values: in some moment you can just forget to check for null. You may like the null object pattern as an alternative.


text:
Q: load checkboxes in fixed columns I am loading checkboxes dynamically from knockout observable array. But it is loading only 1 checkbox per row. I want to load checkbox in 4 columns per row.

        <input style="display: inline-block;white-space: nowrap;overflow: hidden;" type="checkbox" data-bind="checked: name1" />

Here is link to fiddle
I tried using inline-block but doesnt help. I read something about control group but not sure how to implement it.
Someone please point me in right direction.

A: You can group the data as follow :
var groups = [];
var groupSize = 4
var group = [];
// create full groups
for (var index = 0; index < data.length; index++) {
     group.push(data[index])
     if (group.length == groupSize) {
         groups.push(group);
         group = [];
     }
}
// adds the rest
if (group.length) {
     groups.push(group);
}

and use this view :

                <input type="checkbox" data-bind="checked: name1" />

See fiddle
You could also create an computed that groups the data in automatically as here .

A: Try this:

            <input type="checkbox" data-bind="checked: name1" />

and in your js script:
 var data1 = [{
     row: [{
         name1: "one"
     }, {
         name1: "two"
     }, {
         name1: "three"
     }, {
         name1: "three"
     }]
 }, {
     row: [{
         name1: false
     }, {
         name1: true
     }, {
         name1: true
     }, {
         name1: false
     }]
 }];

Here's the live example.


text:
Q: change rout without reloading previous date angular js I show my search result data as below.

This page URL is "http://localhost:8081/#!/app/sanction-screening".  When user clicking the view button, I showed more data in a another page. View button code is
  view

After click view button page rout like this "http://localhost:8081/#!/app/sanction-screening-view/1"
In the view page controller i am using below code to access object
.config(["$stateProvider",function ($stateProvider) {
    $stateProvider.state("app.sanction-screening-view", {
        url: "/sanction-screening-view/:id",
        templateUrl:
          "modules/sanction-screening-view/sanction-screening-view.html",
        controller: "sanctionViewCtrl",
    });
},])

All functionalities working well. In the second page i added back button. when i click my back button, page rout to the search result page correctly. but search result is cleared(empty table). My back button code like
  $scope.goBack = function () {
    $state.go("app.sanction-screening");
  };

When I click the back button, I need to show last search result grid. How I do it, if u can please send the small example

A: I see 2 possible solutions:

*

*Whenever you search on the grid page, change the route to store the searched information, i.e. in the query string, something like .../app/sanction-screening?search=username. Now, whenever you initialize this grid page (also includes when you go back from the users page), you get the query string from the route and load the search result accordingly.

*Instead of polluting your route with query string, you store the state of the grid page (i..e search information) in local storage. For eg: you could store in local storage (key = <your-grid-name>, value = <your-grid-states, query-string, search terms, etc>). Now, same as above, while initializing the grid page, you take these saved data from the local storage, as per your grid name and load the search result accordingly.


text:
Q: cannot type at command prompt in mac single user mode I am trying to run applejack. At the bong, I press the command + s keys. The prompt comes up, but when I type, nothing happens. I have a Mac USB keyboard attached and a dynex USB mouse.
I tried resetting the PRAM & NVRAM according to the suggestions found here - essentially pressing the Command, Option, P and R buttons.
I can log in normally and use the mouse and keyboard. I'm not sure what to do next. Please keep in mind that I am a Mac novice.

Note that I have the following setup and intentions:

*

*Mac OS X Server Version 10.6.8 (Snow Leopard)

*I am trying to run applejack in preparation for updating to maverick.


text:
Q: Mandrill XMLHttpRequest Error - invalid Access-Control-Allow-Origin headers I have an app on Heroku at http://random-name.herokuapp.com that sends emails with Mandrill.  However, regardless of whether I'm running the app locally at localhost:5000 or remotely on Heroku, I throw the following error when trying to send emails:

XMLHttpRequest cannot load
  https://mandrillapp.com/api/1.0/messages/send.json. Response to
  preflight request doesn't pass access control check: A wildcard '*'
  cannot be used in the 'Access-Control-Allow-Origin' header when the
  credentials flag is true. Origin 'http://random-name.herokuapp.com' is
  therefore not allowed access.

There's a lot of documentation on Stack Overflow about this error (see CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true), and consequently, I set my express headers to the following:
app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "http://localhost:5000 http://random-name.herokuapp.com");
  res.header('Access-Control-Allow-Credentials', true);
  res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

However, this doesn't seem to solve the issue.  I couldn't find anything useful in Mandrill's documentation either.  I'm guessing I'm specifying the headers incorrectly, or perhaps they aren't even being used.  Any ideas?

A: Access-Control-Allow-Origin takes a single value, not a space separated list.
You need to return whatever the client sends in the Origin request header (test to make sure that is an acceptable origin to you first though!).


text:
Q: ActiveMQ Artemis error AMQ224065 explanation? In ActiveMQ Artemis 2.15.0 version, we are auto-creating queues. As in default auto-delete set to true ( unchanged ). We see following log time to time. From the log message it seems server tries to remove auto-created queue and fails since it has a 1 messages. My question is why broker tries to remove the queue when there are messages in queue ?
2020-10-22 02:48:23,599 ERROR [org.apache.activemq.artemis.core.server] AMQ224065: Failed to remove auto-created queue test:
ActiveMQIllegalStateException[errorType=ILLEGAL_STATE message=AMQ229215: Cannot delete queue test on binding test - it has 1 messages]

A: As you can imagine, the broker has lots of threads doing lots of different tasks. It's totally possible for the last message to be removed from the queue and the broker to start the process to delete the queue and in the mean-time another thread adds a message to the queue. This ERROR message would be logged in such a situation.
I recommend you disable auto-delete for both addresses and queues or at least set auto-delete-queues-delay and auto-delete-addresses-delay to a non-zero value (e.g. 5000). Auto deletion will be disabled by default in a future version of the broker.


text:
Q: Can't print value from array of objects Here I am filling the localStorage:
let storageObj = {};
storageObj.date = (new Date().toLocaleString().replace(", ","T"));
storageObj.url = this.responseURL;
localStorage.setItem(storageObj.date, storageObj.url);

In mounted() I am iterate all data from localStorage like:
for(let obj of Object.entries(localStorage))
{
    this.lastpasts.push(obj);
}

And placing every Object to lastpasts (located in data() {lastpasts : []}).
In template I want to print only url:

    {{el.url}}

But this code do not print nothing. Work only {{el}}. It's print in HTML block:
[ "24.06.2017T11:55:10", "362e9cc5-e7e6" ]
[ "24.06.2017T12:26:47", "b0f9f20d-7851" ]

Browser console do not have any errors.

A: In the chat session we managed to solve his issue.
It was caused by the fact, that he was using Array of Arrays instead of Array of Objects. Because Array can be used only with index, not field name, {{el.url}} was not working.
The code to get values from LocalStorage had to be changed to:
mounted() {
  for(let obj of Object.entries(localStorage)) {
    var x = {};
    x.url = obj[0];
    x.date = obj[1];
    this.lastpasts.push(x);
  }
}

Now, it is possible to use {{el.url}}


text:
Q: Aggregate functions in where clause MS Access I have multiples tables with Names and Ages like this:
| Name     | Age |
------------------
| Carlos   | 25  |
| Mauricio | 28  |
| Cesar    | 19  |
| Hernan   | 7   |

And I need to retrieve all the names that are above the average Age.
I tried
 select Name from Table1 where Age > avg(Age)

but I found that the where clause does not work with aggregate functions, so I tried
 select Name from Table 1 having Age > avg(Age)

But it does not work either.

A: You can do it with following query:
select Name from Table1 where Age > (select avg(Age) from Table1)


text:
Q: Why am I getting SIGTSTP error even for small inputs? I was trying to solve this problem https://www.spoj.com/problems/STPAR/ on spoj. I have written the code as per my knowledge. But, I don't know why I'm getting this error. Please help me figure out the bug in my code. Thanks in advance!!!
#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n;
    cin>>n;
    while(n!=0)
    {
        int i,arr[n];
        for(i=0;i<n;i++)
            cin>>arr[i];
        int temp=1;
        stack<int>s;
        i=0;
        while(arr[i]!=temp and i<n)
        {
            s.push(arr[i]);
            i++;
        }
        temp++;
        bool flag=false;
        while(true)
        {
            if(temp==n+1)
            {
                flag=true;
                break;
            }
            else if(!s.empty())
            {
                if(s.top()==temp)
                {
                    s.pop();
                    temp++;
                }
            }
            else if(i!=n-1)
            {
                if(arr[i+1]==temp)
                {
                    i++;
                    temp++;
                }
                else
                {
                    int j=i+1;
                    while(arr[j]!=temp and j<n)
                    {
                        s.push(arr[j]);
                        j++;
                    }
                    i=j-1;
                }
            }
            else if(!s.empty())
            {
                if((s.top()!=temp) and ((i!=n-1) and (arr[i+1]!=temp)))
                    break;
            }
        }
        if(flag)
            cout<<"yes";
        else
            cout<<"no";
        if(n)
            cout<<"\n";
        cin>>n;
    }
    return 0;

}
The input was :
5
5 1 2 4 3
0
Here are the input and output formats:
Input
There are several test cases. The first line of each test case contains a single number n, the number of love mobiles. The second line contains the numbers 1 to n in an arbitrary order. All the numbers are separated by single spaces. These numbers indicate the order in which the trucks arrive in the approach street. No more than 1000 love mobiles participate in the street parade. Input ends with number 0.
Output
For each test case your program has to output a line containing a single word "yes" if the love mobiles can be re-ordered with the help of the side street, and a single word "no" in the opposite case.

A: You have an endless loop in the while(true)
when:

*

*temp != n+1

*And s.empty() is false

*And s.top() !=temp
Maybe there are other errors...


text:
Q: convert xaml to c# Could you please help me convert something like this:
<TextBox Name="MyTextBox" Text = "{Binding RelativeSource={RelativeSource TemplatedParent}, Path=TextBox.Text}" />

to c# code.

A: It will be following
TextBox MyTextBox = new TextBox();
MyTextBox.Name = "MyTextBox";
Binding binding = new Binding("TextBox.Text");
binding.RelativeSource = new RelativeSource(RelativeSourceMode.TemplatedParent);
MyTextBox.SetBinding(TextBox.TextProperty, binding);


text:
Q: Finding the difference between two dateTimes in XSLT I have an XML file which includes some dates with start and end points, like shown as follows:
<start time="2016-02-21T00:59:06+02:00"/>
.....
.....
<end time="2016-02-22T02:24:38+02:00"/>

Question:
How to calculate the difference between two time attributes?

A: Your dates are in ISO format so in XSLT 2.0 you can do
xs:dateTime(end/@time) - xs:dateTime(start/@time)

The result is an xs:dayTimeDuration, which you can convert to seconds (for example) by doing
(xs:dateTime(end/@time) - xs:dateTime(start/@time)) div xs:dayTimeDuration('PT1S')

A:
I am getting the error: ... xsl:version: only 1.0 features are supported

Here's a purely XSLT 1.0 solution:
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<xsl:template match="event">
    <xsl:variable name="start">
        <xsl:call-template name="dateTime-to-seconds">
            <xsl:with-param name="dateTime" select="start/@time" />
        </xsl:call-template>
    </xsl:variable>

    <xsl:variable name="end">
        <xsl:call-template name="dateTime-to-seconds">
            <xsl:with-param name="dateTime" select="end/@time" />
        </xsl:call-template>
    </xsl:variable>

    <xsl:variable name="duration" select="$end - $start" />
    <xsl:variable name="d" select="floor($duration div 86400)"/>
    <xsl:variable name="t" select="$duration mod 86400"/>
    <xsl:variable name="h" select="floor($t div 3600)"/>
    <xsl:variable name="r" select="$t mod 3600"/>
    <xsl:variable name="m" select="floor($r div 60)"/>
    <xsl:variable name="s" select="$r mod 60"/>

    <xsl:copy>
        <xsl:copy-of select="name"/>
        <duration>
            <xsl:value-of select="$d"/>
            <xsl:text> days, </xsl:text>
            <xsl:value-of select="$h"/>
            <xsl:text> hours, </xsl:text>
            <xsl:value-of select="$m"/>
            <xsl:text> minutes and </xsl:text>
            <xsl:value-of select="$s"/>
            <xsl:text> seconds</xsl:text>
        </duration>
    </xsl:copy>
</xsl:template>

<xsl:template name="dateTime-to-seconds">
    <xsl:param name="dateTime"/>

    <xsl:variable name="date" select="substring-before($dateTime, 'T')" />
    <xsl:variable name="time" select="substring-after($dateTime, 'T')" />

    <xsl:variable name="local-time" select="substring($time, 1, string-length($time) - 6)" />
    <xsl:variable name="offset" select="substring-after($time, $local-time)" />

    <xsl:variable name="year" select="substring($date, 1, 4)" />
    <xsl:variable name="month" select="substring($date, 6, 2)" />
    <xsl:variable name="day" select="substring($date, 9, 2)" />

    <xsl:variable name="hour" select="substring($local-time, 1, 2)" />
    <xsl:variable name="minute" select="substring($local-time, 4, 2)" />
    <xsl:variable name="second" select="substring($local-time, 7)" />

    <xsl:variable name="offset-sign" select="1 - 2 * starts-with($offset, '-')" />
    <xsl:variable name="offset-hour" select="substring($offset, 2, 2) * $offset-sign" />
    <xsl:variable name="offset-minute" select="substring($offset, 5, 2) * $offset-sign" />

    <xsl:variable name="a" select="floor((14 - $month) div 12)"/>
    <xsl:variable name="y" select="$year + 4800 - $a"/>
    <xsl:variable name="m" select="$month + 12*$a - 3"/>
    <xsl:variable name="jd" select="$day + floor((153*$m + 2) div 5) + 365*$y + floor($y div 4) - floor($y div 100) + floor($y div 400) - 32045" />

    <xsl:value-of select="86400*$jd + 3600*$hour + 60*$minute + $second - 3600*$offset-hour - 60*$offset-minute" />
</xsl:template>

</xsl:stylesheet>

Demo: http://xsltfiddle.liberty-development.net/aiyndK

A:
I checked and found out that I can use XSLT version 2. Also by
times/dates I meant different in dates, which means how many days,
hours, minutes ans seconds.

Then I would suggest you do it along the lines of:
<xsl:variable name="duration" select="xs:dateTime(end/@time) - xs:dateTime(start/@time)" />
<xsl:value-of select="days-from-duration($duration)"/>
<xsl:text> days, </xsl:text>
<xsl:value-of select="hours-from-duration($duration)"/>
<xsl:text> hours, </xsl:text>
<xsl:value-of select="minutes-from-duration($duration)"/>
<xsl:text> minutes and </xsl:text>
<xsl:value-of select="seconds-from-duration($duration)"/>
<xsl:text> seconds</xsl:text>

Full demo: http://xsltfiddle.liberty-development.net/aiyndK/1

A: Using XSLT3.0 compliant Saxon processor, I use this (should work for 2.0 also):-
xs is xsd schema
<xsl:variable name="to" select="...to node value"/>
<xsl:variable name="from" select"...from node value"/>
<xsl:value-of select="days-from-duration(xs:dayTimeDuration(xs:date($to) - xs:date($from)))"/>


text:
Q: How to generate random questions and corresponding answers for quiz game? I'm making a quiz game and i want questions to be randomly generated. The problem is i dont know how to make corresponding answers to questions and how to make them not to repeat. Also problem is that i get columns by index in in the answers
questions = [("Was Einshtein a genius?", "B"), ("How old is Putin?", "C"), ("What is my favourite dish?", "D"),
 ("Why i broke up with my girl?", "A" )]

 answers =   [["A. He is a fool", "B. Definetly", "C. He's stupid", "D. He's a gay"],
  ["A. 65", "B. 48", "C. 69", "D. 61"],
  ["A. Pizza", "B. KFC Chicken", "C. Big tasty", "D. Lazania"],
  ["A. She cheated on me", "B. She stole my phone", "C. She broke my phone", "D. She broke ,y heart"]]

ques_ran = random.randint(0,3)
for i in questions:
    print(questions[ques_ran])
    for key in answers:
        print(key[ques_ran])
    b = input('Enter an asnwer ')

I expect that each of these four questions with corresponding answers will display randomly and they won't repeat(there should be all 4 present questions with answers displaying for 4 iterations, one question on one iteration)

A: Trying to keep multiple lists "in sync" always makes things more complicated.  Things will be easier if you combine the question, possible answers, and correct answer into a class, then put instances of that class into a single list.
Then you can use random.shuffle or random.sample to randomize your list of questions while avoiding duplicates.

A: Build a list that contains both the questions and answers.  There are lots of better ways to do this, but a quick fix given your current separate lists is to just zip them together.  Then you can use random.choice to select a single question/answer pair, or random.shuffle to iterate through all of them in random order, etc.
q, a = random.choice(list(zip(questions, answers)))
print(q[0])
print(a)
if input() == q[1]:
    print("Correct!")
else:
    print("Wrong!")

A: A possible implementation, if you want to ask all questions in a random order without repeats, could be to list all indices and shuffle them:
import random
order = list(range(len(questions)))
random.shuffle(order)

for i in order:
    print(questions[i][0])
    print('\n'.join(answers[i]))
    ans = input('answer: ')
    print('correct' if ans == questions[i][1] else 'incorrect')

NB. I would probably use a different logic to store the data though. Probably a single container with question, choices, correct answer.


text:
Q: Expand/Collapse functionality between components I have 2 different components where I am using Angular - Expansion Panel for expandable summary view.
I am able to integrate <mat-expansion-panel> to individual components successfully.
I need help to make Component2.html as parent of Component1.html (Expand within expand- Please see below Image)

*

*Component 1 should be able to expand and collapse independently to show data

*Component 2 should embed Component 1 within itself, so when Component 1 is expanded it can show its data and display remaining Child components
NOTE - Both the component has Sibling relation, no parent child or child - parent
Component1.html

        <mat-accordion>
          <mat-expansion-panel (opened)="doExpand = true"
                             (closed)="doExpand = false">
          <mat-expansion-panel-header>
            <mat-panel-title>

data

      </mat-panel-title>
      <mat-panel-description>

          <inline-misal-edit
                        [(field)]="data.name" [elementType]="a.bName" (fieldChange)="dataModified(data)"
                        cols="30" rows="1"></inline-misal-edit>

      </mat-panel-description>
    </mat-expansion-panel-header>

news

{{data.news?.created | news}}

      </mat-expansion-panel>
    </mat-accordion>

Component2.html

    <mat-accordion>
        <mat-expansion-panel (opened)="doExpand = true"
                             (closed)="doExpand = false">
          <mat-expansion-panel-header>
            <mat-panel-title>
              misal Id
            </mat-panel-title>
            <mat-panel-description>

{{misal.id || 'new'}}

            </mat-panel-description>
          </mat-expansion-panel-header>

{{misal.data[0].name}}

Country Pass

Plugins Program

            <north-dhamma[(misal)]="misal" [editMode]="editMode" (misalChange)="recordModified.emit()"></registry-number>

Related Plugins Program

            <land-hole></land-hole>

                </mat-expansion-panel>
      </mat-accordion>

.ts file
  panelOpenState = true;

UPDATE
The answer given below by Robbie works for parent - child component relation  but not for the sibling component

A: One way to do this is using a shared service - https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service
However I find the following solution much simpler, it allows to share data between 2 siblings.
app-sibling2.component.ts
import { AppSibling1Component } from '../app-sibling1/app-sibling1.component';

export class AppSibling2Component {
   @Input() data: AppSibling1Component;
   ...
}

In you parent component template:

<app-sibling1 #data></app-sibling1>

<app-sibling2 [data]="data"></app-sibling2>

I believe this is what you are looking for. Let me know if you have any questions

A: You should be able to add your child component right after the close tag of mat-expansion-panel-header
<mat-accordion>
  <mat-expansion-panel>
    <mat-expansion-panel-header>
      <mat-panel-title>
        Parent Expansion
      </mat-panel-title>
    </mat-expansion-panel-header>

Content of parent

    <app-child></app-child>
  </mat-expansion-panel>
</mat-accordion>

https://stackblitz.com/edit/angular-5euuwx?file=src%2Fapp%2Fexpansion-overview-example.html

A: I am bit confused over there you want Component2.html as parent of Component1.html and you mentioned both the component has Sibling relation, no parent child or child - parent.
Keeping that in mind how about having a ExpansionWrapperComponent that wraps both Component1 and Component2 and incorporates the behavior - if Component2 is toggled Component1 must get toggled at the same time Component1 can be toggled separately too.
expansion-wrapper.component.html

    <ng-content select="app-component2"></ng-content>

    <ng-content select="app-component1"></ng-content>

expansion-wrapper.component.ts
import { AfterContentInit, Component, ContentChild, OnInit } from '@angular/core';
import { Component1Component } from '../component1/component1.component';
import { Component2Component } from '../component2/component2.component';

@Component({
  selector: 'app-expansion-wrapper',
  templateUrl: './expansion-wrapper.component.html',
  styleUrls: ['./expansion-wrapper.component.css']
})
export class ExpansionWrapperComponent implements OnInit, AfterContentInit {

  @ContentChild(Component2Component, { static: false }) component2: Component2Component;

  @ContentChild(Component1Component, { static: false }) component1: Component1Component;

  constructor() { }

  ngOnInit() {
  }

  ngAfterContentInit() {
    this.component2.panelStateChanged.subscribe(res => {
      this.component1.togglePanelState(res);
    });
  }

}

Where Component1 and Component2 contains separate expansion panel. With this Component1 is a sibling of Component2 and feels like embeded into Component2.
Check the application over stackblitz

A: I'm confused about what are your needs.

Component 2 should embed Component 1 within itself

What you are requiring is something like this
// component2.component.ts
@Component({
  selector: "component2",
  template: `
    <component1></component1>
  `,
  styles: []
})
export class Component2 {
}

Both the component has Sibling relation, no parent child or child - parent

But here, you want this.
// app.component.ts
@Component({
  selector: "app",
  template: `
    <component2></component2>
    <component1></component1>
  `,
  styles: []
})
export class AppComponent {
}

I guess what you want is something like this, demo. 2 sibling <mat-expansion-panel> as a display unit.


text:
Q: Placing User Input into Table and Sum the Total in Lua I'm attempting to make a script on my own that would be beneficial for technicians/salesmen in the field.  There are three products that make up this product line.  But the only difference between these products are the sizes.  Each size contains a certain amount of brackets required to mount them.  For the small, only one is necessary.  For the medium, two.  And for the large, four.
I want my script to issue a prompt asking the user for how many of each type of product, as any installation can have any amount of a mixture of these product sizes. (sorry if this is confusing, but hopefully my code below will help explain better.)  I would ideally like this script to take the amount of each product size needed, add them up and spit out the total amounts of brackets required for the installation.  Right now, I cannot figure out how badly I am butchering this code as I am new to programming.
Please review the code below and any help and/or suggestions is greatly appreciated.
function (t)
    local t = {}
    a,b = i,brackets
    io.write ("Enter Total Number of Small Products")
    answer = io.read()
    if answer then
        brackets = table.insert (t,#t+1,(answer * 1))
    end
    io.write ("Enter Total Number of Medium Products")
    answer = io.read()
    if answer then
        brackets = table.insert (t,#t+1,(answer * 2))
    end
    io.write ("Enter Total Number of Large Products")
    answer = io.read()
    if answer then
        brackets = table.insert (t,#t+1,(answer * 4))
    end
    local sum = 0
    for i,brackets in ipairs (t) do
        sum = sum + brackets
    end
    print (sum)
end

A: I see several issues here that I'd raise:

*

*Your code is all contained in an anonymous function. While this is syntactically valid, you haven't shown that this function is captured and eventually called. A simple script is largely written at file scope, although there are times when writing function main() --[[stuff happens]] end can make sense. Especially if instead of just writing main() you write something like pcall(main) to capture and handle any errors it threw.

*Your anonymous function is declared to take a parameter named t. That parameter is then immediately shadowed by the local variable named t, and cannot be accessed at all inside the function.

*You clearly know about local variables. So why are you using globals named a, b, i, brackets and answer?

*The variables a, and b are not used again, and i and brackets are shadowed by the locals created by the for loop later.

*You know about functions, so you should notice your repeated code that prompts and reads for a value, and collect that into a function.

*table.insert isn't documented to return a value.

*You are using t as an array, which is a pattern that table.insert already knows about so the second argument of #t+1 is redundant. If missing, that is where table.insert will put the value.

*You call table.insert, io.read, and io.write frequently. Current best practices suggest that copying those functions into local variables will speed up their access by eliminating the access to the global symbol table (to look up table) and then a second access to look up the function. Saying something like local insert,read,write = table.insert,io.read,io.write somewhere in the file scope will do the trick. Doing it the function scope will work, but will re-create those locals on every call to the function.

*You are using t as an array, and a pattern like t[#t+1] = expression is a very common idiom for simply appending an item to the array. Not only is it faster than calling table.insert (even after localizing the value), but it is also clearer.

*You don't appear to be using the individual counts of part sizes for anything else. So there really isn't any need to be keeping the array at all. Of course, a likely creaping feature would be to produce a report that summarizes the number of each size, the number of brackets, and then includes totals. In that case, keeping a table makes sense.

*At the command line, you are going to discover some of the mysteries of stream buffered I/O. In particular, stdout is line buffered (on linux and Windows by default, and almost certainly also on Mac) as long as the output is a terminal and not a file or pipe. Line buffered I/O is not guaranteed to be synchronized between streams. So your prompts are likely to not actually be visible to the user when you stop to read their answer. One way to work around this is to always print a newline, which will cause the entire line to be output. Another is to call io.flush() after each call to io.write().

*Put some consideration into error handling. Not just what happens if io.write fails, but what happens when your user answers "none" or "three" instead of the expected "0" or "3". Users do that. Your code uses an implicit conversion from string to number and will fail with a very messy error message if that conversion fails. Consider explicitly calling tonumber(), and then consider what to do when it returns nil. Even explicitly writing (tonumber(answer) or 0) * 3 is better than just answer * 3 because it converts all non-numbers into the number 0. Even better would be guide the user to valid entry.

A: The code you posted has a number of problems. If the only requirements you have are those you stated, the following script use a function to perform the input and the computation of the sum, which is returned as a result.
local function GetSum()
    local sum = 0
    local answer
    io.write ("Enter Total Number of Small Products: ")
    answer = io.read()
    if answer then
        sum = sum + tonumber( answer )
    end
    io.write ("Enter Total Number of Medium Products: ")
    answer = io.read()
    if answer then
        sum = sum + 2 * tonumber( answer )
    end
    io.write ("Enter Total Number of Large Products: ")
    answer = io.read()
    if answer then
        sum = sum + 4 * tonumber( answer )
    end
    return sum
end

print( GetSum() )

Note: the calls to the tonumber function are not necessary, since Lua coerces the string in answer into a number in that context, but in a bigger application it is useful to be explicit so that the reader can clearly spot that a type conversion is being done.


text:
Q: UpsertDE error with triggered API campaigns I have a data extension (Data Extensions > Lifecycle Campaigns > API Tables > Patient_Records_DB) that is used to capture send event data for one of our triggered campaigns. The send event capture is happening through the statement below. When I use the UpsertDE fuction and clear the data extension out before sending, the triggered campaign works fine. When there is data in the data extension and I use the UpsertDE function with the same data set, the triggered campaign errors out in the queue. I added the SendLogCount function to attempt to override the error, but this also errors out when the data extension already has data populated that is a match. Any thoughts?
  Set @SendLog = LookupOrderedRows("Patient_Records_DB",1,"AppointmentDateTime","FamilyID",@familyid)
  Set @SendLogCount = Rowcount(@SendLog)

IF @SendLogCount > 1 THEN
UpdateDE(
"Patient_records_DB",1,
"PatientID",@ApptSubscriberKey,
"PatientID",@ApptSubscriberKey,
    "HOHid",@HOHid,
    "PatientFirstName",@PatientFirstName,
    "FamilyID",@familyid,
    "AppointmentID",@FamilyAppt,
    "AppointmentDateTime",@PatientApptTime,
    "AppointmentTypeCode",@AppointmentTypeCode,
    "RescheduleYN",@RescheduleYN,
    "EventDate",@EventDate)

ELSE

InsertDE(
    "Patient_Records_DB",
    "PatientID",@ApptSubscriberKey,
    "HOHid",@HOHid,
    "PatientFirstName",@PatientFirstName,
    "FamilyID",@familyid,
    "AppointmentID",@FamilyAppt,
    "AppointmentDateTime",@PatientApptTime,
    "AppointmentTypeCode",@AppointmentTypeCode,
    "RescheduleYN",@RescheduleYN,
    "EventDate",@EventDate)

ENDIF

  /*UpsertDE(
    "Patient_Records_DB",1,"PatientID",@ApptSubscriberKey,
    "PatientID",@ApptSubscriberKey,
    "HOHid",@HOHid,
    "PatientFirstName",@PatientFirstName,
    "FamilyID",@familyid,
    "AppointmentID",@FamilyAppt,
    "AppointmentDateTime",@PatientApptTime,
    "AppointmentTypeCode",@AppointmentTypeCode,
    "RescheduleYN",@RescheduleYN,
    "EventDate",@EventDate)*/

A: You do not need to specify the PatientID field twice. It looks like you are setting PatientID as the match column, but then also specifying it as a column you want to insert into. You do not need to do this, setting it as the match column automatically sets it as a column that gets inserted to.
So just remove one of these from the function call: "PatientID",@ApptSubscriberKey,
Also, you don't need to do the LookUp and conditional logic to do update vs. insert. Upsert takes care of that for you automatically. All you need is the following code:
UpsertDE(
"Patient_Records_DB",1,
"PatientID",@ApptSubscriberKey,
"HOHid",@HOHid,
"PatientFirstName",@PatientFirstName,
"FamilyID",@familyid,
"AppointmentID",@FamilyAppt,
"AppointmentDateTime",@PatientApptTime,
"AppointmentTypeCode",@AppointmentTypeCode,
"RescheduleYN",@RescheduleYN,
"EventDate",@EventDate)


text:
Q: Repository design for complex objects? What is the best way to design repositories for complex objects, assuming use of an ORM such as NHibernate or Entity Framework?
I am creating an app using Entity Framework 4. The app uses complex objects--a Foo object contains a collection of Bar objects in a Foo.Bars property, and so on. In the past, I would have created a FooRepository, and then a BarRepository, and I would inject a reference to the BarRepository into the FooRepository constructor.
When a query is passed to the FooRepository, it would call on the BarRepository as needed to construct the Foo.Bars property for each Foo object. And when a Foo object is passed to the FooRepository for persistence, the repository would call the BarRepository to persist the objects in the Foo.Bars property.
My question is pretty simple: Is that a generally accepted way to set up the repositories? Is there a better approach? Thanks for your help.

A: In domain-driven design, there is the concept of a "root aggregate" object. The accepted answer to a related question has good information on what it is and how you would use it in your design. I don't know about the Entity Framework but NHibernate does not require the usage pattern you are describing. As long as all the nested objects and their relationships are properly mapped to tables, saving the aggregate root will also save all its child object. The exception is when a nested object has specific business logic that needs to performed as part of its access or persistence. In that case, you would need to pass the "child" repositories so you are not duplicating that business logic.

A: Repository pattern helps grouping of business transactions among related entities. Meaning if you have two domain objects foo and bar and have a common transactions like GetList(),Update() then a common repository like FoobarReporsitory can be created. You can even abstract that to an interface called IFoobarReporsitory to make application loosely coupled.


text:
Q: How to make FZF autocomplete files from path under cursor How to get FZF to show files from the path under cursor on the command line?
As opposed to files under the current dir.
For example,  suppose I'm at ~/code/projects, type cp on the command line,
press CTRL-t so FZF show me the files under the current working directory and
I can select a file, let's say it is myapp/READM.me. Then I'll have
cp myapp/README.me on the command line and I can continue typing. This is what
normally happens.
The behavior I'm seeking for is this: I'm at ~/code/projects, type
cp ~/downloads, press CTRL-t should make FZF show me the files under
~/downloads and not under the current working directory. Thus, I should
be able to select, let's say, the file ~/downloads/test1.txt and then the text
on command line should be cp ~/downloads/test1.txt.
How to accomplish?


text:
Q: How to use keycloak with NestJS properly I need to use keycloak with NestJS and GrapphQL (type-graphql). There are some guides for using it with pure Express, but I'd prefer using with NestJS auth pattern. Can someboby give any suggestion?

A: This is a kind of an old question, but since I just went through implementing it,  I would like to point to a great tutorial Protecting your NestJS API with Keycloak. It does not use passport, but is simply call the OpenId Connect UserInfo endpoint on Keycloak: https://openid.net/specs/openid-connect-core-1_0.html#UserInfo.
I find it very easy to add to an application, very easy to follow, and generally very well usable (comparing to an unnamed SaaS application I was using before).
async authenticate(accessToken: string): Promise<User> {
    const url = `${this.baseURL}/realms/${this.realm}/protocol/openid-connect/userinfo`;

    try {
        const response = await this.httpService.get<KeycloakUserInfoResponse>(url, {
            headers: {
                authorization: `Bearer ${accessToken}`,
            },
        }).toPromise();

        return {
            id: response.data.sub,
            username: response.data.preferred_username,
        };
    } catch (e) {
        throw new AuthenticationError(e.message);
    }
}

A: I never tried it myself, but i guess i will soon. What i would do:

*

*Check out the Authentication Technique again, and especially learn how to implement the different strategies of passport in nest: https://docs.nestjs.com/techniques/authentication

*Take a look at the npm-package and it's documentation. The guys from passport have dedicated a whole section to OpenID: http://www.passportjs.org/docs/openid/

*Implement the OpenID-Strategy in nestjs - here i would just follow the docs, since they are pretty good

I hope this will maybe help you out. At the end of the day, you will have an OpenID implementation of passport with KeyCloak and can use a guard to protect your Routes / Schemes.


text:
Q: Reactive Extensions: How to create a placeholder observable? I have a method, getObs(), that returns an observable, which should be shared by all callers. However, that observable might not exist when somebody calls getObs(), and creating it is an async operation, so my idea was to return a placeholder observable that is replaced with the real observable once it is created.
My basic attempt goes something like this:
var createSubject = new Rx.Subject();
var placeholder = createSubject.switchLatest();

Where I can return placeholder if the real observable does not exist when 'getObs()' is called. When the real observable is created, I use createSubject.onNext(realObservable), which then passes it to switchLatest() that unwraps it for any subscribers.
However, it does seem like overkill to use a Subject and switchLatest for this purpose, so I am wondering if there is a more direct solution?

A: If the act of getting the observable itself is asynchronous, you should model that also as an observable.
For example...
var getObsAsync = function () {
    return Rx.Observable.create(function (observer) {
        var token = startSomeAsyncAction(function (result) {
                // the async action has completed!
                var obs = Rx.Observable.fromArray(result.dataArray);
                token = undefined;
                observer.OnNext(obs);
                observer.OnCompleted();
            }),
            unsubscribeAction = function () {
                if (asyncAction) {
                    stopSomeAsyncAction(token);
                }
            };

        return unsubscribeAction;
    });
};

var getObs = function () { return getObsAsync().switchLatest(); };

And if you want to share a single instance of that observable, but you do not wish to get the observable until someone actually subscribes, then you do:
// source must be a Connectable Observable (ie the result of Publish or Replay)
// will connect the observable the first time an observer subscribes
// If an action is supplied, then it will call the action with a disposable
// that can be used to disconnect the observable.
// idea taken from Rxx project
Rx.Observable.prototype.prime = function (action) {
    var source = this;
    if (!(source instanceof Rx.Observable) || !source.connect) {
        throw new Error("source must be a connectable observable");
    }

    var connection = undefined;
    return Rx.Observable.createWithDisposable(function (observer) {
        var subscription = source.subscribe(observer);

        if (!connection) {
            // this is the first observer.  Connect the underlying observable.
            connection = source.connect();
            if (action) {
                // Call action with a disposable that will disconnect and reset our state
                var disconnect = function() {
                    connection.dispose();
                    connection = undefined;
                };
                action(Rx.Disposable.create(disconnect));
            }
        }

        return subscription;
    });
};

var globalObs = Rx.Observable.defer(getObs).publish().prime();

Now code wherever can just use globalObs and not worry about it:
// location 1
globalObs.subscribe(...);

// location 2
globalObs.select(...)...subscribe(...);

Notice, that no one actually even needs to call getObs because you just setup a global observable that will (via defer) call getObs for you when someone subscribes.

A: You can use a subject to hook up the source after the fact:
var placeholder = new Subject<YourType>();
// other code can now subscribe to placeholder, best expose it as IObservable

when the source is created:
var asyncCreatedObs = new ...;
placeholder.Subscribe(asyncCreatedObs);
// subscribers of placeholder start to see asyncCreatedObs


text:
Q: how to solve the differential equation $\sin^{2}(dy/dx)- x = 0$ for $y(0)=0$ and what is its domain for this point? how to solve the differential equation $\sin^{2}(dy/dx) - x = 0$ for $y(0) = 0$ and what is its domain for this point?
Note: I have calculated it with online tools, so i am not asking the result. I am asking the steps for the result.
Note2: The question is true, it is exactly as i wrote it.( It is not like sin^2(x) etc.) No editing required.

A: By the non-negativity of the square, your equation is defined on $x\in [0,1]$ and can be simplified to $\cos(2y'(x))=1-2x$. Then with the inverse cosine
$$
y'(x)=k\pi\pm\frac12\arccos(1-2x).
$$
Each $k\in\Bbb Z$ gives a valid solution.