Backbone and Require.js not finding certain modules at specific level of defines

Question: Is there a limit to the number of dependencies Require.js will validly call? I'm getting strange 404 errors that I can't seem to debug.
I have the following structure:
-js
--views
---guide
----chapter.js
----guide.js
----section.js
----sidebar.js

In my router.js file, I do:
define([

    'underscore',
    'backbone',

    'views/guide/guide'
], function(_, Backbone, guideView) {
});

In guide.js:
define([
    'underscore',
    'backbone',
    './sidebar',
], function(_, Backbone, sidebarView) {
});

In sidebar.js:
define([
    'underscore',
    'backbone',
    'jquery',
    'easing',
    'audiojs',
    'markdown',

    './chapter'
], function(_, Backbone, $, easing, audiojs, markdown, chapterView) {
});

Finally, in chapter.js:
define([
    'underscore',
    'backbone',
    'jquery',
    'easing',
    'audiojs',
    'markdown',

    './section.js',

    'lib/text!templates/guide/chapter.html',
], function(_, Backbone, $, easing, audiojs, markdown , sectionView, template) {
});

For the LAST one, I get a 404 error:
http://localhost/testapp/views/guide/section.js?bust=1372855006799

It seems to be dropping 'js' from the file path and I have no idea why, unless there's some limit to how many levels of dependency I can call, or something like that.
Any thoughts?
Answer: you dont need to use the .js in your paths, require knows that you are trying to load javascriptfiles so there is not need to put them. try removing the .js
 './section',

and also I think you have an extra comma at the end of the template definition as is the last one.
 'lib/text!templates/guide/chapter.html'

And I dont think there is a limit on the levels of dependency.
Comment: Holy god you gotta be kidding me. I have no idea how I missed that. Thank you for pointing that out, that fixed it. GUUUHH


How to render HTML of entity?

Question: I have created my custom entities using Entity Construction Kit module.
Is it possible to  render an HTML output of entity programatically? So I could display an entity for example in block?
I have found function entity_view, but it returns only array, not whole HTML output.
For now, I am using Views to achieve this. I create a view that displays one instance, and  I am using function view_embed_view to display HTML.
But is there any direct function, so I don't need to create a view?
Answer: If you've got it working with entity_view, you probably just need to use:
print render($entity);

where $entity is the render array returned from entity_view.

How to render HTML of entity?


duvida com angularjs, input e metodo onblur()

Question: Como faço para um input chamar uma função?
O campo é um cep, quero que quando o usuario sair desse campo, seja chamado a função getCep().
Sei que no JavaScript tem a função onblur, mas com AngularJs não achei um jeito de fazer isso.
Comment: Para um input chamar uma função não é necessario chamar o Angular, a nao ser que voce queira alterar o estado de um objeto no angular,, portanto basta chamar ``
Answer: Se a sua função estiver dentro do escopo de seu controller, você pode fazer simplesmente, usando o ng-blur:
 <input type="text" ng-blur="getCep()">

Caso não esteja, faça com o onBlur mesmo:
 <input type="text" onblur="getCep()">

Exemplo

function controller($scope){
  $scope.getCep = function(){
   $scope.demo = $scope.cep;
  }
}

<input type="text"
       ng-model="cep"
       ng-blur="getCep()"
       ng-focus="demo = ''"
 >

{{demo}}

No exemplo acima apenas simulei a função getCep() fazendo que ela mostra o que foi digitado ao dar um blur na caixa de texto. Da mesma forma usei o ng-focus para deixar a var demo vazia.
Comment: deu certo amigão, muito obrigado.


Is the speed/performance of webgl on RaspianOS (Debian64) via VirtualBox the same as on an actual RaspberryPi?

Question: My question is simple. If anyone knows the answer I'd appreciate input. I'm running Raspian OS (Debian64bit) via VirtualBox and it seems to be running my webgl code fine. But I'd like to know if the performance would be the same on a Raspberry Pi running the same OS. I don't know if the specs matter. let me know if they do and I can post them.
Answer: No its not, you're not emulating the hardware of a raspberry pi but just the architecture.
Comment: should i expect worse or better performance from webgl and the gpu? or is there no way of telling?
Comment: to clarify i mean should i expect better or worse performance on the Pi?  What percentage increase/decrease in performance would you say occurs on average for gpu intensive applications?
Comment: There is no average, there is too many factors involved, specs of your host system, settings in virtualbox, driver versions, then for the emulated and actual raspberry PI: OS version, driver versions, browser version, background processes running, environment temperature and last but not least the efficiency of your javascript code, the efficiency of your glsl code and then the general silicone lottery. For cross platform development there's just no way around testing your application on the actual target platform.


Get Sub-Files with folders' IDs - Client Object Model

Question: I want to get some folders - sub files. I have all folders SharePoint ID in a list. My code is working but it's performance very bad because there is a lot of context.ExecuteQuery;
I want to make it maybe with a Caml Query.
using (var context = new ClientContext("http://xxx/haberlesme/"))
{
    var web = context.Web;
    var list = context.Web.Lists.GetById(new Guid(target));

    int[] siraliIdArray;
    //siraliIdArray = loadSharePointIDList(); think like this

    for (var j = 0; j < siraliIdArray.Count; j++)
    {
        var folderName = listItemCollection[j]["Title"].ToString();//Folder Name
        var currentFolder = web.GetFolderByServerRelativeUrl("/haberlesme/Notice/" + folderName);
        var currentFiles = currentFolder.Files;

        context.Load(currentFiles);

        //I don't want to execute for n folder n times. I want to execute n folder 1 time.
        context.ExecuteQuery();

        var ek = new LDTOTebligEk();

        //I don't want to add one - one
        foreach (var file1 in currentFiles)
        {
            ek.DokumanPath = urlPrefix + folderName + "/" + file1.Name;
            ek.DokumanAd = file1.Name;

            ekler.Add(ek);

        }
    }
}

For example I have 100 folder but I want to get 10 folders sub folder in one Execution
Comment: Is `cLientcontext` an entity file generated by SPMetal.exe?
Comment: no it is a class like 'public class ClientContext : ClientRuntimeContext' at 'Microsoft.SharePoint.Client.dll'
Comment: I have edited your title. Please see, "[Should questions include "tags" in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not".
Answer: Since CSOM API supports Request Batching:

The CSOM programming model is built around request batching. When you
  work with the CSOM, you can perform a series of data operations on the
  ClientContext object. These operations are submitted to the server in
  a single request when you call the ClientContext.BeginExecuteQuery
  method.

you could refactor your code as demonstrated below:
var folders = new Dictionary<string,Microsoft.SharePoint.Client.Folder>();
var folderNames = new[] {"Orders","Requests"};
foreach (var folderName in  folderNames)
{
   var folderKey = string.Format("/Shared Documents/{0}", folderName);
   folders[folderKey] = context.Web.GetFolderByServerRelativeUrl(folderKey);
   context.Load(folders[folderKey],f => f.Files);
}
context.ExecuteQuery();  //execute request only once

//print all files
var allFiles = folders.SelectMany(folder => folder.Value.Files);
foreach (var file in allFiles)
{
   Console.WriteLine(file.Name);
}

Answer: Use Caml Query:
Microsoft.SharePoint.Client.List list = clientContext.Web.Lists.GetByTitle("Main Folder");

Microsoft.SharePoint.Client.CamlQuery caml = new Microsoft.SharePoint.Client.CamlQuery();

caml.ViewXml = @"<View><Query><Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='Folder'>SubFolderName</Value></Eq></Where></Query></View>";

caml.FolderServerRelativeUrl = " This line should be added if the main folder is not in the site layer";

Microsoft.SharePoint.Client.ListItemCollection items = list.GetItems(caml);

clientContext.Load(items);

//Get your folder using items[0]


Prove that $k$ is of the form $pn^2 \pm 2cn + a$

Question: I'm trying to do this problem (Underwood and Dudley, Elementary Number Theory, pg. 181, #53):

If $p$ is a prime and $ap + b = c^2$, then show that all values of $k$ making $kp + b$ a square are given by $k = pn^2 \pm 2cn + a$ where $n$ is any integer.

It's straightforward to show that any $k$ satisfying $k = pn^2 \pm 2cn + a$ makes $kp + b$ a square:
$$\begin{align*}
(pn^2 \pm 2cn + a)p + b &= (pn)^2 \pm 2cpn + ap + b \\
&= (pn)^2 \pm 2cpn + c^2 \\
&= (pn \pm c)^2
\end{align*}
$$
However I can't figure out how to approach the other direction. A hint would be appreciated.
Answer: ARGH, I figured it out as soon as I proofread my question. I'll leave this here in case this is interesting for anybody else.
Let $kp + b = x^2$. Then $x^2 \equiv c^2 \mod p$, and since $p$ is prime, either $x \equiv c $ or $x \equiv -c \mod p$. So there exists an integer $n$ such that either $x = pn + c$ or $x = pn - c$. Write $x = pn \pm c$ to handle both cases at once. Then
$$ kp + b = (pn \pm c)^2$$
which means
$$ kp = p^2 n^2 \pm 2pnc + c^2 - b $$
and since $c^2 = ap + b$, we have
$$ kp = p^2 n^2 \pm 2pnc + ap $$
which implies
$$ k = p(n^2 \pm 2nc + a) $$
as desired.


How to add a collection_select in a form within another form

Question: I want to add a collection_select from a form I want to be within another form.
I have a Product model, with:
has_many :distribution_companies
has_many :distributors, :through => :distribution_companies, :source => :company

and Company model, with:
has_many :distribution_companies
has_many :distributed_products, :through => :distribution_companies, :source => :product

(The distribution_companies has only the references to the mentioned models)
This is the form (don't pay attention on the indentation):
= form_for @product, html: { :multipart => true } do |f|
= f.label :name do
  Name
= f.text_field :name

/.../

= f.fields_for :distribution_companies do |pn|
= pn.collection_select :company_id, Company.all, :id, :name

= f.submit 'Create the product'

I need to add select a company for the @product and store that in the distribution_companies table. I tried as abowe (also with pn.object.coll...). Any idea?
Comment: May be you are missing `accepts_nested_attributes_for :distribution_companies` in your `Product` model.
Comment: Can you post your controller,may be you are missing `@product.distribution_companies.build`in the new method.
Comment: @Pavan If I had any rep points, you would get even a vote up :)
Comment: Can you post the `log` generated when you `submit` the form
Comment: Did you try adding what i suggested?
Comment: @Pavan `accepts_nested_attributes_for :distribution_companies` is already in the Product model. Nothing shows on the form (no drop down list) so, there's nothing to see in the log about it.
Comment: Atleast there would be some parameters generated.Can you post it in the question please.
Comment: try `f.fields_for :distribution_company do |pn|`
Comment: @nithin OP has `has_many` relation.So your suggestion won't work.
Comment: @DR_ `DistributionCompany` model?
Comment: @Pavan thanks, I forgot the initialization: `@product.distribution_companies.build`
Comment: I will be adding it as answer,please accept it by ticking the tick mark green :)
Answer: As i said ,you have to add @product.distribution_companies.build to the new method of our controller.
def new
  @product = Product.new
  @product.distribution_companies.build
end


View dentro de uma área como default no MVC

Question: Como posso fazer para que uma view que esta dentro de uma área seja a default quando rodar a aplicação?
Erro que eu estou recebendo:

Minha estrutura:

Meu arquivo RouteConfig

Isso que eu fiz abaixo não funcionou.

namespace WebApplication1
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapRoute(
                name: "Default",
                url: "{area}/{controller}/{action}/{id}",
                defaults: new { area = "Administracao", controller = "Usuarios", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

Obrigado
Answer: A rota está ok. O grande problema aqui está no View Engine, que não é algo simples de resolver. Vou traduzir esta resposta do SO gringo:
Primeiro você precisa criar um View Engine que olhe sobre as áreas do seu projeto. Em meus projetos, uso o namespace MeuProjeto.Infrastructure.ViewEngines:
BaseAreaAwareViewEngine.cs
public abstract class BaseAreaAwareViewEngine : VirtualPathProviderViewEngine
{
    private static readonly string[] EmptyLocations = { };

    public override ViewEngineResult FindView(
        ControllerContext controllerContext, string viewName,
        string masterName, bool useCache)
    {
        if (controllerContext == null)
        {
            throw new ArgumentNullException("controllerContext");
        }
        if (string.IsNullOrEmpty(viewName))
        {
            throw new ArgumentNullException(viewName,
                "Value cannot be null or empty.");
        }

        string area = getArea(controllerContext);
        return FindAreaView(controllerContext, area, viewName,
            masterName, useCache);
    }

    public override ViewEngineResult FindPartialView(
        ControllerContext controllerContext, string partialViewName,
        bool useCache)
    {
        if (controllerContext == null)
        {
            throw new ArgumentNullException("controllerContext");
        }
        if (string.IsNullOrEmpty(partialViewName))
        {
            throw new ArgumentNullException(partialViewName,
                "Value cannot be null or empty.");
        }

        string area = getArea(controllerContext);
        return FindAreaPartialView(controllerContext, area,
            partialViewName, useCache);
    }

    protected virtual ViewEngineResult FindAreaView(
        ControllerContext controllerContext, string areaName, string viewName,
        string masterName, bool useCache)
    {
        string controllerName =
            controllerContext.RouteData.GetRequiredString("controller");
        string[] searchedViewPaths;
        string viewPath = GetPath(controllerContext, ViewLocationFormats,
            "ViewLocationFormats", viewName, controllerName, areaName, "View",
            useCache, out searchedViewPaths);
        string[] searchedMasterPaths;
        string masterPath = GetPath(controllerContext, MasterLocationFormats,
            "MasterLocationFormats", masterName, controllerName, areaName,
            "Master", useCache, out searchedMasterPaths);
        if (!string.IsNullOrEmpty(viewPath) &&
            (!string.IsNullOrEmpty(masterPath) ||
              string.IsNullOrEmpty(masterName)))
        {
            return new ViewEngineResult(CreateView(controllerContext, viewPath,
                masterPath), this);
        }
        return new ViewEngineResult(
            searchedViewPaths.Union<string>(searchedMasterPaths));
    }

    protected virtual ViewEngineResult FindAreaPartialView(
        ControllerContext controllerContext, string areaName,
        string viewName, bool useCache)
    {
        string controllerName =
            controllerContext.RouteData.GetRequiredString("controller");
        string[] searchedViewPaths;
        string partialViewPath = GetPath(controllerContext,
            ViewLocationFormats, "PartialViewLocationFormats", viewName,
            controllerName, areaName, "Partial", useCache,
            out searchedViewPaths);
        if (!string.IsNullOrEmpty(partialViewPath))
        {
            return new ViewEngineResult(CreatePartialView(controllerContext,
                partialViewPath), this);
        }
        return new ViewEngineResult(searchedViewPaths);
    }

    protected string CreateCacheKey(string prefix, string name,
        string controller, string area)
    {
        return string.Format(CultureInfo.InvariantCulture,
            ":ViewCacheEntry:{0}:{1}:{2}:{3}:{4}:",
            base.GetType().AssemblyQualifiedName,
            prefix, name, controller, area);
    }

    protected string GetPath(ControllerContext controllerContext,
        string[] locations, string locationsPropertyName, string name,
        string controllerName, string areaName, string cacheKeyPrefix,
        bool useCache, out string[] searchedLocations)
    {
        searchedLocations = EmptyLocations;
        if (string.IsNullOrEmpty(name))
        {
            return string.Empty;
        }
        if ((locations == null) || (locations.Length == 0))
        {
            throw new InvalidOperationException(string.Format("The property " +
                "'{0}' cannot be null or empty.", locationsPropertyName));
        }
        bool isSpecificPath = IsSpecificPath(name);
        string key = CreateCacheKey(cacheKeyPrefix, name,
            isSpecificPath ? string.Empty : controllerName,
            isSpecificPath ? string.Empty : areaName);
        if (useCache)
        {
            string viewLocation = ViewLocationCache.GetViewLocation(
                controllerContext.HttpContext, key);
            if (viewLocation != null)
            {
                return viewLocation;
            }
        }
        if (!isSpecificPath)
        {
            return GetPathFromGeneralName(controllerContext, locations, name,
                controllerName, areaName, key, ref searchedLocations);
        }
        return GetPathFromSpecificName(controllerContext, name, key,
            ref searchedLocations);
    }

    protected string GetPathFromGeneralName(ControllerContext controllerContext,
        string[] locations, string name, string controllerName,
        string areaName, string cacheKey, ref string[] searchedLocations)
    {
        string virtualPath = string.Empty;
        searchedLocations = new string[locations.Length];
        for (int i = 0; i < locations.Length; i++)
        {
            if (string.IsNullOrEmpty(areaName) && locations[i].Contains("{2}"))
            {
                continue;
            }
            string testPath = string.Format(CultureInfo.InvariantCulture,
                locations[i], name, controllerName, areaName);
            if (FileExists(controllerContext, testPath))
            {
                searchedLocations = EmptyLocations;
                virtualPath = testPath;
                ViewLocationCache.InsertViewLocation(
                    controllerContext.HttpContext, cacheKey, virtualPath);
                return virtualPath;
            }
            searchedLocations[i] = testPath;
        }
        return virtualPath;
    }

    protected string GetPathFromSpecificName(
        ControllerContext controllerContext, string name, string cacheKey,
        ref string[] searchedLocations)
    {
        string virtualPath = name;
        if (!FileExists(controllerContext, name))
        {
            virtualPath = string.Empty;
            searchedLocations = new string[] { name };
        }
        ViewLocationCache.InsertViewLocation(controllerContext.HttpContext,
            cacheKey, virtualPath);
        return virtualPath;
    }

    protected string getArea(ControllerContext controllerContext)
    {
        // First try to get area from a RouteValue override, like one specified in the Defaults arg to a Route.
        object areaO;
        controllerContext.RouteData.Values.TryGetValue("area", out areaO);

        // If not specified, try to get it from the Controller's namespace
        if (areaO != null)
            return (string)areaO;

        string namespa = controllerContext.Controller.GetType().Namespace;
        int areaStart = namespa.IndexOf("Areas.");
        if (areaStart == -1)
            return null;

        areaStart += 6;
        int areaEnd = namespa.IndexOf('.', areaStart + 1);
        string area = namespa.Substring(areaStart, areaEnd - areaStart);
        return area;
    }

    protected static bool IsSpecificPath(string name)
    {
        char ch = name[0];
        if (ch != '~')
        {
            return (ch == '/');
        }
        return true;
    }
}

Como a classe é abstrata, você precisará também criar a classe que deriva BaseAreaAwareViewEngine:
AreaAwareViewEngine.cs
public class AreaAwareViewEngine : BaseAreaAwareViewEngine
{
    public AreaAwareViewEngine()
    {
        MasterLocationFormats = new string[]
        {
            "~/Areas/{2}/Views/{1}/{0}.master",
            "~/Areas/{2}/Views/{1}/{0}.cshtml",
            "~/Areas/{2}/Views/Shared/{0}.master",
            "~/Areas/{2}/Views/Shared/{0}.cshtml",
            "~/Views/{1}/{0}.master",
            "~/Views/{1}/{0}.cshtml",
            "~/Views/Shared/{0}.master"
            "~/Views/Shared/{0}.cshtml"
        };
        ViewLocationFormats = new string[]
        {
            "~/Areas/{2}/Views/{1}/{0}.aspx",
            "~/Areas/{2}/Views/{1}/{0}.ascx",
            "~/Areas/{2}/Views/{1}/{0}.cshtml",
            "~/Areas/{2}/Views/Shared/{0}.aspx",
            "~/Areas/{2}/Views/Shared/{0}.ascx",
            "~/Areas/{2}/Views/Shared/{0}.cshtml",
            "~/Views/{1}/{0}.aspx",
            "~/Views/{1}/{0}.ascx",
            "~/Views/{1}/{0}.cshtml",
            "~/Views/Shared/{0}.aspx"
            "~/Views/Shared/{0}.ascx"
            "~/Views/Shared/{0}.cshtml"
        };
        PartialViewLocationFormats = ViewLocationFormats;
    }

    protected override IView CreatePartialView(
        ControllerContext controllerContext, string partialPath)
    {
        if (partialPath.EndsWith(".cshtml"))
            return new System.Web.Mvc.RazorView(controllerContext, partialPath, null, false, null);
        else
            return new WebFormView(controllerContext, partialPath);
    }

    protected override IView CreateView(ControllerContext controllerContext,
        string viewPath, string masterPath)
    {
        if (viewPath.EndsWith(".cshtml"))
            return new RazorView(controllerContext, viewPath, masterPath, false, null);
        else
            return new WebFormView(controllerContext, viewPath, masterPath);
    }
}

Note que MasterLocationFormats muda a prioridade de pesquisa do View Engine para primeiro olhar as áreas.
        MasterLocationFormats = new string[]
        {
            "~/Areas/{2}/Views/{1}/{0}.master",
            "~/Areas/{2}/Views/{1}/{0}.cshtml",
            "~/Areas/{2}/Views/Shared/{0}.master",
            "~/Areas/{2}/Views/Shared/{0}.cshtml",
            "~/Views/{1}/{0}.master",
            "~/Views/{1}/{0}.cshtml",
            "~/Views/Shared/{0}.master"
            "~/Views/Shared/{0}.cshtml"
        };

Agora você precisará registrar o View Engine no Global.asax.cs:
Global.asax.cs
protected void Application_Start()
{
    RegisterRoutes(RouteTable.Routes);
    ViewEngines.Engines.Clear();
    ViewEngines.Engines.Add(new AreaAwareViewEngine());
}

Apenas isso já é suficiente para funcionar. A resposta detalha mais algumas coisas, mas grosso modo, é isto.
Comment: Obrigado, embora eu não tenha conseguido entender quase nada de como isso funciona ele funcionou. Eu tinha visto este post no SO de fora mas como meu inglês é fraco eu não consegui entender, ainda mais que é difícil de acreditar que para fazer algo tão simples precisa de tantas linhas de código.
Comment: É verdade. A questão das áreas, a meu ver, não foi bem feita no ASP.NET MVC. Tanto que estão para abandonar o conceito na próxima versão do produto.
Comment: Acho que vou fazer isso também, abandonar elas e deixar os controles, models e views misturados dentro de suas pastas da raiz.


Grid covers another on resizing in WPF

Question: In a GroupBox I have two grids: the 1st one contains can contain lots of textboxes so that I added a ScrollViewer, the 2nd one contains action buttons that must allways be visible.
A 2nd GroupBox above has an Expander and the problem is that when it is expanded and the 1st grid has enough elements, it covers the 2nd grid with buttons. How can I fix this?
Here my code:
<Window x:Class="ControlOverlayBug.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="269" Width="454">
<DockPanel Background="LightGray" SnapsToDevicePixels="True">
    <GroupBox DockPanel.Dock="Top" Header="Simulation Parameters">
        <DockPanel>
            <Expander DockPanel.Dock="Bottom" x:Name="AlgoParams" Header="Change Us...">
                <Grid x:Name="parameterGrid">
                    <DataGrid
                            RowHeaderWidth="0"
                            ItemsSource="{Binding AlgoParameters}"
                            AutoGenerateColumns="False"
                            GridLinesVisibility="None"
                            CanUserAddRows="False"
                            CanUserDeleteRows="False"
                            CanUserReorderColumns="False">
                        <DataGrid.Columns>
                            <DataGridTextColumn Header="Name" Binding="{Binding Name}"  Width="1*" IsReadOnly="True"/>
                            <DataGridTextColumn Header="Description" Binding="{Binding Description}"  Width="1*"/>
                            <DataGridTextColumn Header="Value" Binding="{Binding Value}"  Width="1*"/>
                        </DataGrid.Columns>
                    </DataGrid>
                </Grid>
            </Expander>
        </DockPanel>
    </GroupBox>

    <GroupBox DockPanel.Dock="Bottom" Header="Other Parameters">
        <DockPanel x:Name="BindPanel" VerticalAlignment="Stretch">
            <ScrollViewer VerticalScrollBarVisibility="Auto" DockPanel.Dock="Top" >
                <Grid x:Name="paramGrid"  Margin="3" Background="Yellow">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="30"/>
                        <ColumnDefinition Width="200*"/>
                        <ColumnDefinition Width="5"/>
                        <ColumnDefinition Width="363*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition/>
                        <RowDefinition/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <GridSplitter Grid.Column="2" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" ResizeDirection="Columns" Width="5" Height="Auto" ShowsPreview="false"/>

                    <TextBlock Grid.Row="1" Text="1"/>
                    <TextBlock Grid.Row="1" Grid.Column="1" Text="p10"/>
                    <TextBlock Grid.Row="1" Grid.Column="4" Text="bla"/>

                    <TextBlock Grid.Row="2" Text="2"/>
                    <TextBlock Grid.Row="2" Grid.Column="1" Text="p11"/>
                    <TextBlock Grid.Row="2" Grid.Column="4" Text="blub"/>
                </Grid>
            </ScrollViewer>

            <Grid DockPanel.Dock="Bottom" VerticalAlignment="Bottom" Background="AliceBlue" MinHeight="30">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="123"/>
                    <ColumnDefinition Width="*"/>
                    <ColumnDefinition Width="Auto"/>
                </Grid.ColumnDefinitions>
                <Button Content="_Load Settings" HorizontalAlignment="Left"/>
                <Button Content="_Save Settings" Grid.Column="1" HorizontalAlignment="Left"/>
                <Button Content="_Run Simulation" Grid.Column="2" HorizontalAlignment="Right"/>
            </Grid>
        </DockPanel>
    </GroupBox>
</DockPanel>

Thanks in advance!
Answer: Give your ScrollViewer a MaxHeight to get the scroll working instead of overlapping
Comment: Unfortunately, it does not fix the problem. Expander lets still cover the grid.
Comment: The typical Expander use is at the window's bottom. I think you might need to review your design a bit. I see the window has a fixed height at the initial state and things inside have a dynamic height. This leads definitely to overlapping.
Answer: Well, I solved the problem by changing the DockPanel (named BindPanel) by a Grid with two rows (the 2nd row has a fixed height) and it works. Here the interesting part:
 <GroupBox DockPanel.Dock="Bottom" Header="Other Parameters">
        <Grid x:Name="BindPanel" VerticalAlignment="Stretch" Background="Beige">
            <Grid.RowDefinitions>
                <RowDefinition/>
                <RowDefinition Height="24"/>
            </Grid.RowDefinitions>
            <ScrollViewer VerticalScrollBarVisibility="Auto" VerticalAlignment="Top">
                ...
            </ScrollViewer>

        </Grid>
  </GroupBox>

Grid covers another on resizing in WPF


Como armazenar mais de um valor usando SharedPreferences?

Question: Estou fazendo um app onde criei um checkbox para representar um o item favorito.
O problema que estou tendo é que estou tendo é quando coloco mais de um item como favorito, o último substitui o primeiro, ou seja, está permitindo adicionar somente um registro.
Como posso salvar vários registros usando sharedPreferences?
Segue meu código:
MAIN ACTIVITY
// EVENTO DE CLIQUE
           lista.setOnItemClickListener(new AdapterView.OnItemClickListener() {
               @Override
               public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
                   // CHECK BOX
                   View checkBoxView = View.inflate(FraseAutorFrase.this, R.layout.checkbox, null);
                   CheckBox checkBox = (CheckBox) checkBoxView.findViewById(R.id.checkbox);
                   checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                       @Override
                       public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                           // Save to shared preferences
                           SharedPreferences sharedPreferences = getSharedPreferences("arquivoPreferencia", MODE_PRIVATE);
                           SharedPreferences.Editor editor = sharedPreferences.edit();
                           editor.putString("frase", frasesR[position]);
                           editor.commit();
                       }
                   });
                   checkBox.setText("Marcar como Favorito?");
                   // Recuperar dados
                   SharedPreferences sharedPreferences = getSharedPreferences(ARQUIVO_PREFERENCIA, MODE_PRIVATE);
                   if (sharedPreferences.contains("frase"))
                   {
                       Intent intent = new Intent(FraseAutorFrase.this, Favoritos.class);
                   }

ACTIVITY FAVORITOS
SharedPreferences sharedPreferences = getSharedPreferences("arquivoPreferencia", MODE_PRIVATE);
        String fraseR = sharedPreferences.getString("frase","Não Existem Favoritos!");
            // CRIANDO O ARRAY
            final String[] frasesFavoritoArray =
                    {
                            fraseR
                    };
            // UTILIZANDO O ADPTADOR PARA RECEBER O LISTVIEW
            ArrayAdapter<String> adaptador = new ArrayAdapter<String>
                    (
                            // Primeiro Parametro do Array Adpater é o Context
                            getApplicationContext(),
                            // Segundo Parametro do Array Adpater é o Layout
                            android.R.layout.simple_list_item_1,
                            android.R.id.text1,
                            // Terceiro Parametro do Array Adapter é indicar o nome do Array para exibição
                            frasesFavoritoArray
                    );
            lista.setAdapter(adaptador);

Answer: Os valores salvos em SharedPreferences funcionam como um par "Chave-Valor". Para guardar vários valores, tem que usar chaves distintas. No seu caso, você está usando a mesma chave "frases" para toda a lista. Você pode fazer algo assim no seu código:
editor.putString("frase" + position, frasesR[position]);

Ele vai salvar os dados nas chaves "frase1", "frase2", etc. Depois você tem que adaptar o código que lê essas chaves.
Particulamente não é uma boa prática usar SharedPreferences pra guardar muitos dados, especialmente se os dados da sua lista forem dinâmicos, pois os dados guardados podem não corresponder ao momento em que eles foram salvos.
Comment: Obrigado pela resposta, Márcio.
Qual seria a maneira mais fácil para ler essas informações da "frase" + position?
Comment: Como eu disse, e lendo melhor o seu código, armazenar o que você quer em SharedPreferences não é muito bom, aliás vai dar até bastante trabalho de implementar. O ideal seria realmente usar banco de dados.
Comment: Se ainda quiser insistir com SharedPreferences, dá uma olhada nessa resposta, acho que vai te atender: https://stackoverflow.com/questions/22089411/how-to-get-all-keys-of-sharedpreferences-programmatically-in-android
Comment: Obrigado, Márcio.
Estou usando o SharedPreference mais por limitação de conhecimento em banco de dados, sei que o ideal seria usar o Sqlite.
Mais uma vez, Obrigado!!!
Comment: Dá uma olhada nesse curso, é muito bom. Aprendi com ele: https://br.udacity.com/course/android-basics-data-storage--ud845/
Comment: Valeu, Márcio.
Muito Obrigado, vou fazer esse curso, estou precisando.
Abraço!


Aninhar um array plano em PHP para gerar um menu e submenus em HTML

Question: Tenho um array mais ou menos assim:
Array
(
    [38] => Array
        (
            [name] => Categoria Raiz 1
            [link] => https://...
            [id_parent] => 0
        )

    [205] => Array
        (
            [name] => Subcategoria 1
            [link] => https://...
            [id_parent] => 38
        )

    [206] => Array
        (
            [name] => Subcategoria 2
            [link] => https://...
            [id_parent] => 38
        )
    [484] => Array
        (
            [name] => Categoria Raiz 2
            [link] => https://...
            [id_parent] => 0
        )
    [485] => Array
        (
            [name] => Subcategoria 3
            [link] => https://...
            [id_parent] => 484
        )

    [39] => Array
        (
            [name] => categoria Raiz 3
            [link] => https://...
            [id_parent] => 0
        )

    [147] => Array
        (
            [name] => Subcategoria 4
            [link] => https://...
            [id_parent] => 39
        )
)

Os índices são os IDs das categorias.
Eu preciso aninhar as categorias raiz com as suas subcategorias para criar um menu dropdown, mas estou errando na lógica.
Estou utilizando a template engine Smarty, mas vou escrever o que eu já fiz em PHP puro para facilitar.
<?php
foreach($array as $key => $value) { ?>
    <li data-id_parent="<?php echo $value['id_parent']; ?>">
        <a href="<?php echo $value['link']; ?>"><?php echo $value['name']; ?>

    <?php
            if (!isset($id_anterior)) { ?>

    <?php   } else {
                if ($id_anterior != $value['id_parent']) { ?>

    <?php       }
            }
    ?>

    <?php

    $id_anterior = $key;
}
?>

Eu gostaria que a saída ficasse algo assim:

    Categoria Raiz 1

            Subcategoria 1

            Subcategoria 2

    Categoria Raiz 2

            Subcategoria 3

    Categoria Raiz 3

            Subcategoria 4

Onde estou errando?
Comment: como é a tabela?
Comment: @HananiaMizrahi A tabela é composta por colunas com os mesmos nomes das chaves do array, sendo a coluna `id` chave primária e a coluna `id_parent` chave estrangeira que referencia a própria tabela.
Answer: Sugiro primeiro organizar o array...
$menu = [
    38 => [
            'name' => 'Categoria Raiz 1',
            'link' => 'https://...',
            'id_parent' => 0
    ],
    205 => [
            'name' => 'Subcategoria 1',
            'link' => 'https://...',
            'id_parent' => 38
    ],
    206 => [
            'name' => 'Subcategoria 2',
            'link' => 'https://...',
            'id_parent' => 38
    ],
    484 => [
            'name' => 'Categoria Raiz 2',
            'link' => 'https://...',
            'id_parent' => 0
    ],
    485 => [
            'name' => 'Subcategoria 3',
            'link' => 'https://...',
            'id_parent' => 484
    ],
    39 => [
            'name' => 'Categoria Raiz 3',
            'link' => 'https://...',
            'id_parent' => 0
    ],
    147 => [
            'name' => 'Subcategoria 4',
            'link' => 'https://...',
            'id_parent' => 39
    ]
];

function &find($needle, &$haystack) {
    $return = false;

    if (isset($haystack[$needle])) {
        $return = &$haystack[$needle];
    } else {
        foreach ($haystack as &$item) {
            if (isset($item['child'])) {
                $return = &find($needle, $item['child']);
            }
        }
    }

    return $return;
}

function organize($menu) {
    $organized = [];

    foreach ($menu as $index => &$item) {
        $item['child'] = [];

        $ref = &find($item['id_parent'], $organized);

        if ($ref !== false) {
            $ref['child'][$index] = $item;
        } else {
            $organized[$index] = $item;
        }
    }

    return $organized;
}

$organized = organize($menu);

O resultado de var_dump($organized); será
array(3) {
  [38]=>
  array(4) {
    ["name"]=>
    string(16) "Categoria Raiz 1"
    ["link"]=>
    string(11) "https://..."
    ["id_parent"]=>
    int(0)
    ["child"]=>
    array(2) {
      [205]=>
      array(3) {
        ["name"]=>
        string(14) "Subcategoria 1"
        ["link"]=>
        string(11) "https://..."
        ["id_parent"]=>
        int(38)
      }
      [206]=>
      array(3) {
        ["name"]=>
        string(14) "Subcategoria 2"
        ["link"]=>
        string(11) "https://..."
        ["id_parent"]=>
        int(38)
      }
    }
  }
  [484]=>
  array(4) {
    ["name"]=>
    string(16) "Categoria Raiz 2"
    ["link"]=>
    string(11) "https://..."
    ["id_parent"]=>
    int(0)
    ["child"]=>
    array(1) {
      [485]=>
      array(3) {
        ["name"]=>
        string(14) "Subcategoria 3"
        ["link"]=>
        string(11) "https://..."
        ["id_parent"]=>
        int(484)
      }
    }
  }
  [39]=>
  array(4) {
    ["name"]=>
    string(16) "Categoria Raiz 3"
    ["link"]=>
    string(11) "https://..."
    ["id_parent"]=>
    int(0)
    ["child"]=>
    array(1) {
      [147]=>
      array(3) {
        ["name"]=>
        string(14) "Subcategoria 4"
        ["link"]=>
        string(11) "https://..."
        ["id_parent"]=>
        int(39)
      }
    }
  }
}

E então escreva a lista, por exemplo, com uma função recursiva:
function echoList($array) {
    echo '
';

    foreach($array as $item) {
        echo '
'.$item['name'].'';

        if (isset($item['child']) && !empty($item['child'])) {
            echoList($item['child']);
        }

        echo '
';
    }

    echo '
';
}

echoList($organized);

O HTML resultante:

        Categoria Raiz 1

Subcategoria 1

Subcategoria 2

        Categoria Raiz 2

Subcategoria 3

        Categoria Raiz 3

Subcategoria 4

As funções são recursivas e permitem quantas listas, sublistas e sublistas dentro de sublistas forem necessárias
Answer: Sua estrutura é recursiva, então por que não resolve usando recursividade? E você não precisa reestruturar seu array, basta filtrar os itens que deseja exibir a partir do valor de id_parent.
function menu($items, $parent = 0)
{
    $links = array_filter($items, function ($it) use ($parent) {
        return $it['id_parent'] === $parent;
    });

    if (count($links) === 0) {
        return '';
    }

    $menu = "
";

    foreach ($links as $id => $link) {
        $menu .= "
";
        $menu .= sprintf("%s", $link['link'], $link['name']);
        $menu .= menu($items, $id);
        $menu .= "
";
    }

    $menu .= "
";

    return $menu;
}

Assim ficando:
$items = [
    38 => [
            'name' => 'Categoria Raiz 1',
            'link' => 'https://...',
            'id_parent' => 0
    ],
    205 => [
            'name' => 'Subcategoria 1',
            'link' => 'https://...',
            'id_parent' => 38
    ],
    206 => [
            'name' => 'Subcategoria 2',
            'link' => 'https://...',
            'id_parent' => 38
    ],
    484 => [
            'name' => 'Categoria Raiz 2',
            'link' => 'https://...',
            'id_parent' => 0
    ],
    485 => [
            'name' => 'Subcategoria 3',
            'link' => 'https://...',
            'id_parent' => 484
    ],
    39 => [
            'name' => 'Categoria Raiz 3',
            'link' => 'https://...',
            'id_parent' => 0
    ],
    147 => [
            'name' => 'Subcategoria 4',
            'link' => 'https://...',
            'id_parent' => 39
    ]
];

echo menu($items);

Resultado (após formatado):

    Categoria Raiz 1

Subcategoria 1

Subcategoria 2

    Categoria Raiz 2

Subcategoria 3

    Categoria Raiz 3

Subcategoria 4


Prove that $d(a,b) \le \inf ~\{ ~d(a,s)~|~s \in S \} + \inf ~\{ ~d(b,s)~|~s \in S \} + \sup ~\{~d(b,s)~|~s \in S\}$. Error in proof?

Question: Suppose $(X,d)$ is a metric space and $a,b \in X, S \subseteq X, S \ne \{\phi\}$.
Then, prove that $d(a,b) \le \inf ~\{ ~d(a,s)~|~s \in S \} + \inf ~\{ ~d(b,s)~|~s \in S \} + \sup ~\{~d(s_1,s_2)~|~s_1,s_2 \in S\}$
My Textbook ( Metric Spaces by Michael Searcoid) gives the following proof :
By definition of metric spaces :
$d(a,b) \le  d(a,s_1)  +  d(s_1,s_2) + d(b,s_2)$ where $s_1,s_2 \in S$
$~~~~~~~~~~~\le d(a,s_1)  + d(b,s_2) + \sup ~\{~d(s_1,s_2)~|~s_1,s_2 \in S\}~\forall s_1,.s_2 \in S$
$~~~~~~~~~~~$ where $\sup ~\{~d(s_1,s_2)~|~s_1,s_2 \in S\} = k$ is a constant.
$~~~~~~~~~~~\le \inf \{ d(a,s_1)  + d(b,s_2)\} + k~~~;s_1,s_2 \in S$

$~~~~~~~~\le  \inf \{ d(a,s)~|~s \in S \}  + \inf \{d(b, s)~|~s \in S\} + k$
I think there is an error in the last step because $\inf$ has been distributed. In general $\inf f + \inf g \le \inf ( f + g) $ where $f,g$ are two random functions. Also, see this answer where distribution of the infimum has been cited as false: https://math.stackexchange.com/a/2852545/66069

Could anyone please clarify. Thanks a lot.
Answer: Separating the $s_1$ and $s_2$ dependent terms,
\begin{align*}
\require{color}
&\inf\{d(a,s_1)+d(b,s_2)\mid s_1,s_2\in S\}\\
&=\inf\{\inf\{d(a,s_1){\color{red}{+d(b,s_2)}}\mid s_1\in S\}\mid s_2\in S\}\\
&=\inf\{{\color{blue}\inf\{d(a,s_1)\mid s_1\in S\}}{\color{red}{+d(b,s_2)}}\mid s_2\in S\}\\
&={\color{blue}{\inf\{d(a,s_1)\mid s_1\in S\}+}}\inf\{d(b,s_2)\mid s_2\in S\}\\
&=\inf\{d(a,s)\mid s\in S\}+\inf\{d(b,s)\mid s\in S\}.
\end{align*}
The red and blue terms are independent of the immediate variable in inf, so can be pulled outside as shown.
But there is indeed a mistake in the proof you wrote:
$$
d(a,s_1)+d(b,s_2)+k
$$
is not $\leq\inf\{d(a,s_1)+d(b,s_2)\mid s_1,s_2\in S\}+k$.  One correct way is to give yourself some room first (another way is given by DanielWainfleet in the comments).  For $\varepsilon>0$, pick $s_1,s_2\in S$ so that
$$
d(a,s_1)+d(b,s_2)\leq\inf\{d(a,s_1)+d(b,s_2)\mid s_1,s_2\in S\}+\varepsilon
$$
and hence
\begin{align*}
d(a,b)&\leq d(a,s_1)+d(b,s_2)+d(s_1,s_2)\\
&\leq\inf\{d(a,s_1)+d(b,s_2)\mid s_1,s_2\in S\}+\varepsilon+k\\
&=\inf\{d(a,s)\mid s\in S\}+\inf\{d(b,s)\mid s\in S\}+k+\varepsilon
\end{align*}
Now $\varepsilon>0$ is arbitrary, so
$$
d(a,b)\leq\inf\{d(a,s)\mid s\in S\}+\inf\{d(b,s)\mid s\in S\}+k.
$$
Comment: More directly, let $A=\inf \{d(a,s_1): S_1\in S\}$ and $B=\inf \{d(b,s_2):s_2\in S\}. $ For any   $s_1,s_2\in S$ we  have $d(a,b)\le d(a,s_1)+d(b,s_2)+k.$ So for any $s_2\in S$ we have $d(a,b)\le$ $ \inf \{d(a,s_1)+d(b,s_2)+k: s_1\in S\}=$ $=\inf \{d(a,s_1):s_1\in S\}+d(b,s_2)+k=$ $A+d(b,s_2)+k$... et cetera..... To the proposer:  It is true that if $f,g$ are functions on a common domain $S$ then $\inf f+  \inf g \le \inf \{f(s)+g(s):s\in S\}. $  But here, with $f(s)=d(a,s)$ and $g(s) =d(b,s), $ we are looking at $\inf \{f(s_1)+g(s_2): (s_1,s_2)\in S^2\}.$
Comment: @MathMan. Yes. But I would say that it might only seem  like a distributive law was applied.
Comment: Could you  clarify how did the infimum distribute? It generally cannot be distributed:

$ \inf \{~~d(a,s)+d(b,s)~∣s∈S\} \ne \inf \{d(a,s)∣s∈S\}+\inf \{d(b,s)∣s∈S\}$
Comment: They are minimizing over *different* $s_1,s_2$, so it distributes.
Comment: aah okay. I still have a small confusion. Are $s_1,s_2$ really different variables? They are just different names for the same variables $s$ to be minimized over the same set $S$?
Comment: They are different variables.  We need a point $s_1\in S$ that is close to $a$ and (possibly different) $s_2\in S$ that is close to $b$.  For example, let $X=\mathbb{R}$, $S=(-1,1)$, $a=-1$ and $b=1$.  Then you want $s_1$ to be close to $-1$ and $s_2$ to be close to $+1$.
Comment: @DanielWainfleet you mean, infimum distributed because $s_1,s_2$ are different variables. correct?
Comment: @user10354138 thank you!
Answer: You are correct, that is an error, for the reasons you cited.
I think the first error has happened one step before, when they say
$$d(a,s_1)  + d(b,s_2) \le \inf \{ d(a,s_1)  + d(b,s_2)\}$$
which is of course wrong generally. It would work with supremum, but not infimum.
If you are interested in the proof, it could go like this, using your $k$, we start with the last correct line:
$$d(a,b) \le d(a,s_1)  + d(b,s_2) + k, \quad\forall s_1,s_2\in S.$$
Now choose a sequence $s_{1n}\in S, n\ge 1$ such that $\lim_{n\to\infty} d(a,s_{1n})=\inf\{d(a,s_1),s_1\in S\}$. That's more or less the definition of the infimum. That means we have
$$d(a,b) \le d(a,s_{1n})  + d(b,s_2) + k, \quad\forall s_2\in S, s_{1n} \text { as defined above},$$
which we can rewrite as
$$d(a,b) - d(b,s_2) -k \le d(a,s_{1n}), \quad\forall s_2\in S, s_{1n} \text { as defined above}.$$
Now if we fix $s_2$ the above inequality has a constant on the left side. If we take the limit $n\to \infty$ on both sides, we get
$$d(a,b) - d(b,s_2) - k \le \inf\{d(a,s_1),s_1\in S\}, \quad\forall s_2\in S,$$
which we rewrite again as
$$d(a,b) \le \inf\{d(a,s_1),s_1\in S\} + d(b,s_2) + k, \quad\forall s_2\in S.$$
If we do the same procedure with a sequences $s_{2n}\in S, n\ge 1$ such that $\lim_{n\to\infty} d(b,s_{2n})=\inf\{d(b,s_2),s_2\in S\}$, we finally get the desired outcome:
$$d(a,b) \le \inf\{d(a,s_1),s_1\in S\} + \inf\{d(b,s_2),s_2\in S\} + k.$$
Because we had the freedom to choose our $s_1$ and $s_2$ as we wanted, we could bring in the infimum in 2 cases.
Comment: Thank you for the answer!
Answer: Let $ A=\inf \{d(a,s):s\in S\} $ and $ B=\inf \{d(b,s):s\in S\} $ and $ k=\sup \{d(s,s'):s,s'\in S\}.$
By contradiction, suppose $ d(a,b)=A+k+B+r  \;$ with $r>0.$
Take $s_1\in S$ with $d(a,s_1)<A+r/2.$ Take $s_2\in S$ with $d(b,s_2)<B+r/2 .$ Then $$A+k+B+r=d(a,b)\le $$ $$\le d(a,s_1)+d(s_1,s_2)+d(s_2,b)\le$$ $$\le d(a,s_1)+k+d(s_2,b)<$$ $$<(A+r/2)+k+(B+r/2)=A+k+B+r$$ implying $A+k+B+r<A+k+B+r.$
Comment: Thank you  for the answer!


Permalink to raw file in Github private repo

Question: Okay so I've seen this as a similar question several other places on here but many of those are multiple years old and have not seen a satisfactory answer on any of them. Github Raw File - Can I get a permanent link? and Read Raw Contents of File in Private Repo on Github via access_token
First let me provide my use case as I am open to alternative solutions.
I need to be able to link/display markdown files (.md) that are part of a private github repo in confluence. This does technically work using the confluence plugin Markdown from url when giving it a raw url like raw/repo/readme.md?token=XXXXXXX. The issue is the token generated via looking at the raw link is only valid for 7 days so this will not really work for documentation as obviously after a week part of the doc will no longer be visible. As referenced in one of the links above and several other places online through a google search I see the claim that it should be possible to generate a personal access token and substitute the token ie raw/repo/readme.md?token=PERSONAL_ACCESS_TOKEN but I have not found this to be the case. Even when granting your PAT every permission you can in github this still results in a 404 when attempting to access the url in a browser or through the confluence plugin.
Additionally I've also seen an example with a username like raw/repo/readme.md?login=USERNAME&token=PERSONAL_ACCESS_TOKEN but alas this has the same result of receiving a 404.
So the question is does anyone know how to make this work successfully using a PAT or similar security alternative? Am I missing a url option that would make it happy?
Please note I am NOT looking for alternative confluence plugins to make this happen, I know there are several but due to organizational security concerns these are not really options in my case.
Thanks for any ideas
Answer: To download a file from a private repository
1. You need to generate a Personal Access Tokens.
According to this GitHub help page:

In the upper-right corner of any page, click your profile photo, then click Settings.
In the left sidebar, click Developer settings.
In the left sidebar, click Personal access tokens.
Select the scopes. To use your token to access repositories from the command line, select repo.
Click Generate new token.
Give your token a descriptive name.

Let's suppose your actual token is 1234567abcdefg
2. Embed Token into the link.

Open the file in GitHub web page and click "Raw"
Copy the link of this raw file, maybe something like this:
https:// raw.githubusercontent.com/GITHUB_ACCOUNT/REPOSITORY_NAME/BRANCH_NAME/FILE_NAME.EXTENTION_NAME?token=SOME_NUMBERS_LETTERS
Reform the link as
https:// email@example.com/GITHUB_ACCOUNT/REPOSITORY_NAME/BRANCH_NAME/FILE_NAME.EXTENTION_NAME

As you see, "?token=SOME_NUMBERS_LETTERS" are removed. Insert the token you generated from GitHub + @ right after "https://"

curl -s -O https://firstname.lastname@example.com/GITHUB_ACCOUNT/REPOSITORY_NAME/BRANCH_NAME/FILE_NAME.EXTENTION_NAME

Hope this helps!
Comment: This works for curl but doesn't work for the browser. Do you know how to make it work there? The plugin I'm using is not getting the files properly otherwise @CookiesKush420
Comment: @ CookiesKush420 This doesn't work on browser ? How to make it work in browser ?
Answer: As you've seen, all raw links to private GitHub repositories require a token, which expires after a while.  This is because if a URL is exposed, the impact of the exposure is limited.  The token in the URL you're using is specific to your user, and if it were permanent, then someone could take that token and access that file in the future even if they'd left the organization.  I believe, IIRC, that the token is also specific to the URL in question.
So there isn't a way to do this using a token in a URL.  However, you could use a personal access token in the Authorization header using Basic authentication if your plugin supports that.  I've tested and that does work, and of course it doesn't expose your token to every user.  However, it does require that the site you're working with proxy the request and support that.
You may want to use the PAT of a machine or bot account associated with your organization so that if you leave, the links continue to work.
Answer: Others such as bk2204 have suggested this too,
here is an example of how I access contents of my private GitHub repository in PowerShell
Invoke-RestMethod https://raw.githubusercontent.com/HotCakeX/RepositoryName/main/MyFile.txt -Headers @{"Authorization"="token github_pat_abcdefgh123456789"}

Just need to create a fine-grained Personal Access Token:
https://github.com/settings/tokens?type=beta


Locally continuously differentiable implies locally Lipschitz

Question: I am interesting in the following result:

Let $X$ be a normed space and $f : X \to \mathbb{R}$. If $f$ is continuously differentiable in a neighborhood $V$ of a point $x_0 \in X$, then $f$ is locally Lipschitz at $x_0$.

Using mean value theorem, for all $x,y$ in an open ball $B \subset V$, there exists $z \in [x,y]$ such that $f(x)-f(y)= \langle f'(z), x-y \rangle$ so $|f(x)-f(y)| \leq \max\limits_{z \in B} ||f'(z)||. ||x-y||$.
In finite dimension, we can suppose that the closure of $B$ is in $V$ so that $\max\limits_{z \in B} ||f'(z)|| < + \infty$ because $z \mapsto f'(z)$ is continuous and the closure of $B$ is compact.
But what happens in infinite dimension? Is the result still true?
Comment: «locally continuously differentialble» is exacty the same thing as «continuously differentiable»!
Comment: I think you need to assume $\max\limits_{z \in B} ||f'(z)|| < + \infty$ in infinite dimension to make the result true.
Comment: Would it be possible to choose $f$ so that $Df$ is one of the functions constructed in http://math.stackexchange.com/questions/170615/local-boundedness-of-continuous-functions-on-a-banach-space ?
Comment: https://math.stackexchange.com/questions/2609765/is-a-lipschitz-function-differentiable/2609787#2609787
Answer: Yes, it is still true. Given $x_0$, use the continuity of $f'$ to find a neighborhood $U$ of $x_0$ such that $\|f'(x)-f'(x_0)\|\le 1$ for all $x\in U$. It follows that $\|f'(x)\|\le \|f'(x_0)\|+1$ in $U$. Now the Mean Value Theorem implies that $f$ is Lipschitz on $U$.


What problem is it when I want to map these documents to these 3 different labels?

Question: I am completely new to machine learning, and that means I am new to the ML-related jargon too.
I have a problem at hand where there about a 1000 documents (on an average 500 words each) which need to be mapped to 3 different classes.
Each class is defined based on some real-life concept like Cancer, Drug, children. These concepts are backed by certain taxonomy/controlled vocabulary. For example, MeSH terms for Cancer/Neoplasm.
What problem is it when I want to map these documents to these 3 different labels? Only when a document is mapped to all the labels, then a document is considered a positive match. Should I use pattern matching for it or Machine learning?
Comment: what you mean by "Only when a document is mapped to all the labels, then a document is considered a positive match"?
Comment: It is to filter a document (as positive instance) only if it belongs to all the predefined 3 categories simultaneously.
Answer: To me your problems fits just fine as a multi-label classification.
I am not sure there exists an approach that would seek whether a text belongs to more than one category simultaneously. Nonetheless, I also see no problem for you to take a more heuristic method involving consolidated text classification algorithms.
For example, imagine you train a model to classify documents into three labels $A$, $B$ and $C$.
Now, you input a new, unseen document to to this model. Any of the mainstream libraries will output the likelihood of this document belonging to each of the labels (individually, of course). For example:
<code>+--------------+-----+-----+-----+
|     DOC      |  A  |  B  |  C  |
+--------------+-----+-----+-----+
| new_document | 80% | 69% | 51% |
+--------------+-----+-----+-----+
</code>
All you have to do now is establish a threshold for which you'll consider that the document belongs to all three labels simultaneously. In the example above, if the threshold is 50%, then you consider it a match.
Comment: Exactly, the challenge then will be deciding a sensible threshold for the individual labels.
Comment: Thank you for point me to the problem class. I looked more into it. do you think it is a multi-label problem instead of a multi-class problem?
Comment: @ftTomAndJerry indeed, you are right. Classes are mutually exclusive. I've fixed my answer.


Why can't Singularity GS correctly display the following markup?

Question:

  header

main

  footer

I defined three grids for three screensizes. The markup contains three elements which get displayed in a different column for each screensize.
mobile layout, the main div stays in first column, header and footer get displayed in 2nd column
tablet layout, all three elements get overlapped in 2nd column (because margin-right: -100%;), seems to be a bug.
desktop layout, the only layout which works, header/footer/main get displayed in fifth column
The grid definition:
// grid columns
$grids      : 2;
$grids      : add-grid(6 at 40em);
$grids      : add-grid(12 at 50em);

// grid gutters
$gutters    : .2;

The styles:
html, body {
  margin: 0;
  padding: 0;
  height: 100%;
}

.grid {
  @include background-grid;
  margin: 0 auto;
  max-width: 1080px;
  min-height: 100%;
}

.layout {
  // mobile layout
  @include grid-span(1,2);
  // tablet layout
  @include breakpoint(40em){
    @include grid-span(4,2);
  }
  // desktop layout
  @include breakpoint(50em){
    @include grid-span(8,5);
  }
}

header,
.grid div,
footer {
  @extend .layout;
}

Does somebody know why this happens?
Answer: Singularity needs to know the location of each column. The second value in grid-span is the location which you have set to 2 and 5 forcing columns to start in these locations. You can change that value to 1 if you want things to be placed in the first column.
It also sounds like you are used to floating columns across a page so the one before it effects where the following column is placed. By default Singularity uses a technique called isolation. You can switch to the more traditional float method by writing $output: float. Documentation for these output styles can be found here: https://github.com/Team-Sass/Singularity/wiki/Output-Styles#float
Comment: Thanks for your feedback Scott. I was aware or thought I know/knew how the grid-span works but I was not anymore aware of the default output style of singularitygs.

Still haven't really figured out why it does not work with my setup but I'll let the people know when solved. just read the article by snugug/john albins post http://snugug.com/musings/on-responsive-designs-dirty-little-secret and get to know what it is all about isolation/float output styles.

thx anyway so far!


how to have a query include an id with its name from another table

Question: hi i have two tables "contract" and "users"
contract is like this:
contract_id , buyer_id , seller_id , third_person_id

and user table is like this:
user_id , first_name , last_name

i want a query to give me this information:
contract_id , buyer_id , buyer_first_name , buyer_last_name , seller_id , seller_first_name , seller_last_name , third_person_id , third_first_name , third_last_name

how to get above query?
i want to get names form ids.
Comment: you need 2 joins with user table. One for buyer and one for seller
Comment: would you please write it for me?
Answer: You need to use three join
 select
          c.contract_id ,
          u.buyer_id ,
          u1.first_name as buyer_first_name ,
          u1.last_name as buyer_last_name ,
          c.seller_id ,
          u2.first_name as seller_first_name ,
          u2.last_name as seller_last_name ,
          c.third_person_id ,
          u3.first_name as third_first_name ,
          u3.last_name as third_last_name
    from contract c
    left join users u1 on u1.user_id=c.buyer_id
    left join users u2 on u2.user_id=c.seller_id
    left join users u3 on u3.user_id=c.third_person_id


Carnatic Vs Western 12 Note system

Question: I was trying to learn the chromatic scale and associate it with carnatic equivalents (I know equal temperment is not the way with indian music, but it interest me to relate and learn it to certain scales) I stumbled upon this link and found this image.

I don't understand their abbreviations or interval names and really can't make the comparison with two system. Can anyone please detail the system explained here and make a comparison if possible for better understanding of the usage of abbreviations and interval names.
Edit : 1
Just found a better article which clears some questions on the topic here
With this useful image.
Comment: I don't have enough info to expand this into a answer, but take a look at [this image](http://www.keylessonline.com/images/keyboard_carnatic.jpg)
Comment: @Shevliaskovic The image do help in reading the two systems side by side. As you said it's not enough to expand into an answer.
Comment: Related: https://music.stackexchange.com/q/82734/38256
Answer: Ultimately, I can only give a partial answer, but if I'm understanding the question, I think it will still be helpful.
Often, western music is discussed using solfège: the scale degrees 1–7 are called do, re, mi, fa, sol, la, and ti or si. In many places these are the names of the notes; what, in America, are referred to as notes C–B are referred to in Italy and France as Do–Si. However, for purposes of comparison with the Carnatic system, it's more helpful to think of so-called movable-do systems, where "do" always refers to the tonic of the key.
For Carnatic music, a very similar system called Sargam is used. The degrees of a raag are sung as sa, ri, ga, ma, pa, dha and ni. So that's the origin of those terms in the chart above, they then just use the first letters for their abbreviations and add numbers for any scale degrees that have multiple versions. There are vast numbers of raags, and they all have different ways of presenting these scale degrees. The tuning of, for example, ma, in one raag might be quite different from ma in another. This is vaguely similar to the fact that both western major and minor scales have a "mi" note, but that pitch will be a full half step lower in the minor scales than in the major. However, the similarities end there. For one thing, every raag have "gamaka" associated with each scale degree that will be quite different from one to the next. Gamaka is sometimes translated as "ornament", but that has an implication of being inessential, the gamaka are part of the essence of each raag. Another huge difference between western scales and raags is that the some scale degrees might have different versions, some might be omitted, and some might be different tunings on the way up than on the way down. One can find some parallels in common-practice western music (such as the so-called melodic minor scale), but the overall soundworld and theoretical world are very different.
So, I'm a little skeptical about the whole idea of a 12-note Carnatic system. It sounds a lot like someone trying to impose a Western concept of pitch organization onto a music that it doesn't fit very well. That being said, I'm not an ethnomusicologist, and I'm not familiar with the study that produced this chart, so there might be more to it than I can see. I know enough to be very leery of this kind of analysis—especially given the enormous variety of raags in Carnatic music—but not enough to reject it outright or evaluate the central claims.
It isn't clear from your question, but in case you're asking about some of the other abbreviations: JI just stands for Just Intonation. 12-TET is short for 12-tone equal temperament. Cents are a way of measuring pitch such that there are exactly 100¢ in an equally-tempered half step.
Comment: Your answer do help in understanding this comparison at a basic level. However my question is also interested to know more on the treatment of reading notes(Interval names or their abbreviations). For example when you say G1-G2-G3 [M2-m3-M3] it's more like saying Ebb-Eb-E (bb to be read as flat-flat which is actually equivalent to D). This is under the comparison that {C to B} is equal to {Sa to Ni } is equal to {Do to Ti}. What is the significance of calling D as Ebb for instance? OR When you call R1 as shudha-Ri it's like calling C# as pure-D.
Comment: @RBz your assumption (or understanding) of enharmonic tones (Ebb and D) is based on what is called the equal tempered tuning system where an octave is divided into 12 equal steps, each a 12th root of 2.  This is an irrational number and impossible to tune to the natural harmonics of the vibrating instrument (rational fractions).  The latter tuning is called Just.  In just tuning Ebb is not equal to D.
Comment: @RBz, the table you have shown for chromatic must be the nearest rational fraction that produces the true chromatic tone.  In Just tuning you have more than one way to define the notes in between the diatonic notes and these result in more than 12 notes between the octave.  I cannot count how many musicians have tried to map Easter to Western paradigms.  They do not meld together perfectly.  imo one should not try.  Using western concepts does not lead to a better understanding of Indian music.  imo it is a form of ethnocentrism.
Comment: @ggcg the idea of enharmonic equivalence, however, predates equal temperament by centuries, and indeed it was one of the factors that led to the development of equal temperament.  E double flat and D are enharmonically equivalent on every 12-tone keyboard, regardless of what temperament is in use.

Carnatic Vs Western 12 Note system


Determining the 3rd vertex of an Equilateral and Right angled isoceles triangle.

Question: I am really having problems solving the following problems:

If $(x_1,y_1)$ and $(x_2,y_2)$ are the coordinates of the two vertices on the hypotenuse of a right angled isosceles triangle then the coordinates of the 3rd vertex are?
Similarly-If $(x_1,y_1)$ and $(x_2,y_2)$ are the coordinates of the two vertices of an Equilateral Triangle then the coordinates of the 3rd vertex are?

The answer to 1 and 2 respectively are-
$$\left(\frac{x_1+x_2 \pm(y_1-y_2)}{2},\frac{y_1+y_2 \pm(x_1-x_2)}{2}\right)$$
And
$$\left(\frac{x_1+x_2 \pm\sqrt 3(y_1-y_2)}{2},\frac{y_1+y_2 \pm\sqrt 3(x_1-x_2)}{2}\right)$$
How do I solve this problem?
I tried attempting it by using the fact that the triangle is isosceles and right angled in the first case. So I applied pythagoras theorem but failed to get this answer it was a complicated equation. Secondly I tried multiplying the slopes of the legs of the triangle to get -1 but even this attempt failed.
It was similar with the equilateral triangle problem.
I guess if I understand how to do even one easily the second should bit be difficult.
Please help.
Comment: Do the consecutive + and - stand for plus-minus? And are you familiar with complex numbers?
Comment: Yes they do.. Plus or minus.. Yes i am familiar
Comment: I suggested an edit. Did I screw up anything?
Comment: Just the brackets now it fine.. The whole thing is divided by 2
Comment: CAN this question be done Without Rotation or complex nos using simple pythogoras theorem or distance formula maybe?
Answer: Consider the fact that if P(x,y) is the unknown point, then when you apply rotation around that point, the point P1(x1, y1) goes to (gets mapped to) P2(x2,y2). From this you can construct equations and solve them to get the x and y. Just lookup the formulas for rotation in the 2D plane. The rotation angles are nice in both cases: 90 and 60 degrees. If you do this, you should get the answers you have posted here.
Say you rotate the point (x1,y1) around the point (a,b) on an angle of $\theta$.
Then the point (x1,y1) gets mapped to (x2, y2) where:
$x_2 = (x_1-a) * cos(\theta) - (y_1-b) * sin(\theta) + a$
$y_2 = (x_1-a) * sin(\theta) + (y_1-b) * cos(\theta) + b$
In your case you don't know the $a$ and $b$, you want to find them.
The $\theta$ is $\pm \pi/2$ and $\pm \pi/3$ respectively.
The $x_1, y_1, x_2, y_2$ - these you know.
Here is how one can solve the case: $\pi/3$. You have 3 more cases to solve.

See also:
Rotation
Rotation matrix
Comment: It will work too for the right angled triangle, just try it yourself. What about the plus/minus: well, they correspond to your unknown point being "above" or "below" the segment formed by the 2 known points. That's why I said you need to solve 3 more cases for theta: (1) -pi/3, (2) pi/2, (3) -pi/2.
Comment: The answers you have given isnt correct.. Please read my question and the answer again
Comment: No, thanks. You read, think, and calculate some more. Using my formulas I got your answers using paper and pencil.
Comment: Post the pic of your working then please.
Comment: Posted, you should say thanks a lot.
Comment: Nice.. But what about the plus or minus sign ? And i dont think it will work when the triangle is right angled. Cos theta will be 0...
Comment: Peter how did u get this formula -Say you rotate the point (x1,y1) around the point (a,b) on an angle of θ.
Then the point (x1,y1) gets mapped to (x2, y2) where:
x2=(x1−a)∗cos(θ)−(y1−b)∗sin(θ)+a
Comment: Yesterday I took it from the Internet. Also, years ago I studied it in the University.
Comment: For a complex number i understand that one can work it out like that but with vertices? Please give me the link or explanation or best a derivation of this also of this please... If this formula is correct i have understood the whole thing...
Comment: I gave you two links. The formula is correct, otherwise we would have got wrong answers for your 2 examples (with the 60/90 degrees). Here is 1 more link (look at kirchwey's answer): https://answers.yahoo.com/question/index?qid=20100314163944AAIu9xk
Comment: If you take an analytic geometry course, they will prove it for you. It's no big deal, I guess you can find it in almost any textbook on analytic geometry.
Comment: Thank you so much!


TypeError: not all arguments converted during string formatting error python

Question: I have customized tempest code for our REST API's, but when i run the scripts, using nosetests at the beginning it gives some weird type error as mentioned below, though test cases in the script passes
Traceback (most recent call last):
  File "/usr/lib64/python2.6/logging/__init__.py",line 776, in emit msg = self.format(record)
  File "/usr/lib64/python2.6/logging/__init__.py", line 654, in format return fmt.format(record)
  File "/home/rmcbuild/repository/rmc-test/tempest/openstack/common/log.py", line 516, in format return logging.Formatter.format(self, record)
  File "/usr/lib64/python2.6/logging/__init__.py", line 436, in format record.message = record.getMessage()
  File "/usr/lib64/python2.6/logging/__init__.py", line 306, in getMessage msg = msg % self.args
 TypeError: not all arguments converted during string formatting

has anyone come across this type of error, would appreciate if someone helps me out of it.
Thanks,
Comment: Was there any possible solution u found? I am encountering the same problem as well (I know this post is quite old. But just incase if ur solution could help me)
Answer: This happens when using %s to print a string:
>>> x = 'aj8uppal'
>>> print 'Hello, %s %s' %(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not enough arguments for format string
>>> print 'Hello, ' %(x)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: not all arguments converted during string formatting
>>>

If you put one too many %ss, it gives a TypeError: not enough arguments for format string, but if you put one to few, it gives TypeError: not all arguments converted during string formatting.
What is likely is that you have put a variable(s) in parentheses at the end, but the number of percent signs does not match. Please post your code if you want us to help you further :)
Comment: My code doesn't have any `%s`s and I'm still getting this message from logging
Answer: I received this error when I typed a '&s' by mistake rather than a '%s'
Comment: This is not an answer, comment it on the question if you think it can help him.


indicator function, stopping time and measurability

Question: Let $s < t$. Let $\tau$ be a stopping time. Let M, N square integrable martingale.
In a proof that i'm following i read that:
$$E\big[E[N_{\tau}(M_{\tau} - M_t)\mathbb1_{\tau\le t}|\mathcal F_{s\lor\tau}]|\mathcal F_s\big]=      E[N_{\tau}(M_{\tau} - M_{\tau\lor s})\mathbb1_{\tau\le t}|\mathcal F_s]$$
what i don't understand is why $\mathbb1_{\tau\le t}$ can go outside the expectation without have any change, it seems that the explanation is that it is $F_{s\lor\tau}$ measurable, but instead i think that it is $F_{t}$ measurable and that $ F_{s\lor\tau} \subset F_{t}$. Any help?
Comment: Isn't this just a consequence of the tower property of conditional expectation, because $\mathcal F_s\subset\mathcal F_{s\vee\tau}$?
Comment: ah you mean bringing outside $N(M_t-M_\tau$ modifying the time according to the conditional expectation and then bring it inside again for expoiting the tower property?
Comment: I simply mean that for any integrable $Z$, $E\left[ E[Z\mid\mathcal F_{s\vee \tau}]\mid \mathcal F_s\right] = E\left[ Z\mid \mathcal F_s\right] $.
Comment: yes, of course, but did you notice that there was a change on the equality? from $M_t$ to $M_{t \lor s}$. What it mean is that it has not being simply applied the tower property
Comment: I missed that.  And now the indicator $\Bbb 1_{\tau\le t}$ bothers me, because it isn't measurable with respect to $\mathcal F_{s\vee\tau}$.
Comment: @JohnDawkins so the proof of NCh is it wrong? is it measurable w.r.t. $\mathcal F_t$?
Comment: @JohnDawkins https://math.stackexchange.com/questions/3490881/step-in-the-proof-of-martingale-condition if you look at this my previous question I added specifically the steps of the proof where the same problem present here happen. (are the two line after SHOW )
Comment: @JohnDawkins What step of proof seems wrong to you? It is just the definition.
Comment: @Buddy_ It is true that $\{\tau\leq t\} \in \mathcal F_t$, by definition. And this fact is useless for the equality since it cannote help bring indicator outside the  inner expectation. And it is wrong that $\mathcal F_{s\lor\tau} \subset \mathcal F_{t}$ for $s<t$. Take $A=\{\tau=t+1\}\in \mathcal F_{s\lor\tau}$, and this event dos not belong in general to $\mathcal F_{t}$.
Comment: @NCh thank you for this last comment, it was really helpful
Answer: Indeed, $\{\tau\leq t\}\in F_{s\lor\tau}$.
By definition, $\sigma$-algebra $\mathcal F_\tau$ is
$$
\mathcal F_\tau:=\left\{A\in\mathcal F:A\cap\left\{\tau\le u\right\}\in\mathcal F_u\;\text{for all }u\right\}
$$
Then
$$
F_{s\lor\tau} = \{A\in\mathcal F: A\cap \{\max(s,\tau) \leq u\} \in \mathcal F_u \text{ for all } u\} = \{A\in\mathcal F: A\cap \{s\leq u\}\cap \{\tau \leq u\} \in \mathcal F_u \text{ for all } u\}
$$
Look at $A=\{\tau\leq t\}$ and check whether it belongs to $F_{s\lor\tau}$.
$$
\{\tau\leq t\}\cap\{s\leq u\}\cap \{\tau \leq u\} = \{\tau\leq t\land u\}\cap\{s\leq u\} \in \mathcal F_u.
$$
So, $\{\tau\leq t\}\in F_{s\lor\tau}$.


Multiple regression for a questionnaire study

Question: Let's say I have a study in which I send a 100 people a questionnaire in which the dependent variable is binary, such as "does x, y and z correlate with whether a person is obese or not obese".
Would a logistic regression be a good way to answer this question? Furthermore, would a multiple logistic  regression be a good model to say "does x affect whether a person is obese or not obese, controlling for y?"
Comment: Your questionnaire seems to be about attitudes and perceptions. That is a long way from whatever causes obesity.
Answer: You can fit a multiple logistic regression. But your larger goal is to make a claim about causality, which is rarely easy to do with observational data. In surveys/questionnaires, for example, you need to worry about nonresponse bias, reverse causation, and human biases associated with people's perceptions of themselves (I'm sure there are others too, this is not an exhaustive list). Logistic regression is a tool that will not fix any of these problems for you - it will merely identify patterns within the data that you have.
You may be interested in some of the threads in our causality tag, especially  Under what conditions does correlation imply causation?
Answer: You have not stated, whether the "independent" data from the questionaire are binary as well or metric or pseudo-metric.
Assuming metric predictors (independent variables) and binary outcome (dependent variable) then logistic regression is a natural first choice. That is, if you believe in an additive and more or less monotonic relations. More complex, non-linear relationships might be better described by other regression models like regression trees or random forests or neural networks but a logistic regression is a reasonable first attempt.
For the bivariate case you might also consider simpler/more intuitive attempts such as an Receiver Operator Curve ROC with AUC analysis or even a t-test comparing obese and non-obese participants, if your audience is better acquainted with that then with logistic regression.
If there is data available concerning the weight of the participant, their body mass index or their hip-to-waist ratio it is very often advisable to examine these continuous measures instead of dichotomous values like obesity. Definitions of when exactly one is obese are to some point arbitrary.
Answer: You might best be served by using Item Response Theory, which is like factor analysis with categorical DVs. In this case, there is a latent factor, obesity, that causes responses in the questionnaire. Then you can use the observed obesity outcome as a convergent validity factor.


FreeBSD ports: Set make defines not exposed as Options

Question: In FreeBSD, when you do make config, lots of ports have options that can be set. These options are saved so that when you update the port, they are used again.
Some ports have additional items that are checked for in the Makefile, but not exposed as a configure option. For example, the maildrop port has the MAILDROP_TRUSTED_USERS checked with the following if statement in the Makefile:
<code>.if defined(MAILDROP_TRUSTED_USERS)
   CONFIGURE_ARGS+=        --enable-trusted-users="${MAILDROP_TRUSTED_USERS}"
.endif
</code>
I'm having a brain fart, where can I set MAILDROP_TRUSTED_USERS so that it will be used if the  port get updated later by postmaster? For this install I defined it manually, but if I use postmaster to update a port that forces this port to update, I'd like the value be set for the build.
Answer: I think you're looking for <code>/etc/make.conf</code>.
Comment: Thank you, I search for something like that for 1/2 hour. I was only able to the options page.


Dorian mode cadences

Question: From this question I read that modal cadences are different from tonic cadences.
I'm trying to learn Dorian mode and I noted that in the answer they offer the suggestion of the second chord, first inversion followed by the tonic chord.

In Dorian, you would use ii6(5)-i. (Ex. Em(7)/G-Dm)

My question is. Is this the only modal candence for Dorian?
IE. May I use also the ii without inversions? And is there other type of cadences in Dorian (IE in tonic I know 4 cadences - Perfect, Plagal, Imperfect and Interrupted), is there any similar in modal cadences?
Comment: I'm afraid my answer has been posted before you said *I was aiming at Celtic*. But I can't tell what would be different. What we shouldn't forget is music theory is more opinion based then we would believe. There have been different modes in different times. This means the modes have changed in melodic and harmonic respects. e.g. the sharpened 7th degree wasn't use in the earliest eras.
Comment: What kind of "modal" music? folk, jazz, or medieval?
Comment: I was aiming at Celtic.
Comment: You also have a plagal cadence, from IV to I (G to Dm).
Answer: Actually I miss a discussion about the statements in the linked question. ii6 - i ... how you are quoting would be a plagal cadence. The authentic cadence is: v-i (am-dm ... and as there was also in times of medieval music already a leading tone in many cases the perfect cadence was i-iv-V-i. (dm-gm-A-dm or ii6 instead of iv.)
Excerpt of
In Praise of Harmony: The Teachings of Abbé Georg Joseph Vogler
Comment: This answer goes totally against what I found in the [other question](https://music.stackexchange.com/questions/7111/do-different-modes-have-the-same-cadence-structure/86129#86129), that specifies: `Modes use modal approaches by character emphasis. In fact, if you want to give a more modal approach, no V-I, IV-I, V-i, iv-i, or v-i is appropriate here.` But the cited text gives a specific source.
Comment: All I can say to this is: music theory is more opinion based than most other sciences. It makes only sense to discuss an approach if you cite any theory and name the source of it like I did here. (Have Michael Curtis ' comment on the question "* Es wird wirklich mühsam, alle Orte zu verfolgen, an denen @MaikaSakuranomiya immer wieder diese fehlerhafte Liste von "Modalkadenzen" veröffentlicht. Das ist die Erfindung einer Person und für modale Harmonie nicht im entferntesten üblich*".

Dorian mode cadences


Why do two identical feature vectors (distance score 0) get different labels in DBSCAN?

Question: I have two identical feature vectors. They have a distance score of 0.
I perform DBSCAN Clustering (using sci-kit) and they get different labels.
Is this expected behaviour?
Answer: In theory this could happen for border points, if and only if border point assignments are resolved with a random assignment. Which actually is more costly to do fair instead of a first-assignment-wins or last-assignment-wins strategy (and since the original DBSCAN did not do such a randomized assignment but first-assignment-wins, it is more appropriate to do it this way, too).
It could also be due to numerical precision. The two vectors have a distance score of 0, but for the nearest core point, one of them has distance > epsilon, and the other one < epsilon, due to numerical precision. But I couldn't even design a data set for this to happen on purpose, I doubt this happens on chance easily.
So this should be either a bug or an incorrect usage on your side.
Have you compared the results to the reference implementation of DBSCAN in ELKI? That seems to be somewhat the "official" version by now, and also appears to be carefully validated.
Comment: It turns out, I was calling fit() with the original features vector and not the distance matrix. Thats the source of my error, but your response answers my question. Thanks!


Prove $\limsup A_n \smallsetminus \liminf A_n = \limsup (A_n \cap A_{n+1})$

Question: We have a sequence of sets indexed on the naturals and we want to show the following is true.  There is no assumption of increasing or decreasing containment so I'm not sure what you're supposed to do with the consecutive-ness.
$\limsup A_n \smallsetminus \liminf A_n = \limsup (A_n \cap A_{n+1})$
Note that minus is set theoretic difference.
An obvious issues is that the LHS will not separate nicely since Limsup doesn't yield strict equality when broken over intersection...I tried pushing around DeMorgan's Law a bit but I'm stumped.
Comment: It's not true. $A_{2n} = [0,1]; A_{2n+1} = [2,3]$.
Comment: @ThomasAndrews $\limsup A_n =\bigcap_{n=1}^\infty\bigcup_{m=n}^\infty A_n$.
Answer: The stated equality does in general not hold, as illustrated by the example
$$A_n = \begin{cases}[0,1] &, n \equiv 0 \pmod{2}\\ [2,3] &, n \equiv 1 \pmod{2}.\end{cases}$$
We have $\limsup A_n = [0,1] \cup [2,3]$ and $\liminf A_n = \varnothing = \limsup (A_n \cap A_{n+1})$ then.
However, we always have $\DeclareMathOperator{\sdiff}{\triangle}$
$$\limsup A_n \setminus \liminf A_n = \limsup (A_n \sdiff A_{n+1})$$
where $A \sdiff B$ is the symmetric difference $(A\setminus B) \cup (B\setminus A)$.
Answer: You know that $x\in\limsup_{n\in\Bbb N}A_n$ iff $\{n\in\Bbb N:x\in A_n\}$ is infinite, and $x\in\liminf_{n\in\Bbb N}A_n$ iff $\{n\in\Bbb N:x\notin A_n\}$ is finite. Thus,
$$x\in\limsup_{n\in\Bbb N}A_n\setminus\liminf_{n\in\Bbb N}A_n$$
iff $\{n\in\Bbb N:x\in A_n\}$ and $\{n\in\Bbb N:x\notin A_n\}$ are both infinite.
On the other hand, $x\in\limsup_{n\in\Bbb N}(A_n\cap A_{n+1})$ iff $\{n\in\Bbb N:x\in A_n\cap A_{n+1}\}$ is infinite. Suppose that we can arrange matters so that there is an $x$ such that $x\in A_n$ iff $n$ is even; then for all $n\in\Bbb N$ we'll have $x\notin A_n\cap A_{n+1}$ and therefore $x\notin\limsup_{n\in\Bbb N}(A_n\cap A_{n+1})$, but we clearly will have $x\in\limsup_{n\in\Bbb N}A_n\setminus\liminf_{n\in\Bbb N}A_n$. And this is easy to arrange: for example, just let
$$A_n=\begin{cases}
\{0\},&\text{if }n\text{ is even}\\
\varnothing,&\text{if }n\text{ is odd}\;.
\end{cases}$$
To find a correct equality, suppose that $x\in\limsup_{n\in\Bbb N}A_n\setminus\liminf_{n\in\Bbb N}A_n$, so that $\{n\in\Bbb N:x\in A_n\}$ and $\{n\in\Bbb N:x\notin A_n\}$ are both infinite, and let $$M=\{n\in\Bbb N:x\in A_n\setminus A_{n+1}\}\;;$$ then $M$ must be infinite (why?), and we must have $x\in\limsup_{n\in\Bbb N}(A_n\setminus A_{n+1})$. Thus,
$$\limsup_{n\in\Bbb N}A_n\setminus\liminf_{n\in\Bbb N}A_n\subseteq\limsup_{n\in\Bbb N}(A_n\setminus A_{n+1})\;.$$
The reverse inclusion is even easier to check, so
$$\limsup_{n\in\Bbb N}A_n\setminus\liminf_{n\in\Bbb N}A_n=\limsup_{n\in\Bbb N}(A_n\setminus A_{n+1})\;.$$


Conversion loses qualifiers, but doesn't really

Question: This is somewhat related, but also bit different to: C++ "conversion loses qualifiers" compile error
In my code I'm getting following error:

error C2440: 'initializing': cannot convert from 'const git_commit
  *const *' to 'const git_commit **'

As much as I understand that assigning from T** to const T** would allow to violate rules of constness, here in the example I gave, that is, assigning from const T*const * to const T** actually gains constness, without loosing any, so where/why this is a problem?
Answer: const git_commit * const *

a pointer to a constant array of pointers to constant git_commits
const git_commit * *

a pointer to a mutable array of pointers to constant git_commits
assigning a const array to a mutable array loses const.
Comment: Hi, thanks for the answer. I think I do understand, one thing though, your interpretation is slightly incorrect in the way that you are using word 'array', where in fact there isn't guarantee that there is any array. First one should be read as: pointer to const pointer to const object. Thanks for your answer though.
Comment: Not quite... A pointer to a pointer is not a pointer to an array of pointers (that would be `***`, and being a [three-star programmer](http://c2.com/cgi/wiki?ThreeStarProgrammer) is discouraged). If anything it might be a pointer to an array of `git_commit` objects. Or a "2d" array of `git_commit` objects.
Answer: int const x = 7;
std::cout << x << '\n'; // compiler can optimize to 7
int const* const px = &x;
std::cout << *px << '\n'; // compiler can optimize to 7

int const*const* ppx = &px;
std::cout << **ppx << '\n'; // compiler can optimize to 7

int const** ppx_cheat = ppx; // illegal, but presume we are allowed to do it
int const y = 1;
int const* py = &y;
*ppx_cheat = py;
std::cout << **ppx << '\n'; // compiler can optimize to 7, *but is wrong*

Comment: That's not what's happening here. OP has a bog standard illegal `const T*` to `T*` conversion. (I made the same mistake at first)
Comment: @light you sure?  The error generated above matches the OP's no?
Comment: No it matches what I said
Comment: @light `error: invalid conversion from 'const int* const*' to 'const int**' [-fpermissive]` In what way does this not match the OP's error message?  I mean other than `int` being a different type.  Because that is the error my code above generates.  And which I explain.  Please be specific, not "no, I am right", because I have considered what I can gather of your position assuming you are right, and I cannot reconcile it.  I think I know what error you think I made, but I cannot tell as you are not being specific enough.


Reusing storybook components in another project

Question: Hi Everyone I have tried to create a component using Storybook and reuse it on another project The method I followed is using an npm package. Although i have successfully published my package when I import it to a new project I am running into errors like
React is not defined.
`ReferenceError: React is not defined
at pa (http://localhost:3000/static/js/bundle.js:11178:3)
npm i publishstory`
https://www.npmjs.com/package/publishstory
This is my npm package any help  how I can reuse my storybook components I have tried many possible solutions
This is How I have called my component in the new project App.js
**
`import React from 'react';
import {Button} from 'publishstory';
function App() {
  return (

Hello

    <Button></Button>

  );
}
export default App;`

**
Answer: Normally when publishing a library, you're not doing a full minified build of your code. You just transpile it with babel for instance, so it's still readable code.
Your library then needs to define its peerDependencies like react, react-dom. You don't ship these dependencies with your library, because the app consuming your library should care for those.
But from what I see you got that last part right already.
You're saying that you get errors that react is not defined in your new app? Well, did you add react & react-dom as dependencies in that said app? Because you really need to have it there and the version should be compatible with what you defined in your library.
If you've done that, I don't see why it wouldn't work. Maybe provide more information on this app?


Google API users.get error 401 Unauthorized

Question: So, im tryng to use users.get from google api and it work fine if i call it directly Oauth 2.0 Client Application but with it after get the token and make the request its necessary to allow on brownse to use it propertly and i can't let this way.
So, i changed to use service accounts. I get the authentication token, i make the request but everytime i get erorr 401  Unauthorized :
System.AggregateException
  HResult=0x80131500
  Message=Um ou mais erros.
  Source=mscorlib
  StackTrace:
   at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
   at googleteste.Program.Main(String[] args) in \source\repos\googleteste\googleteste\Program.cs:line 36

Inner Exception 1:
HttpRequestException: O código de status de resposta não indica êxito: 401 (Unauthorized).

I already did domain delegation on scopes .
I create the keys, JSON and P12.
Thanks.
public static async Task<string> GetAccessTokenFromJSONKeyAsync(string jsonKeyFilePath, params string[] scopes)
    {
      using (var stream = new FileStream(jsonKeyFilePath, FileMode.Open, FileAccess.Read))
      {
        return await GoogleCredential
            .FromStream(stream) // Loads key file
            .CreateScoped(scopes) // Gathers scopes requested
            .UnderlyingCredential // Gets the credentials
            .GetAccessTokenForRequestAsync(); // Gets the Access Token
      }
    }

public static string GetAccessTokenFromJSONKey(string jsonKeyFilePath, params string[] scopes)
    {
      return GetAccessTokenFromJSONKeyAsync(jsonKeyFilePath, scopes).Result;
    }

var token = GoogleServiceAccount.GetAccessTokenFromJSONKeyAsync(
            "Keys/wneniac-2744e4a55337.json",
            new[] { "https://www.googleapis.com/auth/admin.directory.user", "https://www.googleapis.com/auth/admin.directory.user.security", "https://www.googleapis.com/auth/contacts", "https://www.googleapis.com/auth/gmail.modify" });

      Console.WriteLine(new HttpClient().GetStringAsync($"https://admin-admin.googleapis.com/admin/directory/v1/users/usertosearch?access_token={token}&domain= ").Result);

Comment: Where did you get this code are you following a sample from someplace?   Unauthorized means you dont have access something's wrong with your delegation.
Comment: I got it from https://www.ashishvishwakarma.com/get-access-token-for-google-api-service-account-c-sharp/ . Here it call userinfo.profile but i got the same error as i call users.get. I followed every step from this tutorial.
Comment: I think your issue is that its from Oct 10, 2017.    You need to delegate to a user if you want to get profile information back.
Comment: Already did it.
Comment: no you haven't not in your code I'm not seeing it
Comment: I just removed to post here but in the real one its there. https://admin-admin.googleapis.com/admin/directory/v1/users/USERHERE?access_token={token}&domain=DOMAINHERE . It's that you was talking about, right ?
Comment: Try my edit see if it helps.  Im a little busy right now so i dont have time to create you a full sample.
Comment: Ok, ill check it right now.
Comment: Same error, : Unauthorized  .
Comment: then you haven't configure deligation to the user on your domain yet
Comment: I tried to call it from postman getting the token and using it with url. I got the error : {
    "error": {
        "code": 401,
        "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",
        "status": "UNAUTHENTICATED"
    }
}

Still this is a delegation problem ? Or someting im doing wrong ?
Answer: In order for your service account to act on behalf of a user on your domain. Your code must demote what the user it is supposed to be impersonating.
That is what we use the CreateWithUser method for.   This user has been configured in my workspace domain to be allowed to access in my case google drive.
var credential = GoogleCredential.FromFile(PathToServiceAccountKeyFile)
    .CreateWithUser("firstname.lastname@example.com")  // delegate to user on workspace.
    .CreateScoped(new[] {DriveService.ScopeConstants.Drive});

Without denoting what user the service account is supposed to be impersonating, the service account cant do anything.
Comment: After all tests i actually found the problem and it was the user i was using. The user has acess to delegation but it wasn't admin and because of this i was getting the error. I changed it and its working now. Thanks !


Hierarchical Queries inside Join

Question: I'm facing one annoying problema and I would like some help.
This is the situation.
CREATE TABLE tree_hierarchy (
  id        NUMBER (20)
 ,parent_id NUMBER (20)
);
CREATE TABLE tree_information (
  id        NUMBER (20)
 ,some_text VARCHAR(20)
 ,tree_id NUMBER (20)
);
INSERT INTO tree_hierarchy (id, parent_id) VALUES (2, null);
INSERT INTO tree_hierarchy (id, parent_id) VALUES (4, 2);
INSERT INTO tree_hierarchy (id, parent_id) VALUES (9, 4);
INSERT INTO tree_hierarchy (id, parent_id) VALUES (20, null);
INSERT INTO tree_hierarchy (id, parent_id) VALUES (40, 20);
INSERT INTO tree_hierarchy (id, parent_id) VALUES (90, 40);
INSERT INTO tree_information (id, some_text, tree_id) VALUES (10,'Some teste', 2);
INSERT INTO tree_information (id, some_text, tree_id) VALUES (11,'Other tree', 20);

And i would like to do something like this.
SELECT hier.*
  FROM tree_information Ti
  JOIN (
        SELECT
            id,
            parent_id
         FROM tree_hierarchy th
         where connect_by_isleaf = 1
        START WITH th.id = ti.tree_id
        CONNECT BY PRIOR th.id = th.parent_id

  ) hier on 1=1;

but ti.tree_id is not visible inside the select.
If I change the start with condition for
 START WITH th.parent_id is null

Will stay wrong.
Someone has idea how to solve this situation ?
Comment: Can you please show what your expected output should be?
Comment: "Here is what I want to do" and then after that you show code, which DOESN'T do what you want to do (this is why you are posting this in the first place). So how are we supposed to guess what you DO want to do? From code that DOESN'T do it, and nothing else? Please see what OldProgrammer wrote above.
Answer: I would appreciate if you provide expected result explicitly.
My best guess is:
SELECT hier.*, ti.*
  FROM tree_information Ti
  JOIN (
        SELECT
            id,
            parent_id,
            connect_by_root th.id as tree_id
         FROM tree_hierarchy th
         where connect_by_isleaf = 1
        START WITH th.id in ( select tii.tree_id from tree_information Tii)
        CONNECT BY PRIOR th.id = th.parent_id
  ) hier on ti.tree_id = hier.tree_id;

ID  PARENT_ID   TREE_ID ID  SOME_TEXT   TREE_ID
 9          4         2 10  Some teste        2
90         40        20 11  Other tree       20

Hierarchical Queries inside Join


Why is referencing a column (as a left-hand operand) that is not part of the table being queried not an error in the EXISTS operator?

Question: Given this SQL batch:
CREATE TABLE #source
(
  ID int,
  SourceDescr varchar(255)
)
INSERT INTO #source
VALUES
(1, 'first'),
(2, 'second')

CREATE TABLE #target
(
  ID int,
  TargetDescr varchar(255)
)
INSERT INTO #target
SELECT * FROM #source

INSERT INTO #target
SELECT * FROM #source S
WHERE NOT EXISTS
(
  SELECT 1
  FROM #target
  WHERE SourceDescr = S.SourceDescr
  --       /\ How is this not an error?
)

Why does the WHERE clause in the EXISTS operator work? Surely there is no SourceDescr column in the #target table.
I even tried this and it also works:
INSERT INTO #target
SELECT * FROM #source S
WHERE NOT EXISTS
(
  SELECT SourceDescr -- ??
  FROM #target
  WHERE SourceDescr = S.SourceDescr
)

Reading the official documentation for EXISTS did not clarify this for me.
Thanks.
Comment: `WHERE SourceDescr = S.SourceDescr` is equivalent to `WHERE S.SourceDescr = S.SourceDescr` which is always true.
Answer: This is interpreted as:
INSERT INTO #target
    SELECT S.*
    FROM #source S
    WHERE NOT EXISTS
    (
      SELECT 1
      FROM #target
      WHERE S.SourceDescr = S.SourceDescr
    );

It runs, but it does not do what you intend.
This is one reason why I advise using qualified column names for all column references in all your queries.  Your intended logic:
INSERT INTO #target
    SELECT S.*
    FROM #source S
    WHERE NOT EXISTS
    (
      SELECT 1
      FROM #target t
      WHERE t.SourceDescr = S.SourceDescr
    );

would generate a compile-time error and never execute.
Answer: Because it is explained in the documentation: Subqueries (SQL Server):

column names in a statement are implicitly qualified by the table referenced in the FROM clause at the same level. If a column does not exist in the table referenced in the FROM clause of a subquery, it is implicitly qualified by the table referenced in the FROM clause of the outer query.