text:
Q: How to check checkbox when a-tag is clicked in each table row? I'm working with an older version of jquery. My current code only works on the first line of my table. If I switch it to a class instead of an ID, it checks every row. I need it to work individually on each row.
Jquery Code:
$('#enableCheckbox').click(function(){
    $('#checkbox').attr("checked", true);
})

HTML:
Create
<input type="checkbox" name="checkbox" id="checkbox">

A: You want to check checkbox on every a tag click so don't give id to a tag because its work for first id only.
Please see below code, I think it's will be help you.

$(document).ready(function(){
$("table tr td a").click(function (e) {
          $(this).parent().next().find('input').attr("checked", true);
  //If you want to check and uncheck on click then follow below code
  //$(this).parent().next().find('input').attr("checked", !$(this).parent().next().find('input').attr("checked"));
    });
  });

    Create
<input type="checkbox" name="checkbox" id="checkbox">

    Create
<input type="checkbox" name="checkbox" id="checkbox">

A: ids must be unique on a table, so you cannot use the same id for each row of the table as most browsers will only return the very first element that has the id. (That is the reason that you are only getting the first row of the table).
What you can do, is you can set your event listener for a class like you mentioned, but also have a unique data element for the table row.
Or if you don't have another input in the subsequent table cell you could use some code like this:
$('.enableCheckbox').on("click", function(event){
   var $input = $(event.target).parent().find("input");
   $input.prop("checked", true);
});


text:
Q: How Does ActionDescriptorProviderContext Get Results? In
 Microsoft.AspNetCore.OData.Routing.Conventions.DefaultODataRoutingConvention.SelectAction(RouteContext routeContext), my Controller class don't appear in IActionDescriptorCollectionProvider requiredService = routeContext.HttpContext.RequestServices.GetRequiredService();
My assembly which contains the above class is located in the same bin folder.
This causes the "No Action Match Template" issue even though there is actually a code (a controller class together with its method) for that.
I found out the issue is caused by the missing item (which is my controller class) in the object Microsoft.AspNetCore.Mvc.Infrastructure.ActionDescriptorCollection.Items that is called by the previous line routeContext.HttpContext.RequestServices.GetRequiredService();.
...
      string str3 = !string.IsNullOrEmpty(str2) ? str1 + "/" + str2 : str1;
      //below is the problematic part
      IActionDescriptorCollectionProvider requiredService = routeContext.HttpContext.RequestServices.GetRequiredService<IActionDescriptorCollectionProvider>();
      List<ActionDescriptor> actionDescriptorList = new List<ActionDescriptor>();
      ActionDescriptor actionDescriptor1 = (ActionDescriptor) null;
      foreach (ControllerActionDescriptor actionDescriptor2 in requiredService.ActionDescriptors.Items.OfType<ControllerActionDescriptor>())
      {...

Because the property Items is assigned in the constructor of ActionDescriptorCollection which receives the parameter IReadOnlyList items, I also tried to find how does the constructor is called.
namespace Microsoft.AspNetCore.Mvc.Infrastructure
{
    using System;
    using System.Collections.Generic;
    using System.Runtime.CompilerServices;

    public class ActionDescriptorCollection
    {
        public ActionDescriptorCollection(IReadOnlyList<ActionDescriptor> items, int version)
        {
            if (items == null)
            {
                throw new ArgumentNullException("items");
            }
            this.<Items>k__BackingField = items;
            this.<Version>k__BackingField = version;
        }

Based on the stack trace, it is called by the method UpdateCollection()  from Microsoft.AspNetCore.Mvc.Internal.ActionDescriptorCollectionProvider in the line _collection = new ActionDescriptorCollection(
                new ReadOnlyCollection(context.Results),
                Interlocked.Increment(ref _version));
namespace Microsoft.AspNetCore.Mvc.Internal
{
    /// <summary>
    /// Default implementation of <see cref="IActionDescriptorCollectionProvider"/>.
    /// </summary>
    public class ActionDescriptorCollectionProvider : IActionDescriptorCollectionProvider
    {
...
        private void UpdateCollection()
        {
            var context = new ActionDescriptorProviderContext();

            for (var i = 0; i < _actionDescriptorProviders.Length; i++)
            {
                _actionDescriptorProviders[i].OnProvidersExecuting(context);
            }

            for (var i = _actionDescriptorProviders.Length - 1; i >= 0; i--)
            {
                _actionDescriptorProviders[i].OnProvidersExecuted(context);
            }

            _collection = new ActionDescriptorCollection(
                new ReadOnlyCollection<ActionDescriptor>(context.Results),
                Interlocked.Increment(ref _version));
        }
    }
}

The context.Results is the ActionDescriptorProviderContext.Results
namespace Microsoft.AspNetCore.Mvc.Abstractions
{
    public class ActionDescriptorProviderContext
    {
        public IList<ActionDescriptor> Results
        {
            [CompilerGenerated]
            get
            {
                return this.<Results>k__BackingField;
            }
        }

        public ActionDescriptorProviderContext()
        {
            this.<Results>k__BackingField = new List<ActionDescriptor>();
            base..ctor();
        }
    }
}

From this point, how is the Results populated with value?
I would expect to see the class from an assembly which is in the bin folder together.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting raster stack to RGB GeoTIFF for use as a background image in maps using R? I've been trying to use R to download google maps images as rasters, then convert them into GeoTIFF files which can be imported as a geo-referenced background layer in GIS programs.
I've been searching for hours now, but I can't seem to figure out how to save a colored geotiff file.  I can make Geotiff files which contain only the raster data with no saved color maps, but I've been unable to figure out how to add color maps to the GeoTIFFs.
Here's my code so far:
## Install and load required packages
install.packages('openmap')
require(ggmap)
require(raster)
require(dismo)

## Get region of interest
region <- c(11.03,12,-1.1,-0.04)
e = extent(region)

## Download google maps image of region
map <- gmap(e,rgb = T)

## Plot map
plotRGB(map)

## Write a geotiff raster (does not contain RGB info!)
writeRaster(x = map,
            filename = 'GoogleMap.tif',
            format = 'GTiff',
            overwrite = T
            )

The resulting raster can by imported by other programs as a raster layer, but the colormap is undefined.
And ideas on how to add RGB info to the resulting geoTIFF?
Heres a link to an example GeoTIFF which works in the GIS software I'm using
Perhaps I am misunderstanding what a geotiff is.  I assumed a geotiff was just a TIFF file with georeferencing metadata... but perhaps is there a difference between geotiffs and just normal tiff with georeferenced metadata?
I'm thinking this because the dismo::gmap function outputs georeferenced gif files which do exactly what I need, as they can be read by normal image viewers and they also can be plotted correctly in GIS software, unlike the geotiffs which I made, which cannot be read by image viewers.

A: I wasn't able either to export with raster, but an alternative would be to use writeJPEG() from package jpeg. Note that:

*

*writeJPEG() expects an array as input: using as.array(r) does the trick

*writeJPEG() expects RGB values between 0-1. In my case, reading with raster, they were 0-255, so just rescale!

Your example didn't work for me, but here is one, using the R logo, importing it with raster() adding some (truly beautiful) art, and exporting to jpg:
library(raster)
library(jpeg)

r <- stack(system.file("img","Rlogo.jpg",package="jpeg"))

r$Rlogo.1 <- getValues(r$Rlogo.1)/2

plotRGB(r)

writeJPEG(as.array(r)/255, "out.jpeg")


text:
Q: File size limit and/or update count limit Is there a limit to the size of a file or the number of times file can be updated in SharePoint?
Recently had a file that could not be updated and was troubleshooting.

A: Maximum file size limit is 2 GB. This can't be changed.
But SP web applications have much lower configurable limitation out of box, these are set in CA.
Default values are:

*

*For SharePoint 2013: default max file size is 250 MB

*For SharePoint 2007/2010: default max file size is 50 MB

A: Yes there is a limitation on the number of times you can update a file in SharePoint. If you closely look into below article link you can see the Major Versions and Minor versions limit shown.
SharePoint 2013 List & Library Limitations
SharePoint 2010 List & Library Limitations
Regarding maximum file size upload, @Aziz has already informed you in his answer about the file size limitations. The above two articles also states the file size limitation. Check for File Size in the table.


text:
Q: I/O panel filtering for shielded room We are looking into setting up a very basic shielded chamber inside a small room at my company to be able to perform some basic relative radiated EMC measurements.
We will buy a somewhat cheap spectrum analyzer together with a set of near field probes and a biconical antenna, and want to have a room where we can perform measurements with as little interference as possible.
So I've been looking into doing a very cheap DIY shielded chamber inside the room, by building a wooden frame and wrapping chicken wire around the frame with thick aluminum foil to seal all joints.
The only thing I still feel unsure about is how to do the filtering for the I/O panel. What we need to get into the chamber is the following signals:

*

*230V/50 Hz power

*USB 2.0

*Ethernet

*Coax antenna connector for biconical antenna

*Two BNC connectors for DC power supply

*SMA connector for various RF stuff

So my question is how I would filter all of these signals in suitable ways? Our plan right now is to slap ferrites on all signals, but I don't think that will accomplish very much. What would be a better way?
EDIT: For anyone looking for additional answers to this question, I asked Keith Armstrong over at emcstandards.co.uk and he very kindly made this blog post about my question: https://www.emcstandards.co.uk/constructing-io-panels-for-shielded-rooms

A: You can read about "bulkhead" connectors for low/moderate DC power, or logic level control signals.
Otherwise you need a 6" by 6" by 20" power_line filter, bonded to the steel/copper of the walls.
By the way, aluminum oxide forms INSTANTLY upon exposure to air, thus the aluminum will not make ohmic contact between the various sheets.
There will be high capacitance as you crumple the sheet_edges together, but not ohmic.
C = Eo * Er * Area/Distance
C = 9-12 farad/meter * (Area = 2cm * 50cm)/100 micron
C = 9e-12 farad/meter * (100 cm * cm) / 0.0001millimeter
C = 9e-12 farad * 100/0.0001 *  cm/meter * cm/millimeter
C = 9e-12 * 1Million * 0.01 * 10
C = 9e(-12 + 6 -2 +1) = 9e-7 = 0.9 uF
which may be adequate even at 10MHz.


text:
Q: Using PowerShell's Where-Object -Filterscript with AWS EC2 Tags to filter resources How can I use Where-Object -Filterscript to look up AWS resources based on Tag and corresponding tag value?
If I run a command to look at the tags:
(Get-Ec2Address -region $region).Tags

I receive an output like:

Key                Value
---                    -----
environment         dev
project            project
Name              blah

So if I want to look up all EIP resources where the project tag has a value which matches "project", how can I do that? I'm trying this:
 Get-EC2Address -region $region | Where-Object -FilterScript {
     $_.Tags.Key -match "project" -and `
     $_.Tags.Value -like "*$project*"
}

But that's just showing me the EIPs that have a key "project" and a value "project", not where the EIPs have the key of "project" and the CORRESPONDING value is "project".
For example,
Get-EC2Address -region $region | Where-Object -FilterScript {
     $_.Tags.Key -match "project" -and `
     $_.Tags.Value -like "*dev"
}

will still return a result, despite us having no projects called "dev"
How can I link those the Key and the Value when filtering?

A: You can always do it like this
Get-EC2Address -region $region | Where-Object -FilterScript {$_.Tags.Key -match "project"} | Where-Object -FilterScript {$_.Tags.Value -like "*$project*"}

I dont have an AWS env to test your code. This^^ is a little inefficient but should work.


text:
Q: TFS2012 User Storys Tasks with different iteration paths In my Company we are using Team Foundation Server 2012 and Agile as Project Template. We are still learning how the Board and the Backlog show Tasks within User Stories and I realized that "Orphan" Tasks are not shown in these cases...
I made an query to solve the problem about the "Orphan" tasks but I realized that the same issue is happening when a User Story and a Task have, for some reason (maybe someone assign it to a User Story after creating it), a different iteration path... the tasks are not shown in the Backlog or Board.
Is there an automatic way to make tasks having the same iteration path as their parents? How can I make a query to show tasks whose User Stories have a different iteration path as them?
Thanks a lot in advance!

A: Well. After more researching I have realized about two thing:
- It is not needed to do this in order to show the Tasks in the Board/Backlog because, if the User Story contains tasks that are defined in different iterations, the User Story will be shown in the different iterations, repeated, but only with the tasks belonging to the iteration.
- If someone still wants to create the query, maybe to reunite User Stories, the solution is creating a new Query of the type Work Items and Direct Links and change the following parameters:
  * In Filters for top level work item Add a new clause And Iteration Path = IterationA
  * In Filters for linked work items Add a new clause And Iteration Path <> IterationA
  * In Filter options Types of links select Return selected link types and check Child and Parent.
Unfortunately there is no way, so far I know, to do it automatically for all iterations so you have to do a Query of this type for all iterations.


text:
Q: Error While Read Windows Log Event in mvc 6 I am trying to create a web application to read all windows events log and display into the web page. i tried it in asp.net mvc 5 its working but when I tried to execute it in a asp.net mvc 6 application is shows error.
Controller
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using WebApplication1.Models;
using WebApplication1.Models.PaginationExample;

namespace WebApplication1.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
        EventLog eventLog = new EventLog("Application", "nb-ahja1", "EventLoggingApp");

        var model = new List<Eventlogg>();
        foreach (EventLogEntry log in eventLog.Entries)
        {
            var demo = new Eventlogg();
            demo.Source = log.Source;
            demo.Id = log.EventID;
            demo.Level = log.EntryType.ToString();
            demo.Date = log.TimeGenerated;
            demo.Category = log.Category;
            model.Add(demo);
        }
        return View(model.OrderByDescending(x => x.Date).ToList());
    }

    public ActionResult About()
    {

        return View();
    }

    public ActionResult Contact()
    {
        ViewBag.Message = "Your contact page.";

        return View();
    }
}
}

Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebApplication1.Models
{
    public class Eventlogg
    {
        public string Source { get; set; }
        public int Id { get; set; }
        public string Level { get; set; }
        public DateTime Date { get; set; }
        public string Category { get; set; }

    }
}

View

@model List<WebApplication1.Models.Eventlogg>
@{
    ViewBag.Title = "Home Page";
}

            Level
        Date
        Source
        Id
        Category

@foreach (var item in Model)
{

            @item.Level
            @item.Date
            @item.Source
            @item.Id
            @item.Category

}

Error
Severity    Code    Description Project File    Line    Suppression State
Error   CS0246  The type or namespace name 'EventLog' could not be found (are you missing a using directive or an assembly reference?)  PocDashboard.DNX Core 5.0   C:\Users\ahja\Documents\Visual Studio 2015\Projects\AteaPoCDashboard\src\PocDashboard\Controllers\HomeController.cs 19  Active

A: Basically you're missing an assembly reference that you need to add to your project.
'EventLog' is part of system.diagnostics namespace which is part of System.dll assembly, make sure that this assembly is referenced in your project.


text:
Q: Posting XML back to server Rails As i have never done this before I was wondering if anyone could either point out some resources that show best practices when dealing with XML (post/puts requests) or perhaps show an example.
for example i am trying to post back some XML to the google contacts api to update a contact
What i currently do is save the incoming XML into my model, edit functionality is performed within the app and then saved back to the model.Once everything is updated I then want to post back the updated contact back to the api in XML format, at present i only update the email address and persons name
Which is a PUTS request to
https://www.google.com/m8/feeds/contacts/userEmail/full/{contactId}

Could someone offer up an example of how they would do it?
The XML to be returned is
PUT /m8/feeds/contacts/default/full/<var>contactId</var>
If-Match: <var>Etag</var>

<entry gd:etag='<var>Etag</var>'>
<id>http://www.google.com/m8/feeds/contacts/<var>userEmail</var>/base/<var>contactId</var></id>
<updated>2008-02-28T18:47:02.303Z</updated>
<category scheme='http://schemas.google.com/g/2005#kind'
term='http://schemas.google.com/contact/2008#contact'/>
<gd:name>
<gd:givenName>New</gd:givenName>
<gd:familyName>Name</gd:familyName>
<gd:fullName>New Name</gd:fullName>
</gd:name>
<content type='text'>Notes</content>
<link rel='http://schemas.google.com/contacts/2008/rel#photo' type='image/*'
href='https://www.google.com/m8/feeds/photos/media/<var>userEmail</var>/<var>contactId</var>'/>
 <link rel='self' type='application/atom+xml'
href='https://www.google.com/m8/feeds/contacts/<var>userEmail</var>/full/<var>contactId</var>'/>
<link rel='edit' type='application/atom+xml'
href='https://www.google.com/m8/feeds/contacts/<var>userEmail</var>/full/<var>contactId</var>'/>
<gd:phoneNumber rel='http://schemas.google.com/g/2005#other'
primary='true'>456-123-2133</gd:phoneNumber>
<gd:extendedProperty name='pet' value='hamster'/>
<gContact:groupMembershipInfo deleted='false'
href='http://www.google.com/m8/feeds/groups/<var>userEmail</var>/base/<var>groupId</var>'/>
</entry>
</pre>

Any advice is appreciated
Thanks

A: I don't know anything about the google contacts API, but to POST/PUT/GET in Rails is quite simple using Net::HTTP, HTTParty or similar.
In HTTParty I'm pretty sure it's something like:
require 'httparty'
response = HTTParty.put("https://www.google.com/m8/feeds/contacts/userEmail/full/{contactId}",
             :body => { :xml => xml_data })


text:
Q: Turning text with hours and minutes to minutes I have got a big dataframe that look like this:

from
to
distance in km
traveltime

1033
1076
1.8
6 mins

1035
1076
2.6
1 min

1036
1076
2.4
1 hour 26 mins

1037
1076
6.7
3 hours 1 min

i want get the traveltime column to show the traveltime in minutes, so like this:

from
to
distance in km
traveltime

1033
1076
1.8
6

1035
1076
2.6
1

1036
1076
2.4
86

1037
1076
6.7
181

I have tried the hm() function but it doesn't work on the values which are smaller than 1 hour.

A: Try this wrapping a time transformation in nested replacements for strings:
#Code
df$NewTime <- unname(sapply(sub('s','',sub("\\s+min",
                  "", sub("hour|hours", "* 60 +", df$traveltime))),
              function(x) eval(parse(text=x))))

Output:
df
  from   to distance.in.km     traveltime NewTime
1 1033 1076            1.8         6 mins       6
2 1035 1076            2.6          1 min       1
3 1036 1076            2.4 1 hour 26 mins      86
4 1037 1076            6.7  3 hours 1 min     181

Some data used:
#Data
df <- structure(list(from = c(1033L, 1035L, 1036L, 1037L), to = c(1076L,
1076L, 1076L, 1076L), distance.in.km = c(1.8, 2.6, 2.4, 6.7),
    traveltime = c("6 mins", "1 min", "1 hour 26 mins", "3 hours 1 min"
    )), row.names = c(NA, -4L), class = "data.frame")

Another option using stringr:
library(stringr)
#Code 2
df$NewTime <- sapply(str_extract_all(df$traveltime, "\\d+"), function(x) {
  x1 <- as.numeric(x)
  if(length(x1)>1) x1[1]*60 + x1[2] else x1 })

It will produce the same output.

A: Another solution could be by extracting the number substrings. First, get the numbers into a list and then convert hours into minutes by multiplying 60.
matches <- regmatches(df$traveltime, gregexpr("[[:digit:]]+", df$traveltime))
hr_mins <- lapply(matches, function(x){
  x <- as.numeric(x)
  if(length(x) > 1) x[1] * 60 + x[2] else x
})
df$traveltime <-  unlist(hr_mins)

Output
  from   to distance.in.km traveltime
1 1033 1076            1.8          6
2 1035 1076            2.6          1
3 1036 1076            2.4         86
4 1037 1076            6.7        181

Data
df <- structure(list(from = c(1033, 1035, 1036, 1037), to = c(1076,
1076, 1076, 1076), distance.in.km = c(1.8, 2.6, 2.4, 6.7), traveltime = c("6 mins",
"1 min", "1 hour 26 mins", "3 hours 1 min")), class = "data.frame", row.names = c(NA,
-4L))

A: You can convert traveltime to lubridate's period object, convert the period object to number of seconds and divide it by 60 to get duration in minutes.
library(lubridate)
df$travel_min <- period_to_seconds(period(df$traveltime))/60
df

#  from   to distance.in.km     traveltime travel_min
#1 1033 1076            1.8         6 mins          6
#2 1035 1076            2.6          1 min          1
#3 1036 1076            2.4 1 hour 26 mins         86
#4 1037 1076            6.7  3 hours 1 min        181


text:
Q: broken animation in portfolio filter without plugins html code

    all
    web design
    php
    wordpress
    html

web design

wordpress

php

html

wordpress

php

html

web design

web design

html

php

html

php

wordpress

web design

wordpress

web design

html

php

wordpress

wordpress

html

php

wordpress

Css(with scss)
*{
    margin: 0;
    padding: 0;
    border: none;
}

body{
    padding: 50px;
}

$col1: #ff3030;
$col2: lightblue;
$col3: lightgreen;

span{
    display: block;
    border: 1px solid $col1;
    background: $col1 + #111;
    float: left;
    cursor: pointer;
    padding: 10px;
    margin-right: 10px;
    color: #fff;
    font-family: arial;
}

.wp{
    overflow: hidden;
    margin-bottom: 20px;
}

ul{
    list-style: none;
    overflow: hidden;

}

li{
    display: block;
    float: left;
    background: $col3 - #111;
    border: 1px solid $col3 - #222;
    color: #fff;
    text-align: center;
    text-transform: uppercase;
    padding: 40px;
    margin-right: 20px;
    margin-bottom: 20px;
    transition: 1s;
    -webkit-transition: 1s;
}

jquery
$(document).ready(function() {
    var arr1 = [],
        arr2 = [],
        arr3 = [],
        arr4 = [];
    $('li').each(function(i, el) {
        if($(el).attr('name') == 'web') {
            arr1.push(el);
        } else if($(el).attr('name') == 'wordpress') {
            arr2.push(el);
        } else if($(el).attr('name') == 'php') {
            arr3.push(el);
        } else if($(el).attr('name') == 'html') {
            arr4.push(el);
        }
    });

    $('span').on('click', function() {
        var $this = $(this),
            elems = $('li');
        if( $this.attr('name') == 'all') {
            elems.fadeIn();
            return false
        }  else if ($this.attr('name') == 'web') {
            elems.fadeOut(600);
            setTimeout(function() {$(arr1).fadeIn(600);
            }, 800);
        }  else if ($this.attr('name') == 'wordpress') {
            elems.fadeOut(600);
            setTimeout(function() {$(arr2).fadeIn(600);
            }, 800);
        }  else if ($this.attr('name') == 'php') {
            elems.fadeOut(600);
            setTimeout(function() {$(arr3).fadeIn(600);
            }, 800);
        }  else if ($this.attr('name') == 'html') {
            elems.fadeOut(600);
            setTimeout(function() {$(arr4).fadeIn(600);
            }, 800);
        }
    });

});

fiddle link
http://jsfiddle.net/qyY7T/
Or full screen
http://jsfiddle.net/qyY7T/embedded/result/
The problem is in animate effect, which doesn't work... As you can see, I have already set a Timout, but no resaults. I'll thanx to everybody, and ask you - don't give any plugins. Thanx!

A: For some reason you can't fadeout a li so you have to do the ul here is what I mean:
window.arr0 = [],
window.arr1 = [],
window.arr2 = [],
window.arr3 = [],
window.arr4 = [];
$('li').each(function (i, el) {
    arr0.push(el);
    if ($(el).attr('name') == 'web') {
        arr1.push(el);
    } else if ($(el).attr('name') == 'php') {
        arr2.push(el);
    } else if ($(el).attr('name') == 'wordpress') {
        arr3.push(el);
    } else if ($(el).attr('name') == 'html') {
        arr4.push(el);
    }
});
$('span').click(function() {
    $this = $(this);
    $('ul').fadeOut(600);
    setTimeout(function() {
        $('li').css('display', 'none');
        $(window['arr' + $this.attr('name')]).each(function() {
            this.style.display = 'block';
        });
        $('ul').fadeIn();
    }, 600);
});

http://jsfiddle.net/qyY7T/1/


text:
Q: How to rewrite this promise chain to avoid need of multiple functions? I'm just starting with mobx and react (which is a great team, btw.!) and I have a little problem with my store. I want to asynchronously fetch some data from an existing API and then use this data to update some existing observables in my store:
class StationStore {

  @observable stations = []

  loadStations() {
    fetch('http://localhost:3000/api/station/getStations')
    .then(function(response) { return response.json() })
    .then(stations=>this.parseStations(stations));
  }

  @action parseStations(stations) {
    var newStations = stations.map((station)=>{
      let s = new Station;
      s.id=station.id;
      s.name=station.Text;
      s.deviceType=station.DeviceType;
      return s;
    });
    this.stations.replace(newStations);
  }
}

As you can see, I need to divide my logic into two separate functions in order to be able to access this.stations. I tried to include the map and replace part into the loadStations()'s second then(), but when I do so, I cannot access my store because this is undefined in there.
How can I fix this?

A: Use var self = this; should solve your problem
class StationStore {
    @observable stations = [];

    loadStations() {
        var self = this;
        fetch('http://localhost:3000/api/station/getStations')
            .then(function (response) {
                return response.json()
            })
            .then(stations => {
                self.stations.replace(stations.map((station) => {
                    let s = new Station;
                    s.id = station.id;
                    s.name = station.Text;
                    s.deviceType = station.DeviceType;
                    return s;
                }));
            });
    }
}


text:
Q: Point displacement between map (Cesium 3D) and raster (numpy array) It is better to show than tell:

On this image, the layer below the colorful shape is a trivial heat map in raster format.
The colorful shape is the product of the skimage.graph.MCP_Geometric method.
In order to find the cell indexes for the start and end points, I am using the calculation shown in the second answer of this thread: How to extract value from a raster based on lat and lon? (I have used the first one also as a test, ending in the same results.).
The problem:
As you can see from the arrows on the resulting image, the start/end points seem to be displaced in accordance to the starting points of the corridor.
The points' coordinates are in srid 4326.
UPDATE:
The Point coordinates are taken by Cesium with 3d tile rendering. When checking the same rasters and the corresponding points in QGIS I see an even greater displacement:


text:
Q: How to prove an approximation of a combinatorics identity How to prove that $$\sum_{k\ge 0} \binom{n}{rk} =\frac{1}{r}\sum_{j=0}^{r-1}(1+w^j)^n$$ can be approximated as $\frac{2^n}{r}$, where $n\ge 0$, $r\ge 0$, $n>r$, $w^r=1$.
For example, $$(1 + 1)^n + (1 + \omega)^n + (1 + \omega^2)^n) = 2^n + (-\omega^2)^n + (-\omega)^n)$$ $$(1 + 1)^n + (1 + \omega)^n= 2^n $$


text:
Q: Getting a decimal qty from subtracting two times How do I subtract two time variables from each other with the answer as a decimal number? My time variables look like this: 07:32:00
I am looking for something like this:
$total = $start_time - $end_time
echo "$time Hours";

Output to look like this:
5.3 Hours

A: You cant subtract on strings. Your variable "07:32:00" is a string.
You will have to convert the time to Unix timestamp with the php function  strtotime.
And you aslo have to subtract from the largest time.
Here is the solution:
echo (strtotime("15:00:00") - strtotime("11:30:00"))/(60*60);


text:
Q: How to paginate TextView I want to do pagination on TextView like websites with page numbers. I am able to do pagination with this code given below. But don't know how to show page numbers. This is my code to divide text into pages:
      public class PaginationController {

            private static final String TAG = PaginationController.class.getSimpleName();

            private final TextView mTextView;

            private int mPageIndex;
            private String mText;
            private HashMap<Integer, Boundary> mBoundaries;
            private int mLastPageIndex;

            public PaginationController(@NonNull TextView textView) {
                mTextView = textView;
                mBoundaries = new HashMap<>();
                mLastPageIndex = -1;
            }

            public void onTextLoaded(@NonNull String text, @NonNull final OnInitializedListener listener) {
                mPageIndex = 0;
                mText = text;

                if (mTextView.getLayout() == null) {
                    mTextView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            ViewTreeObserver obs = mTextView.getViewTreeObserver();
                            obs.removeOnGlobalLayoutListener(this);
                            setTextWithCaching(mPageIndex, 0);
                            listener.onInitialized();
                        }

                    });

                } else {
                    setTextWithCaching(mPageIndex, 0);
                    listener.onInitialized();
                }
            }

            /**
             * Assume, that page index can be only next or previous. For other cases
             *
             * @param pageIndex index of selected page
             */
            private void selectPage(int pageIndex) {
                Log.v(TAG, "selectPage=" + pageIndex);

                String displayedText;
                if (mBoundaries.containsKey(pageIndex)) {
                    // use existing boundaries
                    Boundary boundary = mBoundaries.get(pageIndex);
                    displayedText = mText.substring(boundary.start, boundary.end);
                    mTextView.setText(displayedText);
                    Log.v(TAG, "Existing[" + pageIndex + "]: " + displayedText);
                } else if (mBoundaries.containsKey(pageIndex - 1)) {
                    //calculate boundaries for new page (previous exists)
                    Boundary previous = mBoundaries.get(pageIndex - 1);
                    setTextWithCaching(pageIndex, previous.end);
                } else {
                    Log.v(TAG, "selectPage(" + pageIndex + "), values=[" + mBoundaries.keySet());
                    // TODO implement selectPage(n), n - random int
                }
            }

            private void setTextWithCaching(int pageIndex, int pageStartSymbol) {
                String restText = mText.substring(pageStartSymbol);

                mTextView.setText(restText);

                int height = mTextView.getHeight();
                int scrollY = mTextView.getScrollY();
                Layout layout = mTextView.getLayout();
                int firstVisibleLineNumber = layout.getLineForVertical(scrollY);
                int lastVisibleLineNumber = layout.getLineForVertical(height + scrollY);

                //check is latest line fully visible
                if (mTextView.getHeight() < layout.getLineBottom(lastVisibleLineNumber)) {
                    lastVisibleLineNumber--;
                }

                int start = pageStartSymbol + mTextView.getLayout().getLineStart(firstVisibleLineNumber);
                int end = pageStartSymbol + mTextView.getLayout().getLineEnd(lastVisibleLineNumber);

                if (end == mText.length()) {
                    mLastPageIndex = pageIndex;
                }
                String displayedText = mText.substring(start, end);
                Log.v(TAG, "Added to Cache[" + pageIndex + "](symbols={" + start + "," + end + "}): " + displayedText);

                //correct visible text
                mTextView.setText(displayedText);

                mBoundaries.put(pageIndex, new Boundary(start, end));
            }

            public boolean next() {
                throwIfNotInitialized();
                if (isNextEnabled()) {
                    selectPage(++mPageIndex);
                    return true;
                }
                return false;
            }

            public boolean previous() {
                throwIfNotInitialized();
                if (isPreviousEnabled()) {
                    selectPage(--mPageIndex);
                    return true;
                }
                return false;
            }

            public boolean isNextEnabled() {
                throwIfNotInitialized();
                return mPageIndex < mLastPageIndex || mLastPageIndex < 0;
            }

            public boolean isPreviousEnabled() {
                throwIfNotInitialized();
                return mPageIndex > 0;
            }

            void throwIfNotInitialized() {
                if (mText == null) {
                    throw new IllegalStateException("Call onTextLoaded(String) first");
                }
            }

            private class Boundary {

                final int start;
                final int end;

                private Boundary(int start, int end) {
                    this.start = start;
                    this.end = end;
                }
            }

            public interface OnInitializedListener {
                void onInitialized();
            }
        }

        This code is my code to set text to textview:

          mController = new PaginationController(tvContent);

                        if(history!=null)
                        onTextLoaded(history);

A: There's two easy to do pagination of the text.

*

*RecylerView with Horizontal LinearLayoutManager.

*Or you can use ViewPager with PagerAdapter.


text:
Q: PHP arrays from form input I have some data in a html table which has been populated from a mysql database.  To put the data into the html table I have done the following:
$meterdetail = getMeterDetails($ticketNumber);

This gets a number of records from the mysql table  Then for each record retrieved from the db I do the following..
foreach ($meterdetail as $v2) {

        <input type='hidden' name='ids[]' value='".$v2['id']."'>
        <input type='text' name='meters[]' value=''>

Ultimately what I am trying to do here is update each record (based on the ID from the mysql table) with the values in the input of the table.
When I click on a submit button I need to step through each record that was collected and insert the value that was typed into the html form corresponding to the relevant id.
To process the $_POST data I do the following
if (!empty($_POST['meters']) && !empty($_POST['ids'])) {
    for ($i = 0; $i < count($_POST['meters']); $i++) {
        updateRecord($_POST['ids'][$i],$_POST['meters'][$i]);
    }
}

This seems to be working but for some reason I don't feel comfortable with this solution so my question is:  Is there a better (more elegant / more correct) way to do this (particularly the processing of the 2 $_POST arrays)?  Can I create one associative array with the ID as key and the form input value as the corresponding value?

A: $met = $_POST['meters'];
$id = $_POST['ids'];

if (isset($met) && isset($id))
{
    for ($i = 0; $i < count($id); $i++)
    {
        updateRecord($id[$i],$met[$i]);
    }
}

A: A better way is to make sure you have 'set in stone' names for your inputs;
foreach ($meterdetail as $key => $v2) {
    echo "

        <input type='hidden' name='id_".$key."' value='".$v2['id']."'>
        <input type='text' name='meter_".$key."' value=''>

    ";
}

And than process the post-data as such:
$ids = array();
$meters = array();
foreach($_POST as $name => $value) {
    if(strpos($name, 'id_') === 0) {
        $ids[substr($name, 3)] = $value;
    }
    if(strpos($name, 'meter_') === 0) {
        $ids[substr($name, 3)] = $value;
    }
}

if(count($ids) && count($meters)) {
    foreach($ids as $key => $id) {
        updateRecord($id, $meters[$key]);
    }
}

This way you are always sure you have accompanying values which you are updating in the db.
PS: this is proof of concept... haven't tested it yet...


text:
Q: Please, add more detailed description of badges, explaining why should I respect the user bearing them There is a lot of questions about the same problem: "What does Tenacious badge mean?"
The short description of the badge is really hard to understand (as shown in the question 69322), and a lot of questions received an answer with pointer to the List of all badges with full descriptions, and this link often was enough to enlighten the asker.
Jeff Atwood answered the question "Why is the description on the badges page so sparse?" with suggestion that more descriptive descriptions would be too confusing for the users, and the badges should be surprise, not a goal.
I humbly insinuate that while that answer seems to match the original question it has been quoted from, for that question it is not a good answer. A small link would not clutter the page readability. Also if there are badges, and they are displayed publicly, then their description should be understandable. Hiding a good description of some component smells a little like security-by-obscurity.
There is a lot of questions concerning this topic, and a lot of them has no accepted answer. (I upvoted these questions, but I doubt it will draw attention to them, as they are usually pretty old.) For example:

*

*"Please improve the description of the Organizer badge" - asked a year ago, no answer,

*"Make badges more descriptive" - the accepted answer is a link to the list,

Two answers for the question "What does the "tenacious" badge reward?" form a beautiful description of the badge - they answer the question "Why this badge exists", and "What good has been done by this user".
I understand that Jeff does not want to see the descriptions which tell us "what should I click to get this badge", but the descriptions like these two mentioned above are a different thing. Similar descriptions tell me why should I respect the user bearing this badge.
Maybe not all badges need more details - probably bronze ones do not. So, how about adding a short description in this style?


text:
Q: AngularJS / GoogleMaps (Hide markers at all times) Using AngularJS and the GoogleMaps API, my team and I noticed that it is quite hard to get markers to do exactly what you want them to.
We are using polygons (instead of markers) on our map page to represent certain areas.  When those areas are clicked, an infoWindow pops up with relevant information.  When the user clicks another polygon, the infoWindow goes to that polygon with no problem and no marker shows up on the original parking lot.  This is all good and well, but when the user closes an infoWindow given from any polygon, the red marker shows up again.
Bottom Line:  Is there a way to permanently hide markers so that even when an infoWindow is closed (close clicked), it doesn't show up?

A: According to Google Docs:
To remove a marker from the map, call the setMap() method passing null as the argument.
marker.setMap(null);

You can also play around with the full sample. It includes hiding and deleting markers functionality.


text:
Q: How can we get parent package annotations?Anyone offer an example? Imagine that we have a class:User.java below package: src/service/model
And we can get the package (src/service/model) annotations
using User.class.getPackage().getAnnotaions();
Then How can we get the parent package (src/service) annotations.
I don't know how to get package annotations in a skip level.

A: You can get all packages in app and than filter required package to get Annotations:
String userPackName = User.class.getPackage().getName();      // src.service.model
int lastIndex = userPackName.lastIndexOf(".");
String parentPackName = userPackName.substring(0, lastIndex); // src.service
Annotation[] annotations = Arrays.stream(Package.getPackages())
                .filter(pack -> pack.getName().equals(parentPackName))
                .findFirst()
                .map(Package::getAnnotations)
                .orElseGet(() -> new Annotation[0]);

, but Package.getPackages() will only return the packages defined in the current class loader (any classes from root package (src/service) were loaded by current class loader).
java.lang.Package snippet:
@CallerSensitive
public static Package[] getPackages() {
    ClassLoader cl = ClassLoader.getClassLoader(Reflection.getCallerClass());
    return cl != null ? cl.getPackages() : (Package[])BootLoader.packages().toArray((x$0) -> {
        return new Package[x$0];
    });
}

/** @deprecated */
@CallerSensitive
@Deprecated(
    since = "9"
)
public static Package getPackage(String name) {
    ClassLoader l = ClassLoader.getClassLoader(Reflection.getCallerClass());
    return l != null ? l.getPackage(name) : BootLoader.getDefinedPackage(name);
}


text:
Q: Fatal error: Uncaught Error: Call to a member function bind_param() on bool no encuentro la solucion alguien me puede ayudar con esto no encuentro el error.
lo que estoy intentando hacer es simplemente agregar un nuevo registro a la base de datos por el metodo get.
  <?php
include 'conexion.php';
$nombre=$_GET['nombre'];
$apellido=$_GET['apellido'];

//$nombre="mateo";
//apellido="gallego";

$sentencia=$conexion->prepare("INSERT INTO prueba VALUES (?, ?)");
$sentencia->bind_param('ss',$nombre,$apellido);
$sentencia->execute();

$resultado = $sentencia->get_result();
if ($fila = $resultado->fetch_assoc()) {
         echo json_encode($fila,JSON_UNESCAPED_UNICODE);
}
$sentencia->close();
$conexion->close();
?>

y esta es la conexion de la base de datos
<?php
$hostname = 'localhost';
$database = 'detalles_egallego_gestion';
$usernamebase = "root";
$passwordbase = "";

$conexion=new mysqli($hostname, $usernamebase, $passwordbase, $database);
$conexion->set_charset("utf8");
if ($conexion->connect_errno){
    echo "el sitio web esta presentando problemas";
}

?>

muchas gracias al que pueda ayudarme


text:
Q: how to add New UIViewCOntroller Over UiView I have added subview in a UIViewController and I want a new UIViewController Should be loaded on click of button.
Challenge is I am not able to use button in new UIViewController.
Code which I have write:
DetailsOfDayViewController *aViewController =[[DetailsOfDayViewController alloc] initWithNibName:@"DetailsOfDayViewController" bundle:nil];
aViewController.dateParsing = dateparsing;
[self addSubview:aViewController.view];

A: For showing another controller you can following options
1. Add SubView
 newViewControllerObj.view.frame = oldViewControllerObj(self).view.frame
  [oldViewControllerObj(self).view.newViewControllerObj.view];

2. Present
  [oldViewControllerObj(self) presentViewController: newViewControllerObj animated:YES completion:nil];

3. Push using Navigation (For this you already have to set navigation controller as root controller)
  [oldViewControllerObj(self).navigationController pushViewController:newViewControllerObj animated:YES];

A: This will fix your issue. This is happening because your view controller is being deallocated when you don't have any strong pointers on it.
DetailsOfDayViewController *aViewController =[[DetailsOfDayViewController  alloc] initWithNibName:@"DetailsOfDayViewController" bundle:nil];
aViewController.dateParsing = dateparsing;
[self addChildViewController:aViewController];
[self addSubview:aViewController.view];

Another fix will be connecting this view controller to a property:
@property(nonatomic,strong) DetailsOfDayViewController *aViewController;

And change your code like this:
self.aViewController = [[DetailsOfDayViewController  alloc] initWithNibName:@"DetailsOfDayViewController" bundle:nil];
self.aViewController.dateParsing = dateparsing;
[self addSubview:self.aViewController.view];


text:
Q: Getting search values by clicking links in application layout I have a row of cities at the top of a layout. I also have a sidebar with a list of categories. In a view that is rendered within this layout, I'd like to query results of a model with category and location fields, based on which city has been selected, and by which category is most recently clicked.
I'm having trouble figuring out the best way to do this. I guess I'd like the city buttons to function like radio buttons, so that when a category is clicked, it is still using the last selected location to query the results. I'm also not sure how to pass the clicked button's value to the Offers model's search function:
def self.search(query, query2, query3)
    where("title like ?", "%#{query}%").
    where("category = ?", "%#{query2}%").
    where("city = ?", "%#{query3}%")
end

This is the last step in finishing a large project for me, and any help would be greatly appreciated. If all else fails, I'll just end up using two dropdowns for category and location, but I'd really like to get this working.

A: Routing
You'll basically need to define a route to handle this - allowing you to pass a series of parameters through your links to your controller, allowing you bring back the data as defined by the links
Whether you handle this through plain HTTP, or through Javascript, it's the same process link > controller > response
I would do this:
#config/routes.rb
resources :offers do
   collection do
      get :search
   end
end

This will allow you to create your links as follows:
<% @cities.each do |city| %>
   <%= link_to city.name, offers_search_path(city: city.name) %>
<% end %>

This should create the link: domain.com/offers/search?city=scarborough
--
Controller
When you have a link like the one above, your controller will then be able to handle the city param, allowing you to perform a conditional search as follows:
#app/controllers/offers_controller.rb
Class OffersController < ApplicationController
   def search
       @result = Offer.search params[:city] #-> considering you want to use a class method
   end
end

--
Ajax
If you wanted to perform the search via ajax, you'd do all of the above except you'd handle the link as a remote one:
<%= link_to city.name, offers_search_path(city: city.name), remote: true %>

This will send an ajaxified request to your controller, which you'll be able to handle as follows:
#app/controllers/offers_controller.rb
Class OffersController < ApplicationController
   respond_to :js, :json, :html
   def search
       @result = Offer.search params[:city]
       respond_with @result
   end
end


text:
Q: Count the ways to choose distinct subsets $A_0, A_1, . . . , A_n$ of ${1, 2, . . . , n}$ such that $A_0 ⊂ A_1 ⊂ . . . ⊂ A_n$ I was given this question. Count the ways to choose distinct subsets $A_0, A_1, . . . , A_n$ of ${1, 2, . . . , n}$ such that $A_0 ⊂ A_1 ⊂ . . . ⊂ A_n$
I followed a different example to solve this
Let us count the number of ways to assigning elements to $A_0; A_1 - A_0; A_2 - A_1, ..... , A_n - A_n-1$, and X. Now, however, there are no constraints, so each of the n elements can choose any of the n + 2 sets, which gives $(n+2)^n$
Is my solution correct? It seems to me like i feel as if it is unfinished or it could be more detailed.

A: From the strict inclusions we can get the size of each set in a chain: $|A_i| \ge |A_{i-1}| + 1$, so $|A_n| \ge n + |A_0|$. On the other hand, $A_n \subseteq \{1, \dotsc, n\}$! This forces $|A_i| = i$.
In particular, $A_0$ is empty, there are $n$ choices for $A_1$, and $n-1$ choices for $A_2$ given $A_1$, and so on.


text:
Q: Package class scope in Meteor I'm having some issues writing packages, perhaps someone can help.
I am trying to include new npm modules and add them into the Meteor class.
So for example in my package.js I have declared:
mongoose = require('mongoose');

This works fine, I can console log this and it shows the object.
However inside Package.on_use( I can't use the Meteor class: Meteor is not defined
 - I have even tried using the startup package before using the Meteor class with no look.
and
Inside a js file included using: api.add_file I can't get the mongoose class:  mongoose is not defined

A: The solution as it seems is to use inside the add_file file:
var require = __meteor_bootstrap__.require;

That way I can use the require in there.

Edit: This doesn't actually solve all use cases as it only runs server side, so either I need a solution that will work both client side and server side or a way to declare requires in the package folder and using its return value some how.


text:
Q: Как добавить и зачем нужны BuildVariants? Вот я разбираюсь с тем как писать тесты для андроид и вот тут есть такое учебное пособие в течении обьяснений мы переключаем BuildVariants

*

*Только вот я так до конца не понял зачем нужны разные версии? Почему
бы не собрать все в одну?

*Как добаволять в этот выпадающий список свои названия и
конфигурации?

ПРАВКА
Немного понял исходя из ответа @temq как это работает только хотел бы уточнить еще несколько вопросов которые появились

*

*Насколько я понял, что когда в productFlavors создаешь свои
сборки вот так
productFlavors {
mock {
  applicationIdSuffix = ".mock"
}
prod {}
}

то , чтоб студия понимала от куда брать подтягивать изменения нужно
создать директорию в src с таким же именем, именно по имени студия
понимает что это именно так директория

Если названия будут отличаться то студия не поймет куда идти, верно?

*Хотел бы еще уточнить как студия подтягивает изменения в зависимости
от build variant
Я понял так, что за основу берется main и потом студия смотрит
какой build variant сейчас выбран и смотрит какие классы нужно
заменить... Но ведь названия классов отличаются.

Вот как на скриншоте допустим сейчас включена версия mockDebug. В
этом варианте мы используем другой класс из папки data то есть
студия должна взять за основу main дирикторию и понять, что
использовать файл FakeNotesServiceApiImpl вместо
NotesServiceApiImpl . Я полагаю что это можно понять сравнив пути
к классам они полностью похожи, но сами имена разные... Как это
будет работать?
Хотя вот судя по этой заметке, файлы не заменяются как я думал, а как то по другому это работает только теперь не понятно как

Files in the flavor-specific folders do not replace files in the main source set. Trying to do that will result in a duplicate class exception. This is a common misconception because it's how resources are merged.

*И вот еще насчет случая когда нужно собрать версию для релиза я так
понимаю, что для этого нужно в build variant выбрать
prodRelease, но не совсем понятно от куда в таком стучае студия
будет тянуть файлы? По логике должны собираться все файлы из
дериктории main, но согласно productFlavors студия должна тянуть
файлы из дириктории prod ... Не понятно.
И тут же вопрос чем отличаются в структуре файлов версии допустим
prodDebag и prodRelease если директория которая на них указывает
одна

или в этом случае будут браться в учет buildTypes ?

A: Вкратце, могут быть разные архитектуры, чаще всего разница в Release and Debug, практически во всех проектах, настраиваются в strucureProject,в gradle скриптах, чтоб предварительно к примеру использовать другой манифест или подключить другие либы, изменить Dependencies, изменить поведения debugger, арихвацию, подменить версию сборки, место установки и тд. Очень хорошо это дело описано в оф доках. Вопрос довольно объемный, так как на практике приходится немного больше писать, чем показывают в доках.
Вот пример, как у меня сейчас:

A: Build variants это всевозможные варианты сборки вашего приложения. По умолчанию это debug и release. Можно добавлять свои варианты редактируя buildTypes и productFlavors в build.gradle вашего приложения. Все это необходимо для вынесения/добавления определенной части логики которая зависит от определенного варианта, а так же сокрытия кода, который не относится к данному варианту сборки и т.д. Так же можно разбивать по вариантам и ресурсы.
Немного распишу про flavors. Обычно они используется для:

*

*реализации платной и демо версии приложения;

*реализации версии приложения где взаимодействие будет вестись не с
реальным сервером, а тестовым сервером, либо вообще будут отдаваться
заранее подготовленные ответы;

*реализации однотипных приложений, у которых есть общая кодовая база, например взаимодействие с сервером, и индивидуальная кодовая база, которая относится к конкретному приложению, например UI.

В вашем примере это как раз второй вариант, т.е. есть две версии приложения: одна смотрит на реальный сервер, а во второй все ответы заранее подготовлены. Разные версии приложения нужны в разные моменты времени, т.е. при выпуске используется Releas вариант, при тестировании Debug, при разработке Mock. Mock вариант так же полезен, когда приложение разрабатывается параллельно с серверной частью, т.е. сервера ещё нет, а приложение уже должно общаться с ним. Тут разработчики серверной части и мобильной договариваются друг с другом на счет запросов/ответов, и мобильный разработчик просто возвращает готовый ответ.
Как это все реализовать? Для этого необходимо в build.gradle файле модуля приложения добавить свой flavor:
android {
...
    defaultConfig {...}
    buildTypes {...}
    productFlavors {
        mock {
            ...
        }
        prod {
            ...
        }
    }
}

После чего появятся следующие варианты сборки приложения: debugMock, releaseMock, debugProd, debugMock. Столько вариантов получается, из за того что flavor's как бы перемножаются с build types. Т.е. создаются все возможные варианты.
После этого в папке src модуля приложения, рядом с папкой main можно создать папку с кодовой базой для каждого flavor'a. В каждой такой папке необходимо поддерживать одинаковые структуры пакетов, не запрещается добавлять и свои пакеты, которые будут доступны только в рамках данного flavor'a. Если код из flavor'a вызывается в общем коде, то необходимо чтобы имена классов и методов в разных flavor'ах совпадали. Тогда при компиляции будет использоваться код из папки main, плюс код из папки конкретного flavor'a. А так как, структура в разных flavor'ах одинаковая, то код подменится корректно, приложение скомпилируется без ошибок, не будет лишнего кода, который не имеет отношения к данному приложению, и это поможет избавиться от конструкций вида(псевдокод):
//Где то в константе храним текущий вариант
if(variantMock) {
    //вызываем замоканную версию
} else if(variantDebug) {
    //вызываем версию для дебага
} else if(...) // и так далее

UPD:

*

*Да, надо создать папку с таким же именем, так же можно комбинировать имена flavor'ов и build types, к примеру mockDebug, mockRelease и т.д.

*Если какие то классы используются в main пакете, например создается экземпляр объекта, то в разных flavor'ах эти классы должны иметь одинаковые имена и распологаться в одинаковом пакете, иначе в одном из вариантов будут появляться ошибки компиляции, т.к. студию не сможет найти класс по пути, указанному в импорте. Разные классы в основном пакете можно создавать через всякие фабрики, но тогда надо что бы они реализовывали какой то интерфейс, но тогда надо будет делать фабрики идентичными для разных flavor'одинаковом. Просто представьте что беруться все файлы из папки prod и копируются в папку main.

*Ресурсы и исходные коды мержаться из папок, соответствующих данному варианту. Т.е. если выбрали prodDebug то будут мержиться папки prod + main + если есть prodDebug/debug.
Просто попробуйте насоздавать flavor'ов и build type'ов и переопределите в каждой из папок какой нибудь текстовый ресурс который выводите на экране, сразу все станет понятней. Папки debug/release/prodDebug/prodRelease не являются обязательными к созданию. По сути и prod можно не создавать если ничего не надо переопределять.


text:
Q: TypeError: Cannot read property 'fetchMore' of undefined in Apollo I'm implementing an infinite scroll with Apollo and React. Everything works fine. When I navigate away from Feed and then back to Feed I'm getting this weird error:

TypeError: Cannot read property 'fetchMore' of undefined

Has anyone else had experience with this issue? I found this but there doesn't seem to yet be any solutions. One of the answers mentions a partial solution "checking the route before executing fetchMore" but I don't know what means.
I'm still in the middle of development so I haven't had a chance to clean this component up yet, but here it is:
import React, { useEffect, useRef } from 'react';
import { useQuery } from '@apollo/client';
import PostUpdateOrShow from '../posts/types/showOrUpdate/PostUpdateOrShow.js'
import Cookies from 'js-cookie';
import Queries from '../../graphql/queries';
import InfiniteScroll from './util/Infinite_Scroll.js';
const { FETCH_USER_FEED, FETCH_TAG_FEED } = Queries;

const Feed = ({
  user, tag
}) => {
  let fetchMoreDiv = useRef(null);
  let cursorId = useRef(null);

  useEffect(() => {
    var scroll = document.addEventListener('scroll', function(event) {
      fetchMoreDiv.current = document.querySelector('#fetchMore')
      var el = fetchMoreDiv.current.getBoundingClientRect()
      var elTop = el.top
      var elBottom = el.bottom
      var innerHeight = window.innerHeight

      if (elTop >= 0 && elBottom <= innerHeight) {
        fetchMore({
          query: gqlQuery,
          variables: {
            query: query,
            cursorId: cursorId.current
          },
        })
      }
    })

    return () => {
      document.removeEventListener('scroll', scroll)
    }
  })

  var gqlQuery
  var query
  if (user) {
   gqlQuery = FETCH_USER_FEED
   query = user.blogName
  } else if (tag) {
   gqlQuery = FETCH_TAG_FEED
   query = tag.title.slice(1)
  } else {
   gqlQuery = FETCH_USER_FEED
   query = Cookies.get('currentUser')
  }

  let { loading, error, data, fetchMore } = useQuery(gqlQuery, {
    variables: {
      query: query,
      cursorId: null
    },
  })

  if (loading) return 'Loading...';
  if (error) return `Error: ${error}`;

  const { fetchUserFeed, fetchTagFeed } = data

  cursorId.current = fetchUserFeed ? fetchUserFeed[fetchUserFeed.length - 1]._id :
  fetchTagFeed[fetchTagFeed.length - 1]._id

  if (tag) {
    return(

          {fetchTagFeed.map((post, i) => {
            return (

                <PostUpdateOrShow
                  post={post}
                />

            )
          })}

          <InfiniteScroll
            fetchMoreDiv={fetchMoreDiv}
          />

    )
  } else {
    return(

          {fetchUserFeed.map((post, i) => {
            return (

                <PostUpdateOrShow
                  post={post}
                />

            )
          })}

          <InfiniteScroll
            fetchMoreDiv={fetchMoreDiv}
          />

    )
  }
}

export default Feed;

Apollo client config:
const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache({
    typePolicies: {
      Query: {
       fields: {
         fetchLikesRepostsAndComments: {
           merge: (existing = [], incoming = []) => {
             return incoming
           }
        },
        fetchUserFeed: {
          keyArgs: ['query'],
            merge: (existing = [], incoming = []) => {
            const elements = [...existing, ...incoming].reduce((array, current) => {
              return array.map(i => i.__ref).includes(current.__ref) ? array : [...array, current];
            }, []);

            return elements
        },
        }
      }
    }
  }
  }),
  errorLink
})

A: I believe the issue is that you are using fetchMore within useEffect hook.
Try to rethink your code to avoid this. Using fetchMore outside the hook would work flawlessly.


text:
Q: Are Arduino inputs equivalent to voltage measurement? I read somewhere that Arduino input pins basically (more or less) just measure the voltage at their pins with respect to ground (and then, based on that, create an analogue value or a digital HIGH or LOW reading). Would that mean that the following two circuits are equivalent with regard to voltage measurement?

A:
Would that mean that the following two circuits are equivalent with regard to voltage measurement?

Measurement, not really, but essentially, yes, volts must change for the input to change.
The details though, are quite a bit more complicated than that.
If the pin is set to an analog input, then whatever voltage present on the pin is converted to a digital value by an internal component called a ADC or analog-to-digital-converter.  0V typically gets a value of 0, while the maximum volts is set to a value limited by the number of bits of resolution the ADC has.  An 8-bit ADC can output a value up to \$2^8\$ or 0-255, so max-volts would get a value of 255 in that case.
If the pin is set to a digital input, then voltages over some threshold like 2.2V are considered "high" or "1", while voltages under some other threshold like 1.8V are considered "low" or "0".  Due to the way these circuits are constructed, the in-between voltage range is generally a no-go area, where the internal components will draw excessive current and could possibly be damaged if left that way for too long.

A: No, because the top circuit only measures two levels.
The second circuit measures in much finer resolution.
For the top circuit to be equivalent to the second circuit, the top circuit would need to be an ADC pin, and not a normal digital input (general purpose IO, GPIO) pin.

A: Kinda, with the caveat that digital inputs can't measure the actual voltage, only tell you whether it is close to 5V or close to 0V.
Yes, the digital input tells you 1 (HIGH) if the voltage is close to 5V, and 0 (LOW) if it's close to 0V. An analog input actually measures the voltage and gives you a number that can be used to calculate the voltage.
Note that in-between voltages on digital pins are not allowed, except for short periods of time when the voltage changes from one to the other. In-between voltages can waste power because, as an over-simplification, they can activate both the 1 circuit and the 0 circuit in the chip, causing them to fight against each other. In extreme cases this can damage those circuits by overheating them. I've never heard of this actually happening to an Arduino, but it's a theoretical possibility.

Arduinos don't, but some chips such as TTL chips have inputs that source (push out) or sink (pull in) significant amounts of current. In this case it is not possible to say whether they are measuring voltage or current, because voltage and current happen together. Some chips (not sure which) might even have current inputs, where the chip keeps the voltage the same and senses the direction of the current instead.


text:
Q: Why Python doesn't have a native Linked List implementation? I have tried some quick experiment comparing the performance of native Python lists with linked lists implementations such as this.
The native python lists are always faster than the non native linked list in the cases where they should not be (according the theory).
from linkedlist import *
import time
a = LinkedList()
b = []
for i in range(1000000):
    b.append(i)
    a.add_first(i)
t0 = time.clock()
a.remove(10)
t1 = time.clock()
b.remove(10)
t2 = time.clock()
print t1-t0
print t2-t1

The results I have on the test above are:

*

*native linked list = 2.00000000001e-05

*python list = 0.005576

*non native linked list = 3.90000000001e-05
So, I was wondering why Python don't have a native Linked List data structure.
In the case of Python, it looks to me that it could be useful algorithmically speaking to have
Linked List instead of the standard Lists to speed up some aspects of the standard library.
My understanding is that the List data structure is a key building block of the language and that it makes the code more maintainable and easily optimizable to focus on that very data structure.
Is there any other reason?

A: Indeed, Python doesn't have a native linked list implementation, and I would also love to know why.
One alternative you may want to consider is collections.deque (= "double-ended queue") which provides very fast constant-time O(1) insertion at both ends. In fact, for your specific example, a deque is a better choice than a linked list, since you don't need insertion in the middle.
However, in general, it is important to keep in mind that a deque is a different data structure than a linked list. A linked list also provides constant-time O(1) insertion in the middle, while a deque only provides linear-time O(n) insertion in the middle. In other words, the time it takes to insert an element in the middle of a deque is proportional to the current length n of the deque, and for a sufficiently large n, it will be slower than with a linked list.
Comparison between collections.deque and a true linked list
Internally, collections.deque is in fact implemented using a linked list. However, this is an implementation detail, and more importantly, it is implemented as a linked list of fixed-size blocks of elements, not as a linked list of individual elements.
This is why insertion in the middle of a collections.deque is O(n) rather than O(1): you still need to modify around half the memory of the whole deque to accommodate a new element N:
before inserting N: [ABCDE]⇄[FGHIJ]⇄[KLM__]
after inserting N:  [ABCDE]⇄[FGNHI]⇄[JKLM_]
changed memory:                ^^^   ^^^^

Instead, with a true linked list (= of individual elements), inserting a new element N in the middle simply consists of allocating a new node and updating the value of four pointers, which is an operation whose performance is independent of the current size of the linked list:
before inserting N: [A]⇄[B]⇄[C]⇄[D]⇄[E]⇄[F]⇄[G]⇄    [H]⇄[I]⇄[J]⇄[K]⇄[L]⇄[M]
after inserting N:  [A]⇄[B]⇄[C]⇄[D]⇄[E]⇄[F]⇄[G]⇄[N]⇄[H]⇄[I]⇄[J]⇄[K]⇄[L]⇄[M]
changed memory:                                ^ ^ ^

The trade-off is that the deque has better memory locality and requires less independent memory allocations. For example, inserting the new element N in the deque above didn't require any new memory allocation at all. This is why in practice, and especially if you're often inserting at the ends rather than in the middle, a deque is in fact a better choice than a linked list.
Note that while inserting elements in the middle of a deque is O(n), inserting new elements at the beginning or the end is O(1):
before:                [ABCDE]⇄[FGNHI]⇄[JKLM_]

prepending P:  [____P]⇄[ABCDE]⇄[FGNHI]⇄[JKLM_]
                    ^ ^

prepending Q:  [___QP]⇄[ABCDE]⇄[FGNHI]⇄[JKLM_]
                   ^

appending R:   [___QP]⇄[ABCDE]⇄[FGNHI]⇄[JKLMR]
                                            ^

appending S:   [___QP]⇄[ABCDE]⇄[FGNHI]⇄[JKLMR]⇄[S____]
                                              ^ ^

Caveats
Of course, for the linked list insertion to actually be O(1), this assumes that you already have a handle h to the node before or after which you want to insert your new node n. On a hypothetical implementation of LinkedList, this could look like:
n = linkedlist.insertbefore(h, "some value")

where:
type(h)     # => <class 'Node'>
type(n)     # => <class 'Node'>
n.value     # => "some value"
n.next == h # => True

If you do not have such handle, then a function like insert(i, x) will still be O(n), because finding the i-th element is O(n), even though the insert operation itself is O(1). Here is some hypothetical implementation of insert(i, x) on our hypothetical LinkedList:
def insert(self, i, x):
    node = self.node_from_index(i)       # Find the i-th node: O(n)
    return self.insertbefore(node, x)    # Insert and return new node: O(1)

This means that linked lists are only worth it for certain problems when you do keep those node handles around. It also makes the API a bit less convenient, and despite each operation being O(1) if you're careful, the constant is generally much bigger. So in practice, they are not that often useful, which may be why they're aren't built-in linked lists in Python.

A: It's just because building list takes majority of the time rather than append method. So, when it's not a linear time operation as you showed, (ex : n^2 operation) append method will be more significant than building which will lead to the result you want to see.


text:
Q: Проблемы с line-height и прижатым футером

* {
  box-sizing: border-box;
}

body,
html,
ul,
li,
div,
h1,
h2,
h3,
h4,
h5 {
  margin: 0;
  padding: 0;
}

.row {
  margin-left: 0;
  margin-right: 0;
}

.row:before,
.row:after {
  content: '';
  display: table;
  clear: both;
}

html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  height: 100vh;
  font-size: 16px;
  background-color: #ccc;
}

.content {
  flex: 1 0 auto;
}

.footer,
.total-price {
  width: 100%;
  flex-shrink: 0;
}

.total-price {
  height: 60px;
  line-height: 60px;
  background-color: #2f3239;
  display: -webkit-flex;
  display: -moz-flex;
  display: -ms-flex;
  display: -o-flex;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
  -webkit-justify-content: space-between;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

.total-price .total-price-step .step {
  background-color: #3b3f48;
  border-right: 1px solid #2f3239;
  width: 60px;
  height: 60px;
  line-height: 60px;
  float: left;
  text-align: center;
  color: #fff;
  font-size: 14px;
  font-weight: bold;
}

.total-price .total-price-step .step.inactive {
  color: #4f535b;
  background-color: #2f3239;
  border-right-color: #4f535b;
}

.total-price .total-price-cost {
  height: 60px;
  color: #fff;
}

.total-price .total-price-cost span {
  display: inline;
}

.total-price .total-price-cost .price {
  margin-right: 30px;
  margin-left: 10px;
  color: #cd9a2b;
}

.total-price .total-price-cost .price .price-small {
  color: #fff;
}

.total-price .total-price-cost .text-900 {
  display: none;
}

.total-price .total-price-cost a {
  float: right;
  display: block;
  width: 150px;
  height: 60px;
  line-height: 58px;
  text-align: center;
  text-transform: uppercase;
  font-weight: bold;
  font-size: 12px;
  color: #fff;
  background-color: #cd9a2b;
  letter-spacing: 5px;
  border: 1px solid #cd9a2b;
}

.total-price .total-price-next span {
  display: inline;
  text-transform: uppercase;
  margin-right: 30px;
  letter-spacing: 4px;
  font-size: 12px;
  color: #4f535b;
}

.total-price .total-price-next a {
  float: right;
  position: relative;
  width: 60px;
  height: 60px;
  background: url(../img/icons/next-step.png) no-repeat center;
  background-color: #3b3f48;
}

.total-price .total-price-next.active span {
  color: #fff;
}

.total-price .total-price-next.active a {
  background-color: #cd9a2b;
}

.price {
  font-family: ProximaB;
  font-weight: bold;
  color: #333333;
  font-size: 40px;
}

.price .price-small {
  font-size: 18px;
  color: #333333;
  font-style: normal;
}

1

2

      Итоговая стоимость:
      Сумма:
      7 800 руб.
      Оплатить

Использовал хак для прижатия футера к низу отсюда: https://css-tricks.com/couple-takes-sticky-footer/
Возникла такая проблема:
После нижнего блока появляется отступ во всех браузерах. Причём, если убрать у класса .total-price свойство line-height: 60px; и повесить это свойство на .total-price .step и .total-price-cost a, то отступ в chrome исчезнет. Но останется в Firefox и IE 10,11 в виде тоненькой полоски, намного тоньше, чем была до этого.
Дальше больше:
Если повесить line-height: 58px на .total-price-cost a (т.к. рамка у него по 1px), то отступ пропадёт и в Firefox, но в злосчастном IE останется тоненькая полоска.
И наконец, финал:
Если удалить всё содержимое из тега с классом .total-price, то отступ в Chrome и Firefox пропадёт даже если у класса .total-price будет свойство line-height: 60px, а вот в IE по-прежнему отступ останется.
Прошу помощи у гуру-верстальщиков, которые мне объяснят, откуда появляются такие различные баги с этим свойством и как с ними бороться. (особенно в ie 10,11)
P.S. Добавил для body цвет фона, чтобы было понятно, где эта самая полоска снизу.

A: Замените line-height на 1:

* {
  box-sizing: border-box;
}

body,
html,
ul,
li,
div,
h1,
h2,
h3,
h4,
h5 {
  margin: 0;
  padding: 0;
}

.row {
  margin-left: 0;
  margin-right: 0;
}

.row:before,
.row:after {
  content: '';
  display: table;
  clear: both;
}

//Footer hack
html {
  height: 100%;
}

body {
  display: flex;
  flex-direction: column;
  height: 100vh;
  font-size: 16px;
  background-color: #ccc;
}

.content {
  flex: 1 0 auto;
}

.footer,
.total-price {
  width: 100%;
  flex-shrink: 0;
}

.total-price {
  height: 60px;
  line-height: 1;
  background-color: #2f3239;
  display: -webkit-flex;
  display: -moz-flex;
  display: -ms-flex;
  display: -o-flex;
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-pack: justify;
  -webkit-justify-content: space-between;
  -ms-flex-pack: justify;
  justify-content: space-between;
}

.total-price .total-price-step .step {
  background-color: #3b3f48;
  border-right: 1px solid #2f3239;
  width: 60px;
  height: 60px;
  line-height: 60px;
  float: left;
  text-align: center;
  color: #fff;
  font-size: 14px;
  font-weight: bold;
}

.total-price .total-price-step .step.inactive {
  color: #4f535b;
  background-color: #2f3239;
  border-right-color: #4f535b;
}

.total-price .total-price-cost {
  height: 60px;
  color: #fff;
}

.total-price .total-price-cost span {
  display: inline;
}

.total-price .total-price-cost .price {
  margin-right: 30px;
  margin-left: 10px;
  color: #cd9a2b;
}

.total-price .total-price-cost .price .price-small {
  color: #fff;
}

.total-price .total-price-cost .text-900 {
  display: none;
}

.total-price .total-price-cost a {
  float: right;
  display: block;
  width: 150px;
  height: 60px;
  line-height: 58px;
  text-align: center;
  text-transform: uppercase;
  font-weight: bold;
  font-size: 12px;
  color: #fff;
  background-color: #cd9a2b;
  letter-spacing: 5px;
  border: 1px solid #cd9a2b;
}

.total-price .total-price-next span {
  display: inline;
  text-transform: uppercase;
  margin-right: 30px;
  letter-spacing: 4px;
  font-size: 12px;
  color: #4f535b;
}

.total-price .total-price-next a {
  float: right;
  position: relative;
  width: 60px;
  height: 60px;
  background: url(../img/icons/next-step.png) no-repeat center;
  background-color: #3b3f48;
}

.total-price .total-price-next.active span {
  color: #fff;
}

.total-price .total-price-next.active a {
  background-color: #cd9a2b;
}

.price {
  font-family: ProximaB;
  font-weight: bold;
  color: #333333;
  font-size: 40px;
}

.price .price-small {
  font-size: 18px;
  color: #333333;
  font-style: normal;
}

1

2

      Итоговая стоимость:
      Сумма:
      7 800 руб.
      Оплатить


text:
Q: just got new imac with fresh Mavericks install, old data still remaining, how to find and delete? I just bought a 24' used iMac.
The previous owner reinstalled Mavericks and sent it to me.
I looked at the disk usage info and it appears as if all the old data, movies, music, and everything else, is still there. Only 100gigs are free on a 500gig drive.
Is there a way to find this old data and reclaim my hard drive space?
I don't have a disk.

A: You do not need a disk to reinstall Mavericks, since it has a recovery partition that will download Mavericks and do a fresh install, if you prefer to do that.
Erase and reinstall Mavericks: http://support.apple.com/kb/PH14243
Otherwise, you can probably just delete the user account, which will offer to delete all the user's info, freeing up considerable space.

A: I would start with this plan. Get a backup disk or connect a USB drive that you can dedicate to backing up your iMac. Get a full Time Machine backup so you can experiment and delete things.
Lion and later (10.7) need no disk to run maintenance and reinstall the OS. You can boot to recovery to wipe the drive and reinstall the core OS. Do keep in mind, you might lose some apps like iLife or iWork if they were installed - which is why it's nice to have a backup before you wipe anything.
Also - you could look in the Apple Menu - open the About this Mac and then click more info. Then click on storage to see what sorts of files are taking up space on the Mac.

A: You could download 'DaisyDisk' and let it analyze your Disk. You get a very good overview what Files are using up your Space.


text:
Q: htaccess - prettify a minified version I have an .htaccess with a good number of redirects. After being modified by a Wordpress plugin, it appears that all the rules have been concatenated; at least no line breaks are visible.
Edit:
This seems to be a problem only when the file is opened in Windows Notepad. When I open it with Sublime, or even copy a snippet to here, it shows the line breaks. I toggled line-wrap in Notepad, but it still treats the whole thing as a single line.

A:
This seems to be a problem only when the file is opened in Windows Notepad.

This is because the file has non-Windows line endings (\r\n), but probably Linux line endings (\n). Windows Notepad only recognizes Windows line endings.
You can use Notepad++ to convert line endings, but this does not stop Wordpress to apply the linux line endings, obviously.


text:
Q: Reading from CSV file and "save" it's contents to List objects and load them in Program.cs My goal with my small Console Application is to read from a CSV file and save it's contents inside a List (which works). I have a separate class with this method. See the uncommented section in UserList.cs:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Globalization;
using System.Linq;
using CsvHelper;

namespace GimpiesConsoleOOcsvListUI
{
    public class UserList
    {
        // public static List<User> DefaultUsers()
        // {
        //     // First line to skip a row and position all users correctly under the right headers
        //     User user0 = new User("", "", "", "");
        //     // Create user default instances
        //     User user1 = new User("Beheer", "beheer@gimpies.nl", "123", "admin");
        //     User user2 = new User("Inkoop", "inkoop@gimpies.nl", "123", "purchase");
        //     User user3 = new User("Verkoop", "verkoop@gimpies.nl", "123", "sales");
        //     // List of users (with a list you can add, get and remove items in the list)
        //     List<User> users = new List<User>();
        //     users.Add(user0);
        //     users.Add(user1);
        //     users.Add(user2);
        //     users.Add(user3);

        //     // Return all the users in the List to other classes
        //     return users;
        // }

        public void LoadUsersFromCSV(List<User> users)
        {
            // using (var mem = new MemoryStream())
            // using (var writer = new StreamWriter(mem))
            using (var reader = new StreamReader("users.csv"))
            using (var csvReader = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                try
                {
                    csvReader.Configuration.Delimiter = ";";
                    csvReader.Configuration.IgnoreBlankLines = true;
                    csvReader.Configuration.HasHeaderRecord = true;
                    csvReader.Configuration.PrepareHeaderForMatch = (string header, int index) => header.ToLower();
                    csvReader.Configuration.MissingFieldFound = null;
                    csvReader.Read();
                    csvReader.ReadHeader();

                    // Store all content inside a new List as objetcs
                    var usersfromcsv = csvReader.GetRecords<User>().ToList();

                    // return users;

                }
                catch (CsvHelper.HeaderValidationException exception)
                {
                    Console.WriteLine(exception);
                }

            }

        }
    }
}

In my Program.cs I want to call this method and use the contents of that created List to use the login code. So to check if the username and password are typed correctly and users can log in.
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Globalization;
using System.Linq;
using CsvHelper;

namespace GimpiesConsoleOOcsvListUI
{
    class Program
    {
        static void Main(string[] args)
        {
            // List of default users
            // List<User> users = UserList.DefaultUsers();

            // Working on it... Try to read csv file first and try to read list from method in UserList.cs
            // UserList ul = new UserList();
            List<User> users = UserList.LoadUsersFromCSV();
            // List<User> users =
            // ul.LoadUsersFromCSV(users);

            // Create login instance
            LoginManager loginMgr = new LoginManager();

            // Create stock instance
            Stock stock = new Stock();

            Start:
            // Welcome message
            Console.WriteLine("Welcome to the Gimpies Console Application! Choose 1 to login or 2 to exit this application:");

            // Get input from user
            string input = Console.ReadLine();

            // Set to false to check if login fails or not
            bool successfull = false;

            while (!successfull)
            {
                if(input == "1")
                {
                    Console.WriteLine("Enter your username:");
                    string username = Console.ReadLine();
                    Console.WriteLine("Enter your password:");
                    string password = Console.ReadLine();

                    foreach (User user in users)
                    {
                        if (username == user.username && password == user.password && user.userrole == "admin")
                            {
                                // Create Admin instance to be able to call methods in that class
                                Admin am = new Admin();
                                // Calling the method in Admin.cs to start Menu logic
                                am.AdminLoggedIn(users);

                                successfull = true;
                                break;
                            }

                        if (username == user.username && password == user.password && user.userrole == "purchase")
                            {
                                // Create Purchase instance to be able to call methods in that class
                                Purchase pc = new Purchase();
                                // Calling the method in Purchase.cs to start Menu logic
                                pc.PurchaseLoggedIn(users);

                                successfull = true;
                                break;
                            }

                        if (username == user.username && password == user.password && user.userrole == "sales")
                            {
                                // Create Sales instance to be able to call methods in that class
                                Sales sl = new Sales();
                                // Calling the method in Sales.cs to start Menu logic
                                sl.SalesLoggedIn(users);

                                successfull = true;
                                break;
                            }
                    }

                        if (!successfull)
                            {
                                Console.WriteLine("Your username or password is incorrect, try again !!!");
                            }
                }

                else if (input == "2")
                {
                    Environment.Exit(-1);
                }

                else if (input == "3")
                {
                    FileOperations fo = new FileOperations();
                    // Calling the method from FileOperations.cs to write the List here to a CSV file
                    fo.WriteUsersToCSV(users);
                    goto Start;
                }

                else if (input == "4")
                {
                    FileOperations fo = new FileOperations();
                    // Calling the method from FileOperations.cs to write the List here to a CSV file
                    fo.ReadUsersFromCSV(users);
                    goto Start;
                }

                else
                {
                    Console.WriteLine("Try again !!!");
                    break;
                }
            }

            // // Loop over stored users within instances inside the list where users are added
            // foreach (User user in users)
            // {

            //     if(loginMgr.Login(user))
            //     {
            //         // Login successfull
            //         Console.WriteLine("Login user " + user.UserName);

            //     }
            //     else
            //     {
            //         // Not successfull

            //     }
            // }

        }
    }
}

I'm getting this error:
Program.cs(20,41): error CS7036: There is no argument given that corresponds to the required formal parameter 'users' of 'UserList.LoadUsersFromCSV(List<User>)' [/home/pascalmariany/Projects/Csharp/GimpiesConsoleOOcsvList/GimpiesConsoleOOcsvListUI/GimpiesConsoleOOcsvListUI.csproj]

This is my User.cs with it's constructor:
namespace GimpiesConsoleOOcsvListUI
{
    public class User
    {
        // Constructor
        public User(string username, string email, string password, string userrole)
        {
            _UserName = username;
            _Email = email;
            _Password = password;
            _UserRole = userrole;
        }

        private string _UserName;
        private string _Email;
        private string _Password;
        private string _UserRole;

        public string username
        {
            get { return _UserName; }
            set { _UserName = value; }
        }

        public string email
        {
            get { return _Email; }
            set { _Email = value; }
        }

        public string password
        {
            get { return _Password; }
            set { _Password = value; }
        }

        public string userrole
        {
            get { return _UserRole; }
            set { _UserRole = value; }
        }

    }
}

What do I need to change to reach my goal?

A: Youve declared your LoadUsersFromCsv method as "takes a list":
public void LoadUsersFromCSV(List<User> users)

but you're trying to use it like "takes nothing and returns a list"
List<User> users = UserList.LoadUsersFromCSV();

The compiler is complaining because you didn't supply a List in the "users" parameter

Looking at the code, it reads the file in and turns it into a list but doesn't return it and it doesn't fill the list it was given either..
I'd suggest you change the LoadUsers method so it returns the list it reads, change it from void to List<User> and remove the users parameter


text:
Q: prove that AD, BE, CF are also concurrent equilateral triangles DBC, ECA and FAB are constructed externally on the sides BC,CA,AB respectively of triangle ABC. Prove that AD, BE, and CF are also concurrent.
i need an approach pl.
the 3 triangles are obviously similar..

A: The intersection point is known as the Fermat First Point. It's the point from which the sum of the distance to each vertex is minimized. The proof that the three line concur at one point can be see in the link above.


text:
Q: Emulating reshape2::melt with pivot_longer for matrixes i just tried to use pivot_longer on a 2D Matrix to get "tidy" data for ggplot. So far that was pretty straight forward with reshape2::melt
library(tidyverse)
library(reshape2)

x <- c(1, 2, 3, 4)
y <- c(1, 2, 3)

Data      <- matrix(round(rnorm(12, 10, 4)), nrow = 4, ncol = 3)
melt_data <- reshape2::melt(Data)

ggplot2::ggplot(meltvec, ggplot2::aes(x = Var1, y = Var2, fill = value)) +
   geom_tile()

However, pivot_longer needs a tibble or data.frame. So i came up with following function:
matrix_longer <- function(.data){
  stopifnot(is.matrix(.data),
            !is.data.frame(.data))

  .data <- as.data.frame(.data)
  names(.data) <- 1:ncol(.data)

  .data$Var1 =1:nrow(.data)

   pivot_longer(.data,cols = as.character( 1:(ncol(.data)-1)), names_to = "Var2", values_to = "value") %>%
     arrange(Var2) %>%
     mutate(Var2=as.numeric(Var2))
 }

And it produces the same output
own_data <- matrix_longer(Data)

ggplot2::ggplot(own_data, ggplot2::aes(x = Var1, y = Var2, fill = value)) +
   geom_tile()

all(own_data==melt_data)

The question is: Is there a better solution? Should/Can i just stick with reshape2::melt? Is it a bad idea to use .data?

A: To get a three-column dataframe of row and column indices and values from a matrix you can simply use as.data.frame.table():
set.seed(9)
Data <- matrix(round(rnorm(12, 10, 4)), nrow = 4, ncol = 3)

as.data.frame.table(Data, responseName = "value")

   Var1 Var2 value
1     A    A    10
2     B    A     9
3     C    A    17
4     D    A     7
5     A    B    10
6     B    B     0
7     C    B    14
8     D    B     7
9     A    C    17
10    B    C    11
11    C    C     9
12    D    C    14

If you want the indices to be integers rather than alphanumeric values (factors by default), you can do:
library(dplyr)

as.data.frame.table(Data, responseName = "value") %>%
  mutate_if(is.factor, as.integer)

   Var1 Var2 value
1     1    1    10
2     2    1     9
3     3    1    17
4     4    1     7
5     1    2    10
6     2    2     0
7     3    2    14
8     4    2     7
9     1    3    17
10    2    3    11
11    3    3     9
12    4    3    14