text:
Q: how to do relationships and usersession in the framework? I do own framework and lean call at this tutorial and several other
http://anantgarg.com/2009/03/13/write-your-own-php-mvc-framework-part-1/
I have two problems in connection with the framework,
1 As the easiest way to do relationships?
2 How to do sessions and login and registrations, whether it was best to SHA512 encryption? Is it enough to do it on functions or in some other way?
current framework repository is located here
https://bitbucket.org/zixxus/myframework/overview

A: Why not refer to some existing frameworks to see how they do things?
Why reinvent the wheel when you can use some of the code they do if their license allows it or if they are happy for you to.
Here is laravel - http://laravel.com/
Currently laravel uses (AES encryption via the mcrypt PHP extension) http://laravel.com/docs/4.2/security#encryption


text:
Q: Entity Framework read queries locking all database I'm developing a web application using ASP.NET MVC and EF6 to access the database.
One of the features of my web application allow the user to download a Excel file. The query to get the information from the database takes like 5 seconds and I notice that until the query it's done we can't do anything on the rest of the web application.
Is this the normal behaviour of EF, lock the database even with AsNoTracking on the query?
If I'm not doing anything wrong and this is the default behaviour of EF how should I resolve this locking problem?
(Update)
I'm using a SQL Server database and the "lock" happens when for exemple I export the excel file and at the same time do a search that uses the same table.
To organize my code i'm using Repository and UnitOfWork pattern and to create the instances i'm using DI Unity.
The UnitOfWork implementation:
public class UnitOfWork : IUnitOfWork
{

    private bool _disposed;
    private DbContext _dbContext;
    private Dictionary<string, dynamic> _repositories;
    private DbContextTransaction _transaction;

    public DbContext DbContext
    {
        get { return _dbContext; }
    }

    public UnitOfWork(DbContext dbContext)
    {
        _dbContext = dbContext;
    }

    public int SaveChanges()
    {
        return _dbContext.SaveChanges();
    }

    public IRepository<TEntity> Repository<TEntity>()
    {
        try
        {
            if (ServiceLocator.IsLocationProviderSet)
                return ServiceLocator.Current.GetInstance<IRepository<TEntity>>();

            if (_repositories == null)
                _repositories = new Dictionary<string, dynamic>();

            var type = typeof(TEntity).Name;

            if (_repositories.ContainsKey(type))
                return (IRepositoryAsync<TEntity>)_repositories[type];

            var repositoryType = typeof(Repository<>);

            _repositories.Add(type, Activator.CreateInstance(repositoryType.MakeGenericType(typeof(TEntity)), this));

            return _repositories[type];
        }
        catch(ActivationException ex)
        {
            throw new ActivationException(string.Format("You need to configure the implementation of the IRepository<{0}> interface.", typeof(TEntity)), ex);
        }
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    ~UnitOfWork()
    {
        Dispose(false);
    }

    public void Dispose(bool disposing)
    {
        if(!_disposed)
        {
            if(disposing)
            {
                try
                {
                    _dbContext.Dispose();
                    _dbContext = null;
                }
                catch(ObjectDisposedException)
                {
                    //the object has already be disposed
                }
                _disposed = true;
            }
        }
    }
}

The Repository implementation:
public class Repository<TEntity> : IRepository<TEntity>
        where TEntity : class
{
    private readonly IUnitOfWork _unitOfWork;
    private readonly DbContext _dbContext;
    private readonly DbSet<TEntity> _dbSet;

    public Repository(IUnitOfWork unitOfWork)
    {

        _unitOfWork = unitOfWork;
        _dbContext = unitOfWork.DbContext;
        _dbSet = _dbContext.Set<TEntity>();
    }

    #region IRepository<TEntity> implementation

    public void Insert(TEntity entity)
    {
        _dbSet.Add(entity);
    }

    public void Update(TEntity entity)
    {
        _dbContext.Entry(entity).State = EntityState.Modified;
    }

    public void Delete(TEntity entity)
    {
        _dbSet.Remove(entity);
    }

    public IQueryable<TEntity> Queryable()
    {
        return _dbSet;
    }

    public IRepository<TEntity> GetRepository<TEntity>()
    {
        return _unitOfWork.Repository<TEntity>();
    }

    #endregion

}

The Unity configuration:
    container.RegisterType<DbContext, DbSittiusContext>(new PerRequestLifetimeManager());
    container.RegisterType<IUnitOfWork, UnitOfWork>(new PerRequestLifetimeManager());

    //Catalog respository register types
    container.RegisterType<IRepository<Product>, Repository<Product>>();

    UnityServiceLocator locator = new UnityServiceLocator(container);
    ServiceLocator.SetLocatorProvider(() => locator);

To create my query have to create a extension method like this:
public static Product FindPublishedAtDateById(this IRepository<Product> repository, int id, DateTime date)
{
    return repository.
            Queryable().
            Where(p => p.Id == id).
            Where(p => p.PublishedFrom <= date && (p.PublishedTo == null || p.PublishedTo >= date)).
            SingleOrDefault();
}

A: If you're downloading a lot of data synchronously it will make the UI freeze up on you. Consider doing this asynchronously. What are you using client side, anyway?
I'm assuming you're generating an excel file from data in the database and it's just a matter of it being enough data that it takes ~5 seconds to create the file and send it to the user.

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP & MYSQL: mysqldump skips tables I am trying to take full backup of my database using php system function and mysqldump command.
<?php
date_default_timezone_set("Africa/Lagos");
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$database = 'db';
$user = 'me';
$pass = 'pass';
$host = 'localhost';
$dir = 'file' . date('Y.m.d_H.m.s') . '.sql.gz';
$tempConfig = tmpfile();
fwrite($tempConfig, "[client]\nhost={$host}\nuser={$user}\npassword={$pass}");
$tempConfigPath = stream_get_meta_data($tempConfig)['uri'];
echo "mysqldump --add-drop-table  --defaults-extra-file={$tempConfigPath} $database  --routines --triggers | gzip  > $dir";
system("mysqldump   --defaults-extra-file={$tempConfigPath} $database | gzip  > $dir");
exit;

The code runs fine, but the problem is it skips many tables. it backup 10 of 190+ tables. the last manual backup i took is about 190MB.
Any Assistance or explanation as to why its not backing up the full db will be helpful.
Thank you.


text:
Q: Does the following series converge or diverge: $\displaystyle\sum_{n=1}^{\infty}\frac{n!}{n^{n}}$? Which of the following series converge, and which diverge?

*

*$\displaystyle\sum_{n=1}^{\infty}\frac{1}{n^{2}+1}$

*$\displaystyle\sum_{n=1}^{\infty}\frac{n!}{n^{n}}$

*$\displaystyle\sum_{n=1}^{\infty}\frac{1}{\sqrt{n^{2}+n}}$
MY ATTEMPT
The first one converges due to the comparison test. Indeed, one has
\begin{align*}
\sum_{n=1}^{\infty}\frac{1}{n^{2}+1} \leq \sum_{n=1}^{\infty}\frac{1}{n^{2}}
\end{align*}
where the last series is the $p$-series with $p = 2 > 1$.
The second series does converge due to the ratio test. Indeed, one has
\begin{align*}
\lim_{n\to\infty}\frac{(n+1)!}{(n+1)^{n+1}}\times\frac{n^{n}}{n!} = \lim_{n\to\infty}\left(\frac{n}{n+1}\right)^{n} = \lim_{n\to\infty}\left(1 - \frac{1}{n+1}\right)^{n} = e^{-1} < 1
\end{align*}
Finally, for the third series it suffices to notice that $n^{2} + n \leq 2n^{2}$. Thence we conclude that it diverges. Indeed, one has
\begin{align*}
\sum_{n=1}^{\infty}\frac{1}{\sqrt{n^{2}+n}} \geq \frac{1}{\sqrt{2}}\sum_{n=1}^{\infty}\frac{1}{n} \longrightarrow +\infty
\end{align*}
Is the wording of my solutions good? Any comments and contributions are appreciated.

A: Most of this is correct and well-worded. Where you have used the phrase "harmonic series with $p = 2$", you really should say "$p$-series with $p = 2$. The harmonic series is $\sum_{n=1}^\infty \frac{1}{n}$, whereas $p$-series are series of the form $\sum_{n=1}^\infty \frac{1}{n^p}$.


text:
Q: Removing time series with only zero values from a data frame I have a data frame with multiple time series identified by uniquer id's. I would like to remove any time series that have only 0 values.
The data frame looks as follows,
id   date          value
AAA  2010/01/01    9
AAA  2010/01/02    10
AAA  2010/01/03    8
AAA  2010/01/04    4
AAA  2010/01/05    12
B    2010/01/01    0
B    2010/01/02    0
B    2010/01/03    0
B    2010/01/04    0
B    2010/01/05    0
CCC  2010/01/01    45
CCC  2010/01/02    46
CCC  2010/01/03    0
CCC  2010/01/04    0
CCC  2010/01/05    40

I want any time series with only 0 values to be removed so that the data frame look as follows,
id   date          value
AAA  2010/01/01    9
AAA  2010/01/02    10
AAA  2010/01/03    8
AAA  2010/01/04    4
AAA  2010/01/05    12
CCC  2010/01/01    45
CCC  2010/01/02    46
CCC  2010/01/03    0
CCC  2010/01/04    0
CCC  2010/01/05    40

This is a follow up to a previous question that was answered with a really great solution using the data.tables package.
R efficiently removing missing values from the start and end of multiple time series in 1 data frame

A: If dat is a data.table, then this is easy to write and read :
dat[,.SD[any(value!=0)],by=id]

.SD stands for Subset of Data.  This answer explains .SD very well.
Picking up on Gabor's nice use of ave, but without repeating the same variable name (DF) three times, which can be a source of typo bugs if you have a lot of long or similar variable names, try :
dat[ ave(value!=0,id,FUN=any) ]

The difference in speed between those two may be dependent on several factors including: i) number of groups ii) size of each group and iii) the number of columns in the real dat.

A: Try this. No packages are used.
DF[ ave(DF$value != 0, DF$id, FUN = any), ]

A: An easy  plyr solution would be
ddply(mydat,"id",function(x) if (all(x$value==0)) NULL else x)

(seems to work OK) but there may be a faster solution with data.table ...


text:
Q: SymbolTable not supported I am trying to find the unused methods using the Query Editor in Developer Console.
I have checked Use Tooling API.
Running SOQL like below:
SELECT Id FROM SymbolTable WHERE externalReferences = NULL

But getting this error:
SELECT Id FROM SymbolTable WHERE externalReferences
               ^
ERROR at Row:1:Column:16
sObject type 'SymbolTable' is not supported. If you are attempting to use a custom object, be sure to append the '__c' after the entity name. Please reference your WSDL or the describe call for the appropriate names.

What I am missing here?

A: You need to query the field from the ApexClass object first, as seen here
https://developer.salesforce.com/docs/atlas.en-us.api_tooling.meta/api_tooling/tooling_api_objects_apexclass.htm
Also

If there is not a cached version of SymbolTable, it will be compiled in the background and the query might take longer than expected. The SymbolTable returned from ApexClass does not contain references; to retrieve a SymbolTable with references, use ApexClassMember.


text:
Q: Backup Exec 2012 - Can only see Server 2012R2 Quorum Node I'm currently trying to get BE2012 to backup or restore to a 2 node failover cluster running on Server 2012R2. The cluster itself only serves a single file server role, which is behaving itself and is visible to clients in the test environment.
The names for the two nodes are FileServer1 and FileServer2, while the cluster is called "SharedFiles" and the file server role is "PublicFiles".
When adding the server to BE2012 however, BE can see the Quorum disk only - the shared disk is not visible through the interface.
In order to use backup exec with the cluster I followed these steps:

*

*Add each cluster node to BE, installing the agent on each.
(Fileserver1, Fileserver2)

*Add the cluster itself to BE. (SharedFiles)

At this point, when creating a test backup job, I get the file tree which shows the FQDN of the cluster, with the only option being the Quorum disk.
I'm now quite stumped. Here are some things I've tried which seem to have helped others in the past:

*

*I've tried failing over the cluster so the node hosting the share changes, figuring perhaps I was looking at a specific machine and not realising it. This doesn't have any effect.

*If I add the file role's (PublicFiles) FQDN to BE as a "file server" then I can see the storage as expected, presumably because its connecting directly via UNC path. Unfortunately you can't restore like this, only backup.

*The only bit of information I can find that kind of describes my symptom is this, for an older version of windows. However, I don't think its relevant as my node names are shorter than the limit in that article.

*If I try and backup the cluster nodes directly, I also can't see the shared volume. I can see the C:\ drives for both, and system state, but not the clustered disk. The clustered disk is visible through windows explorer when connected to the individual cluster node.

Does anyone have any advice on how I can go further with this?

A: This resolved itself - neither the cluster or the backup machine updated or rebooted, but today the quorum disk isn't visible and the actual cluster disk is.
Not really a resolution, so my apologies if you find this post looking for a similar issue.


text:
Q: Create a partial view inside a factory Suppose we have a factory for returning partials containing the logic to select a certain one. I would like some to delegate that responsibility to a factory and then write a neat code inside the controller:
    [HttpGet]
    public PartialViewResult GetQueryItemForCategory(string categoryName, bool campaignSelected)
    {
        return QueryItemBuilderFactory.BuildPartial(categoryName, campaignSelected);
    }

But I really cannot call the PartialView() method inside that factory.
public static class QueryItemBuilderFactory
{
    private static Dictionary<string, Func<bool, PartialViewResult>> _builderActions =
        new Dictionary<string, Func<bool, PartialViewResult>>();
    static QueryItemBuilderFactory()
    {
        _builderActions.Add("Data Field", campaignSelected =>
                                            {
                                                return  PartialView("_DataFieldQueryItemPartial");
                                            });
    }

    public static PartialViewResult BuildPartial(string categoryName, bool campaignSelected)
    {
        return _builderActions[categoryName](campaignSelected);
    }
}

Is there any way to implement it?

A: The protected PartialView methods is defined on the base Controller class:
public abstract class Controller : ControllerBase, IActionFilter,
    IAuthorizationFilter, IDisposable, IExceptionFilter, IResultFilter
{
    ...

    protected internal PartialViewResult PartialView()
    {
        ...
    }

    protected internal PartialViewResult PartialView(object model)
    {
        ...
    }

    protected internal PartialViewResult PartialView(string viewName)
    {
        ...
    }

    ...
}

So inheriting from this Controller class enables you to use this method, whereas it's not available in other situations.
However, as you can see the PartialView methods return PartialViewResult objects so replacing
return PartialView("_DataFieldQueryItemPartial");

in your example with
return new PartialViewResult(){ ViewName = "_DataFieldQueryItemPartial" };

will do the trick.

A: The 'PartialViewResult' class inherits 'ViewResultBase' class. The 'ViewResultBase' class has required properties and methods to setup new view type. Be careful while declaring a object type.

A: calling PartialView is in fact only returning PartialViewResult object. You can create new PartialViewResult anywhere really. So, you can create your own shortcut method FactoryPartialView() on your base controller, which fill use your factory instead "new" operator for creating PartialViewResult.


text:
Q: How to enable WSL2 , DISM can't find it on my updated Win10 I followed: https://docs.microsoft.com/en-us/windows/wsl/install-manual
Here is the output of the first command
Deployment Image Servicing and Management tool
Version: 10.0.19041.572

Image Version: 10.0.19042.631

Error: 0x800f080c

Feature name Microsoft-Windows-Subsystem-Linux is unknown.
A Windows feature name was not recognized.
Use the /Get-Features option to find the name of the feature in the image and try the command again.

Log is here: https://gist.github.com/geocine/e4606b1e6fdbe8b42402207e2d88a258
Clearly my windows is updated and shoult not throw this error so I ran sfc
Beginning system scan.  This process will take some time.

Beginning verification phase of system scan.
Verification 100% complete.

Windows Resource Protection did not find any integrity violations.

I tried to run RestoreHealth for DISM but always stops at 19.2
Deployment Image Servicing and Management tool
Version: 10.0.19041.572

Image Version: 10.0.19042.631

[===========                19.2%                          ]
Error: 3

The system cannot find the path specified.

The DISM log file can be found at C:\Windows\Logs\DISM\dism.log

Log is here: https://gist.github.com/geocine/12abf02e9e8d9f300a58bbcdc9374eac
But component store is not corrupted
dism /online /cleanup-image /checkhealth

It shows this
Deployment Image Servicing and Management tool
Version: 10.0.19041.572

Image Version: 10.0.19042.631

No component store corruption detected.
The operation completed successfully.


text:
Q: Deploy static assets to heroku from local machine - can't open file 'manage.py': [Errno 2] No such file or directory Estoy intentando desplegar mis archivos estáticos de mi aplicación que irá a heroku, en amazon s3, pues asi lo  tengo configurado en mis settings.
Cuando ejecuto el comando heroku run python manage.py collectstatic tengo el siguiente error:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku run python manage.py collectstatic
Running python manage.py collectstatic on neurorehabilitation.... up, run.5168
python: can't open file 'manage.py': [Errno 2] No such file or directory
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

Esto es extraño para mi, debido a que actualmente me encuentro en el directorio en donde esta localizado el archivo manage.py
Intenté aplicar permisos al archivo manage.py mediante chmod +x manage.py pero el resultado es igual
Cuando ejecuto el comando git push heroky master sin desplegar los estáticos antes con heroku run python manage.py collectstatic, tengo este log:
remote:      $ python manage.py collectstatic --noinput
remote:        Traceback (most recent call last):
remote:          File "manage.py", line 10, in <module>
remote:            execute_from_command_line(sys.argv)
remote:          File "/app/.heroku/python/lib/python3.4/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
remote:            utility.execute()
remote:          File "/app/.heroku/python/lib/python3.4/site-packages/django/core/management/__init__.py", line 345, in execute
remote:            self.fetch_command(subcommand).run_from_argv(self.argv)
remote:          File "/app/.heroku/python/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
remote:            self.execute(*args, **cmd_options)
remote:          File "/app/.heroku/python/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
remote:            output = self.handle(*args, **options)
remote:          File "/app/.heroku/python/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 176, in handle
remote:            collected = self.collect()
remote:          File "/app/.heroku/python/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 98, in collect
remote:            for path, storage in finder.list(self.ignore_patterns):
remote:          File "/app/.heroku/python/lib/python3.4/site-packages/django/contrib/staticfiles/finders.py", line 112, in list
remote:            for path in utils.get_files(storage, ignore_patterns):
remote:          File "/app/.heroku/python/lib/python3.4/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files
remote:            directories, files = storage.listdir(location)
remote:          File "/app/.heroku/python/lib/python3.4/site-packages/django/core/files/storage.py", line 299, in listdir
remote:            for entry in os.listdir(path):
remote:        FileNotFoundError: [Errno 2] No such file or directory: '/app/neurorehabilitation/settings/static'

Con un proyecto distinto si pude ejecutar exitosamente el comando  `heroku run python manage.py collectstatic``
No puedo entender la razón por la cual mi heroku toolbet no puede encontrar mi archivo manage.py
ACTUALIZACIÓN
Con el objetivo de tener un despliegue temprano de mi aplicación, he optado por desactivar la opción de archivos estáticos en la plataforma configurando la variable de entorno DISABLE_COLLECT_STATIC de esta forma:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku config:set DISABLE_COLLECTSTATIC=1
Setting config vars and restarting neurorehabilitation... done
DISABLE_COLLECTSTATIC: 1
(nrb_dev) ➜  neurorehabilitation_projects git:(master)

Así la cosas, cuando he hecho git push heroku master finalmente pude desplegar mi aplicación pues la notificación final fue:
remote:
remote:
remote: -----> Discovering process types
remote:        Procfile declares types -> web
remote:
remote: -----> Compressing...
remote:        Done: 46M
remote: -----> Launching...
remote:        Released v15
remote:        https://neurorehabilitation.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy... done.
To https://git.heroku.com/neurorehabilitation.git
 * [new branch]      master -> master
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

Como puede verse, en mi enlace principal https://neurorehabilitation.herokuapp.com/ existe un error, asumo que es debido a que no se colocaron o no se están relacionando los archivos estáticos ... no se si estoy en lo correcto ¿lo estoy?
Pero algo que me intriga es que puedo detallar el admin de Django https://neurorehabilitation.herokuapp.com/admin/ y es algo que me intriga debido a que el administrador Django también posee archivos estáticos, entonces no se si heroku esta o no trabajando con ellos ...
¿Qué habrá sucedido aquí en esta situación con mis archivos estáticos?
Sin embargo, seguí y esta vez si puedo desplegar remotamente sobre heroku acciones que involucren el comando pyhon manage.py <acción>, prueba de ello es que realice efectiva mis primera migraciones de mi aplicación:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku run python  manage.py migrate
Running python manage.py migrate on neurorehabilitation.... up, run.7836
Operations to perform:
  Apply all migrations: contenttypes, auth, userprofiles, sessions, medical_encounter_information, admin
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0001_initial... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying userprofiles.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying userprofiles.0002_auto_20160225_2130... OK
  Applying userprofiles.0003_auto_20160225_2130... OK
  Applying medical_encounter_information.0001_initial... OK
  Applying medical_encounter_information.0002_auto_20160225_2130... OK
  Applying medical_encounter_information.0003_auto_20160225_2130... OK
  Applying medical_encounter_information.0004_auto_20160225_2211... OK
  Applying medical_encounter_information.0005_auto_20160225_2211... OK
  Applying medical_encounter_information.0006_auto_20160225_2303... OK
  Applying medical_encounter_information.0007_auto_20160229_2204... OK
  Applying medical_encounter_information.0008_auto_20160229_2208... OK
  Applying medical_encounter_information.0009_auto_20160301_0130... OK
  Applying medical_encounter_information.0010_auto_20160301_0312... OK
  Applying medical_encounter_information.0011_auto_20160301_1525... OK
  Applying medical_encounter_information.0012_auto_20160301_1601... OK
  Applying medical_encounter_information.0013_auto_20160301_1606... OK
  Applying medical_encounter_information.0014_auto_20160301_1629... OK
  Applying medical_encounter_information.0015_auto_20160301_1633... OK
  Applying medical_encounter_information.0016_auto_20160301_1636... OK
  Applying sessions.0001_initial... OK
  Applying userprofiles.0004_auto_20160225_2211... OK
  Applying userprofiles.0005_auto_20160225_2211... OK
  Applying userprofiles.0006_auto_20160225_2303... OK
  Applying userprofiles.0007_auto_20160229_2204... OK
  Applying userprofiles.0008_auto_20160229_2208... OK
  Applying userprofiles.0009_auto_20160301_0130... OK
  Applying userprofiles.0010_auto_20160301_0312... OK
  Applying userprofiles.0011_auto_20160301_1525... OK
  Applying userprofiles.0012_auto_20160301_1601... OK
  Applying userprofiles.0013_auto_20160301_1606... OK
  Applying userprofiles.0014_auto_20160301_1629... OK
  Applying userprofiles.0015_auto_20160301_1633... OK
  Applying userprofiles.0016_auto_20160301_1636... OK
(nrb_dev) ➜  neurorehabilitation_projects git:(master)

También logré crear en mi aplicación desplegada en heroku un super usuario para ella, desde mi toolbet local:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku run python  manage.py createsuperuser
Running python manage.py createsuperuser on neurorehabilitation.... up, run.5381

Username: bgarcial
Email address: bgarcial@sample.com
Password:
Password (again):
Superuser created successfully.
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

Acto seguido desactivo la variable de entorno configurada anteriormente DISABLE_COLLECTSTATIC=1 (Lo que he hecho es borrarla desde mis heroku dashboard en los settings de mi aplicación)
Pero cuando quiero volver a ejecutar el comando heroku run python  manage.py collectstatic me pasa esto:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku run python  manage.py collectstatic
Running python manage.py collectstatic on neurorehabilitation.... up, run.9342

You have requested to collect static files at the destination
location as specified in your settings.

This will overwrite existing files!
Are you sure you want to do this?

Type 'yes' to continue, or 'no' to cancel: yes
Traceback (most recent call last):
  File "manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/app/.heroku/python/lib/python3.4/site-packages/django/core/management/__init__.py", line 353, in execute_from_command_line
    utility.execute()
  File "/app/.heroku/python/lib/python3.4/site-packages/django/core/management/__init__.py", line 345, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/app/.heroku/python/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/app/.heroku/python/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "/app/.heroku/python/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 176, in handle
    collected = self.collect()
  File "/app/.heroku/python/lib/python3.4/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 98, in collect
    for path, storage in finder.list(self.ignore_patterns):
  File "/app/.heroku/python/lib/python3.4/site-packages/django/contrib/staticfiles/finders.py", line 112, in list
    for path in utils.get_files(storage, ignore_patterns):
  File "/app/.heroku/python/lib/python3.4/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files
    directories, files = storage.listdir(location)
  File "/app/.heroku/python/lib/python3.4/site-packages/django/core/files/storage.py", line 299, in listdir
    for entry in os.listdir(path):
FileNotFoundError: [Errno 2] No such file or directory: '/app/neurorehabilitation/settings/static'
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

Viendo todo esto, asumo que el error está acá al final:
 directories, files = storage.listdir(location)
      File "/app/.heroku/python/lib/python3.4/site-packages/django/core/files/storage.py", line 299, in listdir
        for entry in os.listdir(path):
    FileNotFoundError: [Errno 2] No such file or directory: '/app/neurorehabilitation/settings/static'

Y asumo que en la aplicación remota que he desplegado no se encuentra el directorio static que al igual que en la local es desde alli de donde se originan para ser almacenados en un CDN, en este caso a amazon S3.
No se como enfrentar esto, ¿Por qué en mi deployment no se generan completos los directorios que tengo en mi local machine?
ACTUALIZACIÓN 2
He ejecutado heroku run bash para detallar la estructura de directorios en mi aplicación en la nube y puedo detallar la raíz de mi proyecto, llamada  /app en heroku.
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku run bash
    Running bash on neurorehabilitation.... up, run.5840
    ~ $ pwd
    /app
    ~ $

Al listar su contenido veo todos mis directorios y archivos, de manera similar a como los tengo en mi IDE/entorno de desarrollo
~ $ ls
avatars  custom_storages.py  django-multiselectfield-0.1.3.tar.gz  functional_tests  manage.py  medical_encounter_information  neurorehabilitation  Procfile  requirements  requirements.txt  runtime.txt  userprofiles

Como mi error tiene que ver con este archivo ...
FileNotFoundError: [Errno 2] No such file or directory: '/app/neurorehabilitation/settings/static'

Entonces entro a dicho directorio /app/neurorehabilitation/settings/ pero veo que no existe un directorio llamado static ahí dentro como lo intenta buscar heroku
~ $ cd /app/neurorehabilitation/settings/
~/neurorehabilitation/settings $ ls
base.py  development.py  __init__.py  production.py  staging.py  testing.py
~/neurorehabilitation/settings $

Y esto es porque acorde a la estructura de directorios que yo he establecido cuando cree mi proyecto Django en mi entorno local de desarrollo, definí lo siguiente:

Entonces, acorde a esto, porque git al hacer deploy a heroku esta buscando una ruta neurorehabilitation/settings/static cuando esta no esta dada, desde la fuente original (mi máquina o entorno de desarrollo) ...
¿Qué podría hacer al respecto, pues heroku, cuando yo le doy heroky run python manage.py collectstatic éste busca un directorio que no existe o no esta contemplado en la estructura de archivos de mi proyecto?
Incluso creo que esa es la razón por la cual mis archivos estáticos no son mostrados, pues claro es obvio, no los subí en el push  entonces en mi url principal de la aplicación ya desplegada https://neurorehabilitation.herokuapp.com no se renderizan ni mis templates ni mis CSS ni mis JS porque supongo que acorde a lo que me sucede, heroku los  busca es en dicho directorio que no existe ¿verdad?
Aunque no se porque el admin si funciona https://neurorehabilitation.herokuapp.com/admin/ a pesar de ser una app (django-suit) pero esta tiene CSS JS y demás ...
Es posible que no haya comprendido bien como trabaja heroku en el sentido de deployment en relación a los archivos y directorios
Agradezco algún tipo de orientación :)

A: He querido crear una respuesta paso a paso tomando como referencias algunas orientaciones que he recibido (incluyendo las respuestas y comentarios de esta pregunta) y lo que he podido encontrar de recursos e información alrededor del tema.
A continuación compartiré el paso a paso que he realizado para el despliegue de mi aplicación en Heroku. Espero que lo que pueda escribir aquí pueda ser de utilidad.

*

*Configurando como trabajarán los archivos estáticos en los settings para desplegar a Heroku
El inconveniente por el cual no podía desplegar mis archivos estáticos a Heroku estaba en la configuración de mi archivo settings/base.py
Específicamente, el inconveniente estaba en el valor que tenía mi directiva llamada PROJECT_ROOT.
Heroku sugiere que la directiva de configuración PROJECT_ROOT esté de esta forma:
PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__))

Yo configuraba a PROJECT_ROOT (la he llamado BASE_DIR en mi archivo settings/base.py y asi se referenciará de acá en adelante en mi respuesta) tal como Heroku lo decía, pero el error siempre aparecía.
Lo que decidí fue que como BASE_DIR tiene un valor de configuración por defecto cuando se crea el proyecto Django, entonces lo dejé tal cual con ese valor y no como lo dice Heroku.
Asi las cosas, mi error que tenía, que era este:
FileNotFoundError: [Errno 2] No such file or directory: '/app/neurorehabilitation/settings/static'

era porque tenía a BASE_DIR de esta forma:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))

Entonces, para corregirlo, finalmente mi archivo settings/base.py para configurar mi aplicación y que sea desplegada en Heroku, ha quedado de esta forma:
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/

# This line tells Django to look for static files in a folder named static inside each of our apps.
STATIC_URL = '/static/'

En realidad la raíz del error está en el valor que tomaba la directiva STATICFILES_DIRS que es la que finalmente marca la pauta en relación a la estructura de directorios de los archivos estáticos sin importar la infraestructura en donde estén desplegados.
Al tener configurado mi BASE_DIR de una forma, esto incide en el valor que toma STATICFILES_DIRS, la cual queda de esta forma también para un correcto despĺiegue de mi aplicación: (creo que es asi como la pone por defecto Django, asu que no hay que mover nada con ella)
# With this configuration, Django will look for static files in a folder named static inside each app and into the neurorehabilitation/static folder
STATICFILES_DIRS = (
    os.path.join(BASE_DIR, "static"),
)

Como yo tengo un directorio de settings (settings/{base.py, development.py,production.py,testing.py,staging.py}) y como en estos momentos me dispongo a poner en producción mi aplicación en Heroku, entonces debo configurar de manera apropiada mi archivo settings/production.py pues es el que tomara Heroku para la configuración del despliegue.
Mi archivo settings/production.py en relación a Heroku queda de esta forma:
# Heredo del archivo settings/base.py que es en donde estan las
# configuraciones base o comunes de mi proyecto Django
from .base import *
import dj_database_url

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False

# ------ *** -------------
# For deploy to heroku
# ------ *** -------------

# Update database configuration with $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

# Honor the 'X-Forwarded-Proto' header for request.is_secure()
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')

ALLOWED_HOSTS = ['*']

Vale la pena resaltar que si no se tiene un conjunto de settings como lo tengo acá, todas estas configuraciones pueden ir en el archivo settings.py que por defecto genera Django cuando se crea el proyecto.

Por si consideran necesario saber como configurar un conjunto de
  settings.py, la genial Marina Mele lo explica de esta forma en su
  blog el cual recomiendo visitar y leer, es muy útil.

Adicionalmente, también es necesario instalar el paquete dj-database-url en mi entorno virtual que uso en mi máquina
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ pip install dj-database-url
Collecting dj-database-url
Installing collected packages: dj-database-url
Successfully installed dj-database-url-0.4.0
You are using pip version 8.1.0, however version 8.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

y asi mismo adicionarlo a mi archivo de requirements/production.txt de esta forma
dj-database-url==0.4.0

Para los requerimientos de paquetes, también se tiene un conjunto de archivos de esta forma requirements/{base.txt,development.txt,production.txt,testing.txt} acorde a esta definición u orientación

En este punto del numeral 1 básicamente describo la razón por la
  cual el comando collectstatic no me funcionaba cuando desplegaba mi
  aplicación en heroku y se intentaba copiar y procesar mis archivos
  estáticos a Amazon S3 que es en donde los tengo.

Entonces, además, también he querido compartir el proceso de despliegue de mi aplicación Django en Heroku y otros requisitos para que se haga efectivo.

*Otros archivos necesarios
Adicionalmente, para que el proceso de despligue sea exitoso, es necesario tener en la raíz de mi proyecto los siguientes archivos:

requirements.txt: Como había mencionado anteriormente, tengo este conjunto de archivos para las dependencias de mis paquetes requirements/{base.txt,development.txt,production.txt,testing.txt}
Entonces en la raíz de mi proyecto creo un archivo llamado requirements.txt (ver recuadro amarillo en el enlace) con el siguiente contenido:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ cat requirements.txt
-r requirements/production.txt%                                                 (nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

Y mi archivo requirements/production.txt ha quedado asi:
-r base.txt
gunicorn==19.4.5
dj-database-url==0.4.0

El archivo requirements/base.txt contiene todas las dependencias o paquetes necesarios que son base para mi aplicación.

runtime.txt
Acorde a este enlace, es necesario que Heroku instale la versión de python con la cual estamos trabajando, en mi caso, tengo la 3.4.3, por lo que el contenido de mi archivo runtime.txt (que también debe ir en la raíz de mi proyecto) es:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ cat runtime.txt
python-3.4.3
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

Procfile
Segun este enlace el archivo Procfile

define los tipos de proceso y declara explícitamente que comando debe
  ser ejecutado para inicializar mi aplicación.

Con relación a esta definición, básicamente lo que hacemos es que nuestro archivo Procfile tendrá la instrucción que habilitará el servidor gunicorn que tomará las peticiones y las redirigirá a python, por lo cual es WSGI
Asi las cosas, el archivo Procfile en la raíz del proyecto debe quedar asi:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ cat Procfile
web: gunicorn neurorehabilitation.wsgi --log-file -
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

*Probando el acceso desde mi máquina a través de Heroku Toolbet
Es necesario instalar Heroku Toolbet el cual proporciona acceso a una interfaz de línea de comandos de Heroku (basicamente es una porción o un sistema operativo unix de la maquina en donde esta alojada mi aplicación en Heroku) la cual es utilizada para administrar y escalar aplicaciones asi como extensiones, entre otras cosas.
Probamos el acceso a Heroku desde nuestra máquina de esta forma:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku login
Enter your Heroku credentials.
Email: botibagl@gmail.com
Password (typing will be hidden):
Logged in as botibagl@gmail.com
(nrb_dev) ➜

*Creando mi aplicación en Heroku
Acorde a esta respuesta como mi aplicación a desplegar es python y Django, la aplicación en Heroku desde la herramienta toolbet debe ser creada de esta manera:
 (nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku create test-nrb --buildpack heroku/python
Creating test-nrb... done, stack is cedar-14
Setting buildpack to heroku/python... done
https://test-nrb.herokuapp.com | https://git.heroku.com/test-nrb.git
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

Entonces, de esta manera, mi aplicación Heroku se crea en mi dashboard en mi cuenta web:

*Configurando las variables de entorno que tengo definidas en mi proyecto para que Heroku las entienda
Particularmente en mi proyecto, en mi entorno virtual en mi maquina local, tengo algunas variables de entorno definidas.
Algunas son utilizadas para ocultar valores como el de mis SECRET_KEY's, DATABASE_USER, DATABASE_NAME, DATABASE_PASSWORD, y como estoy utilizando Amazon S3 para alojar mis archivos estáticos, entonces también utilizo algunas claves e identificadores para acceder a estos recursos en Amazon.
Entonces como decíamos, es necesario indicarle a Heroku la forma en la que él conocerá estas variables de entorno.
De acuerdo a este enlace, se configuran las siguientes variables via heroku toolbeet de esta forma:

*

*DJANGO_SETTINGS_MODULE
Mi despliegue, a nivel de configuración, será guiado por el archivo settings/production.py el cual hereda de settings/base.py que es el que tiene todas las dependencias necesarias desde la perspectiva del dominio de mi aplicación.
Entonces la variable DJANGO_SETTINGS_MODULE en Heroku sera configurada de esta forma:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku config:set DJANGO_SETTINGS_MODULE=neurorehabilitation.settings.production
Setting config vars and restarting test-nrb... done
DJANGO_SETTINGS_MODULE: neurorehabilitation.settings.production
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

*

*SECRET_KEY
Para SECRET_KEY la configuración es la siguiente:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku config:set SECRET_KEY='my_secret_key'
Setting config vars and restarting test-nrb... done
SECRET_KEY: 6o_g=0jeqp4)b4q!tt+ic4cgxs^0s=$_rtokd1ndja=4f(9&74
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

Para el acceso a la base de datos, se configuran las siguientes variables:

*

*DATABASE_NAME
Nombre de la base de datos:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku config:set DATABASE_NAME=mydatabasename
Setting config vars and restarting test-nrb... done
DATABASE_NAME: mydatabasename
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

*

*DATABASE_USER
Usuario de la base de datos:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku config:set DATABASE_USER=mydatabaseuser
Setting config vars and restarting test-nrb... done
DATABASE_USER: mydatabaseuser
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

*

*DATABASE_PASSWORD
Contraseña de la base de datos, el password debe ir en comillas simples
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku config:set DATABASE_PASSWORD='mydatabasepassword'
Setting config vars and restarting test-nrb... done
DATABASE_PASSWORD: mydatabasepassword
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

Para acceder a Amazon S3 es necesario configurar las siguientes variables:

*

*Amazon Web Services Access Key ID
El valor del ID debe ir en comillas simples
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku config:set AWS_ACCESS_KEY_ID='my_aws_access_key_id'
Setting config vars and restarting test-nrb... done
AWS_ACCESS_KEY_ID: my_aws_access_key_id
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

*

*Amazon Web Services Secret Access Key
El valor de la clave debe ir en comillas simples
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku config:set AWS_SECRET_ACCESS_KEY='my_aws_secret_access_key'
Setting config vars and restarting test-nrb... done
AWS_SECRET_ACCESS_KEY: my_aws_secret_access_key
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

*

*Amazon Web Services Storage Bucket name
El valor del nombre del bucket (unidad de almacenamiento en Amazon) debe ir en comillas simples
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku config:set AWS_STORAGE_BUCKET_NAME='my-bucket-name-in-s3'
Setting config vars and restarting test-nrb... done
AWS_STORAGE_BUCKET_NAME: my-bucket-name-in-s3
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

Entonces, acorde a las opciones de arriba, en mi dashboard web, las variables de entorno han quedado asi:

*Confirmando los cambios en mi proyecto (git commit) al repositorio de mi aplicación en Heroku

Primero examinamos los archivos que ha sido agregados y están en fase de staging o están listos para ser confirmados:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)

    new file:   requirements.txt
    new file:   runtime.txt

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   neurorehabilitation/settings/base.py
    modified:   neurorehabilitation/settings/development.py
    modified:   neurorehabilitation/settings/production.py
    modified:   requirements.txt
    modified:   runtime.txt

Untracked files:
  (use "git add <file>..." to include in what will be committed)

    .idea/
    Procfile
    gunicorn_start

(nrb_dev) ➜  neurorehabilitation_projects git:(master)

(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ git add requirements.txt
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ git add runtime.txt
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ git add Procfile
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ git add neurorehabilitation/settings/base.py
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ git add neurorehabilitation/settings/development.py
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ git add neurorehabilitation/settings/production.py

Realizamos la operación de commit
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ git commit -m 'Setup changes and configurations for deploy to heroku'
[master 69d69fe] Setup changes and configurations for deploy to heroku
 6 files changed, 38 insertions(+), 5 deletions(-)
 create mode 100644 Procfile
 create mode 100644 requirements.txt
 create mode 100644 runtime.txt
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

*Desplegamos el código de nuestra aplicación al repositorio que heroku ha creado para ella
Antes de ello, es bueno que nos cercioremos que repositorios remotos o alias tenemos asignados. Es importante, porque el alias de heroku es el que debemos tener en cuenta para el deployment al repositorio que heroku crea al crear la aplicación.
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ git remote -v
heroku  https://git.heroku.com/neurorehabilitation.git (fetch)
heroku  https://git.heroku.com/neurorehabilitation.git (push)
origin  https://bgarcial@bitbucket.org/bgarcial/neurorehabilitation_projects.git (fetch)
origin  https://bgarcial@bitbucket.org/bgarcial/neurorehabilitation_projects.git (push)
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

Desplegamos la aplicación al repositorio heroku
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ git push heroku master
Counting objects: 20, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (13/13), done.
Writing objects: 100% (13/13), 1.17 KiB | 0 bytes/s, done.
Total 13 (delta 11), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Using set buildpack heroku/python
remote: -----> Python app detected
remote:      $ pip install -r requirements.txt
remote:
remote:      $ python manage.py collectstatic --noinput
remote:        Found another file with the destination path 'admin/css/forms.css'. It will be ignored since only the first encountered file is collected. If this is not what you want, make sure every static file has a unique path.
remote:        147 static files copied.
remote:
remote:
remote: -----> Discovering process types
remote:        Procfile declares types -> web
remote:
remote: -----> Compressing...
remote:        Done: 46.1M
remote: -----> Launching...
remote:        Released v15
remote:        https://test-nrb.herokuapp.com/ deployed to Heroku
remote:
remote: Verifying deploy.... done.
To https://git.heroku.com/test-nrb.git
   9f0d32f..fcc62c9  master -> master
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

*Ejecutamos las migraciones de nuestra aplicación
Realizamos el proceso de migración para que se hagan efectivos nuestros modelos:
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku run python manage.py migrate
Running python manage.py migrate on test-nrb.... up, run.1678
Operations to perform:
  Apply all migrations: medical_encounter_information, userprofiles, contenttypes, auth, admin, sessions
Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying contenttypes.0002_remove_content_type_name... OK
  Applying auth.0001_initial... OK
  Applying auth.0002_alter_permission_name_max_length... OK
  Applying auth.0003_alter_user_email_max_length... OK
  Applying auth.0004_alter_user_username_opts... OK
  Applying auth.0005_alter_user_last_login_null... OK
  Applying auth.0006_require_contenttypes_0002... OK
  Applying auth.0007_alter_validators_add_error_messages... OK
  Applying userprofiles.0001_initial... OK
  Applying admin.0001_initial... OK
  Applying admin.0002_logentry_remove_auto_add... OK
  Applying userprofiles.0002_auto_20160225_2130... OK
  Applying userprofiles.0003_auto_20160225_2130... OK
  Applying medical_encounter_information.0001_initial... OK
  Applying medical_encounter_information.0002_auto_20160225_2130... OK
  Applying medical_encounter_information.0003_auto_20160225_2130... OK
  Applying medical_encounter_information.0004_auto_20160225_2211... OK
  Applying medical_encounter_information.0005_auto_20160225_2211... OK
  Applying medical_encounter_information.0006_auto_20160225_2303... OK
  Applying medical_encounter_information.0007_auto_20160229_2204... OK
  Applying medical_encounter_information.0008_auto_20160229_2208... OK
  Applying medical_encounter_information.0009_auto_20160301_0130... OK
  Applying medical_encounter_information.0010_auto_20160301_0312... OK
  Applying medical_encounter_information.0011_auto_20160301_1525... OK
  Applying medical_encounter_information.0012_auto_20160301_1601... OK
  Applying medical_encounter_information.0013_auto_20160301_1606... OK
  Applying medical_encounter_information.0014_auto_20160301_1629... OK
  Applying medical_encounter_information.0015_auto_20160301_1633... OK
  Applying medical_encounter_information.0016_auto_20160301_1636... OK
  Applying sessions.0001_initial... OK
  Applying userprofiles.0004_auto_20160225_2211... OK
  Applying userprofiles.0005_auto_20160225_2211... OK
  Applying userprofiles.0006_auto_20160225_2303... OK
  Applying userprofiles.0007_auto_20160229_2204... OK
  Applying userprofiles.0008_auto_20160229_2208... OK
  Applying userprofiles.0009_auto_20160301_0130... OK
  Applying userprofiles.0010_auto_20160301_0312... OK
  Applying userprofiles.0011_auto_20160301_1525... OK
  Applying userprofiles.0012_auto_20160301_1601... OK
  Applying userprofiles.0013_auto_20160301_1606... OK
  Applying userprofiles.0014_auto_20160301_1629... OK
  Applying userprofiles.0015_auto_20160301_1633... OK
  Applying userprofiles.0016_auto_20160301_1636... OK
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

*Creo mi super usuario en mi aplicación

A traves de createsuperuser
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗ heroku run python manage.py createsuperuser
Running python manage.py createsuperuser on test-nrb.... up, run.7499
Username: bgarcial
Email address: bgarcial@eafit.edu.co
Password:
Password (again):
Superuser created successfully.
(nrb_dev) ➜  neurorehabilitation_projects git:(master) ✗

Y es así como queda mi aplicación desplegada en la plataforma heroku https://test-nrb.herokuapp.com/

A: Git no guarda directorios, solo archivos y sólo crea los directorios al clonar que tienen archivos adentro, por lo tanto, puede que si el directorio está vacío (o sea que no hay ningún archivo que esté trackeado en git dentro del directorio) entonces heroku no va a tener dicho directorio.
Además tenes que tener en cuenta que en heroku no tenés permiso de escritura en /app, si necesitas escribir archivos (incluso de forma temporal al compilar) tenés que hacerlo en /tmp


text:
Q: Magnum CI with private github repository I am using Magnum CI with a private github repository.
I have the web hook set up for the Magnum CI, the pushes launch a build.
The build is getting an error when pulling the code down from github. I get the error
remote: Invalid username or password.
I have the Magnum CI rsa key in the branch settings.
What do I need to do?

A: The problem was that Magnum CI requires the SSH of your github. I was using the HTTPS address.


text:
Q: How to redirect to another application Single Sign On Identity Server 4 and logout I have an application A and an application B both of which are Asp.Net MVC Core 2.2 which should behave as if they are a single application to the end user; I'm using SSO in Identity Server; and in order to share claims between them I have given them the same Authentication Cookie name, Application name and access to a shared data protection key location as per the instructions:
https://learn.microsoft.com/en-us/aspnet/core/security/cookie-sharing?view=aspnetcore-2.2
If I login to A and then Redirect to B I can see the claims as expected shared between the applications; however if I then logout from B the logoutId which is generated and sent to the Identity Server 4 has no knowledge of B.
If I give a different name for the Authentication Cookie then I cannot share the claims but after redirecting to B and then logout from B the logoutId which is generated works correctly.
If after redirecting to B then waiting for the login session to timeout and re-authenticating then logout the logout of B works correctly; and the logoutId which is generated and sent to Identity Server 4 has knowledge of both A and B.
I believe this is because after redirecting to B when the Authorize attribute triggers a check that the user is Authenticated; which the user is in Application A and this is 'mistaken' for being already Authenticated in B; as this is a SSO there is no reason to authenticate in B as if authentication was checked with the Identity Server 4 then the user would be authenticated; however since the authentication is not checked the knowledge that the user has redirected to B is not stored in the shared authentication cookie and thus on Sign-out the Identity Server 4 does not receive the correct logoutId.
What can I do to force Identity Server 4 to be notified and thus update the Shared Cookie after the redirect to Application B?

A: You should not use shared cookies between your Angular apps to achieve SSO behavior. Neither you should share claims between those apps. In OAuth, the SSO is achieved by having a single authority uri (your Identity Server 4) that all your domain apps use to authenticate users, meaning that once user goes to application A and is redirected to login and completes login flow, the cookie is left on the on your Identity Server 4 app, and then once you redirect your application B it will see that it's not authenticated and redirect to the Identity Server 4 which will then use the cookie and automatically log the user in (can even skip consent page optionally).
Single sign out is a bit more difficult and is achieved by using SignOutIFrame on your Identity Server 4. In a nutshell, the idea is that once you initiate the logout flow from one of your apps, after the user successfully logs out from the Identity Server 4 app, the rendering of this SignOutIFrame causes all other clients to optionally participate in the logout flow and clear the session, etc. for a given user. More info can be found here.


text:
Q: Input Latitude, Longitude and distance and return sql string filtered by minLat and maxLat and minLong and maxLong So am using an interface called KScript, which is similar to javascript. The purpose is to return an SQL string, that includes lat and long min and max values, so that I can query our database.
Our database consists of records similar to this:
NAME: xy, DATA: xy, LONGITUDE: 53.34, LATIDUDE: 10.03
Now, when the user in the app requests a data record he can put in his current lat and long and drag a distance slider. So I am also giving the script the distance paramater. As a first attempt, I tried just using latitude and simple deducting and adding half of the distance to the latitude. (I know, in reality this is about 100x too much, but just to check).
Now I can definitaly correct this, but i wouldnt know how to account for longitude, as this in effect is now a circle and no longer a straight line.
I tried reading into this, but I dont think much applied to this scenario.
In the end, I need to return an SQL string that basically says:
SELECT xyz WHERE latitude >= " +  minLat + " AND latitude <= " + maxLat + " AND
longitude >= " +  minlong+ " AND longitude <= " + maxLong+ "

So that I can query our database.
This is my attempt:
var distanceLatString = ""
var minLat = 0
var maxLat = 0

if(latitude != 0 )
{
    minLat = (latitude - (distance/2))
    maxLat = (latitude + (distance/2))
    distanceLatString = "(latitude >= " +  minLat + " AND latitude <= " + maxLat + ")"
}

again, this does give me correct results (even with the distance calculation being incorrect, ofc).
Can someone maybe help me out here?
Thank you!


text:
Q: Prove $f_n(x)=(1-x/n)^n$ converges uniformly on non-negative reals I need to prove $f_n(x)=(1-x/n)^n$ converges on non-negative reals. I can easily prove it converges to $f(x)=e^{-x}$, but it is unclear to me whether this convergence is pointwise or uniform.
I have attempted the proof by taking the Taylor expansion of $f$ and do the binomial expansion of $f_n$, and then subtract.
\begin{equation}
|f(x)-f_n(x)|=|\sum_{k=0}^{\infty}(-1)^k\frac{x^k}{k!}-\sum_{k=0}^{n}(-1)^k\binom{n}{k}(\frac{x}{n})^k|\\
=|\sum_{k=0}^{n}(-1)^k\frac{x^k}{k!}-(-1)^k\binom{n}{k}(\frac{x}{n})^k+O(\frac{1}{n^{k+1}})|
\end{equation}
Toss out the big O term for now, since it is just part of the Taylor expansion of $e^{-x}$, with $k>n$. I tried manipulate the terms.
\begin{equation}
=|\sum_{k=0}^{n}(-1)^k\frac{x^k}{k!}(1-\frac{n(n-1)...(n-k+1)}{n^k})|\\
=|\sum_{k=0}^{n}(-1)^k\frac{x^k}{k!}\frac{n^k-n(n-1)...(n-k+1)}{n^k}|\\
\end{equation}
For any non-negative real $x$, each term in the summation clearly converges as we take $n$ large enough. But given a fixed $\epsilon>0$, I can't seem to find $N\in \mathbb{Z^+}$ such that such that $\forall n>N$, $|f(x)-f_n(x)|<\epsilon$. In other word, I have trouble proving the speed of the convergence does not depend on $x$.
Any help would be greatly appreciated, as I really would like to understand this. Thank you in advance!

A: The convergence is not uniform: if it was, then for all $\varepsilon>0$ there exists an $n_0\in\mathbb N$ such that, if $n\geq n_0$, then $|f_n(x)-e^{-x}|<\varepsilon$ for all $x\geq 0$, so $|f_n(2n)-e^{-2n}|<\varepsilon$ for all $n\geq n_0$. Therefore, the sequence $(f_n(2n)-e^{-2n})$ converges to $0$. But, $$f_n(2n)-e^{-2n}=\left(1-\frac{2n}{n}\right)^n-e^{-2n}=(-1)^n-e^{-2n},$$ which does not converge to $0$, and this is a contradiction.


text:
Q: "Truth" as a reply instead of "True" I think this sentence is grammatically correct:

*

*You need a new pair of glasses.

*True.

However, I've heard sometimes someone says Truth instead of True:

*

*You need a new pair of glasses.

*Truth.

Is this correct? Or is it a well-known slang term? Or is it just plain wrong?

A: Truth and true are subtly different in that true, in this sense, is more about accuracy and facts.  Truth extends into a person's veracity, belief system, and perception of reality.  Truth tends to be more a collective term - "Your truth and mine differ" is a reasonable statement.  I agree that "Truth" would be a less likely answer to the cited statement, but it might be an answer to someone saying "God created the Universe".  "(That's) True" as an answer would discount a knowledge that that might not be universally accepted, while "(You speak the) Truth" would indicate that it matches the speakers view of reality.

A: "True" is short for "that's true", and is definitely more widespread than "truth". "Truth" will definitely sound like slang to others.


text:
Q: How does Squirrel add jdbc jars dynamically? Java Squirrel is an great sql tool. It supports ALL databases. I checked it. The only thing you need to do is to point to an external jar.
However, in java, a classpath is immutable. How is it possible? Here is the only solution that works How should I load Jars dynamically at runtime?. However the author says it's hackish
try {
    File file = ...
    URL url = file.toURI().toURL();

    URLClassLoader classLoader = (URLClassLoader)ClassLoader.getSystemClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);
    method.invoke(classLoader, url);
} catch (Exception ex) {
    ex.printStackTrace();
}

How does Squirrel do it? I presume Squirrel is benchmark


text:
Q: R: plotting lines (SpatialLinesDataFrame) with a different line type according to a nominal attribute Data
I have two pairs of lines (SpatialLinesDataframe), 4 overall. The dataset is pasted below:
mydata <- new("SpatialLinesDataFrame", data = structure(list(length = c(500.842234293619,
293.606797749979, 612.066409242344, 629.705729467346), funct = c("t",
"t", "wcs", "wcs")), row.names = c("1", "2", "11", "21"), class = "data.frame"),
    lines = list(new("Lines", Lines = list(new("Line", coords = structure(c(2667675,
    2667655, 2667645, 2667655, 2667645, 2667645, 2667655, 2667665,
    2667675, 2667695, 2667705, 2667705, 2667695, 2667695, 2667705,
    2667725, 2667735, 2667755, 2667775, 2667795, 2667815, 2667825,
    2667835, 2667845, 2667855, 2667865, 2667865, 2667855, 6479005,
    6479015, 6479015, 6479035, 6479055, 6479065, 6479085, 6479095,
    6479115, 6479125, 6479145, 6479155, 6479175, 6479185, 6479205,
    6479215, 6479225, 6479235, 6479245, 6479255, 6479265, 6479275,
    6479285, 6479295, 6479315, 6479335, 6479345, 6479365), .Dim = c(28L,
    2L), .Dimnames = list(NULL, c("x", "y"))))), ID = "1"), new("Lines",
        Lines = list(new("Line", coords = structure(c(2667675,
        2667685, 2667695, 2667705, 2667725, 2667735, 2667745,
        2667765, 2667785, 2667795, 2667815, 2667835, 2667855,
        2667875, 2667895, 2667905, 2667925, 2667935, 6479005,
        6479005, 6479005, 6479005, 6478995, 6478995, 6479015,
        6479025, 6479015, 6479015, 6479005, 6478995, 6478985,
        6478975, 6478965, 6478965, 6478955, 6478955), .Dim = c(18L,
        2L), .Dimnames = list(NULL, c("x", "y"))))), ID = "2"),
        new("Lines", Lines = list(new("Line", coords = structure(c(2667675,
        2667655, 2667655, 2667665, 2667655, 2667675, 2667665,
        2667655, 2667675, 2667665, 2667655, 2667645, 2667635,
        2667645, 2667655, 2667665, 2667675, 2667695, 2667705,
        2667695, 2667685, 2667695, 2667705, 2667725, 2667745,
        2667755, 2667775, 2667795, 2667815, 2667835, 2667845,
        2667855, 2667865, 2667865, 2667855, 6479005, 6478995,
        6479005, 6479015, 6479015, 6479025, 6479025, 6479025,
        6479035, 6479035, 6479035, 6479035, 6479055, 6479065,
        6479085, 6479095, 6479115, 6479125, 6479145, 6479165,
        6479185, 6479205, 6479215, 6479225, 6479235, 6479245,
        6479255, 6479265, 6479275, 6479285, 6479295, 6479315,
        6479335, 6479345, 6479365), .Dim = c(35L, 2L), .Dimnames = list(
            NULL, c("x", "y"))))), ID = "11"), new("Lines", Lines = list(
            new("Line", coords = structure(c(2667675, 2667655,
            2667655, 2667665, 2667655, 2667675, 2667665, 2667655,
            2667675, 2667665, 2667655, 2667645, 2667635, 2667645,
            2667655, 2667675, 2667685, 2667705, 2667725, 2667745,
            2667755, 2667775, 2667775, 2667785, 2667785, 2667795,
            2667805, 2667815, 2667815, 2667825, 2667835, 2667845,
            2667865, 2667885, 2667895, 2667915, 2667925, 2667935,
            6479005, 6478995, 6479005, 6479015, 6479015, 6479025,
            6479025, 6479025, 6479035, 6479035, 6479035, 6479035,
            6479055, 6479065, 6479075, 6479085, 6479105, 6479115,
            6479125, 6479135, 6479135, 6479145, 6479135, 6479135,
            6479145, 6479125, 6479105, 6479085, 6479075, 6479055,
            6479035, 6479025, 6479015, 6479005, 6478995, 6478985,
            6478975, 6478955), .Dim = c(38L, 2L), .Dimnames = list(
                NULL, c("x", "y"))))), ID = "21")), bbox = structure(c(2667635,
    6478955, 2667935, 6479365), .Dim = c(2L, 2L), .Dimnames = list(
        c("x", "y"), c("min", "max"))), proj4string = new("CRS",
        projargs = "+proj=nzmg +lat_0=-41 +lon_0=173 +x_0=2510000 +y_0=6023150 +ellps=intl +units=m +no_defs"))

Goal
As you can see, to each line is attached a nominal attribute, which is stored under funct:
> mydata$funct
[1] "t"   "t"   "wcs" "wcs"

When plotting those 4 lines, I cannot find a viable way of assigning a different line type (using the lty option in r base plotting) according to the nominal variable (e.g., a continuous line for the lines associated to 't', a dashed line to the two associated to 'wcs'). I have made some web search but I could not find anything that can be used in this specific situation.

A: The line type in R plots is a numeric value, so you need to convert your character column to numbers.
You can do this most easily using factor:
> mydata$functN = as.numeric(as.factor(mydata$funct))
> as.data.frame(mydata)
     length funct functN
1  500.8422     t      1
2  293.6068     t      1
11 612.0664   wcs      2
21 629.7057   wcs      2

those numbers are valid line types, so you can then do:
 plot(mydata, lty=mydata$functN)

If you want the solid and dashed lines the other way round then subtract it from 3:
plot(mydata, lty=3-mydata$functN)

which will transform 2 to 1 and 1 to 2.


text:
Q: I dont understand how this code sort this python list(), and how to reproduce it in C++ with a vector I have a C++ vector that i need to sort like this python list:
sorted(self.weirdest, key=lambda tup: (tup[0], tup[-1]))
self.weirdest.sort(key=lambda elem: abs(elem[1]))
self.weirdest.reverse()

But i dont understand what is it doing, can someone explain to me please, thanks.
ps: it's a list of weirdest temperatures values if it can help.

A: First line doesn't do anything. It returns a sorted list which is discarded.
Second line sorts the list by the absolute value of the second element in each entry.
Last line reverses the list.
In C++ something like this would work:
std::sort(weirdest.begin(), weirdest.end(),
          [](const auto& a, const auto& b) {
             return abs(a[1]) < abs(b[1]);
          });

std::reverse(weirdest.begin(), weirdest.end());


text:
Q: did I do something wrong? or I found a bug? this is to prove that there might be a bug in setintersection() or keys() in terraform v1.2.1
that it treats local and var differently.
I hope someone can help to confirm, or point out if I did something wrong?
# this file is to prove that there might be a bug in setintersection() or keys() in terraform v1.2.1
# that it treats local and var differently.
# I hope someone can help to confirm, or point out if I did something wrong?

# local.regions is to serve as the setintersection control set of strings
# as the keys(s_v) has non-region-related keys
locals                    {
  regions               = ["region-1", "region-2"]
}

# local.local_obj has the exact same data structure as of var.var_obj
locals                    {
  local_obj             = {
    collection_local    = {
      subnet_local      = {
        other_keys      = "somthing"
        region-1        = "cidr-for-region-1-for-local-obj"
        # region-2        = "cidr-for-region-2-for-local-obj"
      }
    }
  }
}

# var.var_obj is a map(map(object())) data structure, outter map is the collection of subnets,
# inner map is the subnets within a collection, object is the subnet config
variable "var_obj"        {
  type                  = map(
    map                   (
      object              ({
        other_keys      = "whatever"
        region-1        = optional(string)
        region-2        = optional(string)
      })
    )
  )
  default               = {
    collection_var      = {
      subnet_var        = {
        other_keys      = "something_else"
        region-1        = "cidr-for-region-1-for-var-obj"
        # region-2        = "cidr-for-region-2-for-var-obj"
      }
    }
  }
}

# local.transform-local and local.transform-var are two transforming locals to suite subnet resource needs
locals                    {
  transform-local       = flatten([
    for c_k,c_v        in local.local_obj : [
      for s_k, s_v     in c_v : [
        for rg         in setintersection(local.regions, keys(s_v)) : {
          name          = "${rg}-${s_k}"
          region        = rg
          ip_cidr_range = s_v[rg]
        }
      ]
    ]
  ])

  transform-var         = flatten([
    for c_k,c_v        in var.var_obj : [
      for s_k, s_v     in c_v : [
        for rg         in setintersection(local.regions, keys(s_v)) : {
          name          = "${rg}-${s_k}"
          region        = rg
          ip_cidr_range = s_v[rg]
        }
      ]
    ]
  ])
}

# output.contrast is to show the different behavior of setintersection() and keys() on local and var
# I think it is a bug?
# as commenting out the region-2 in local and var has different behavior,
# local behaves corretly, not producing region-2 record at all,
# but var transformer produced a region-2 record without ip_cidr_range, which will break the resource code execution
output "contrast"         {
  value                 = {
    transform-local     = local.transform-local
    transform-var       = local.transform-var
  }
}

if uncommenting the region-2 line, setintersection() and keys() behave exactly the same on local and var:
output:
contrast            : {
  transform-local   : [
    {
      name          : "region-1-subnet_local"
      ip_cidr_range : "cidr-for-region-1-for-local-obj"
      region        : "region-1"
    }
    {
      name          : "region-2-subnet_local"
      ip_cidr_range : "cidr-for-region-2-for-local-obj"
      region        : "region-2"
    }
  ]

  transform-var     : [
    {
      name          : "region-1-subnet_var"
      ip_cidr_range : "cidr-for-region-1-for-var-obj"
      region        : "region-1"
    }
    {
      name          : "region-2-subnet_var"
      ip_cidr_range : "cidr-for-region-2-for-var-obj"
      region        : "region-2"
    }
  ]
}

but if I comment out the region-2 line (as shown in code above), transform-var output is not desirable as it produces something that will cause malfunctioning
output:
contrast            : {
  transform-local   : [
    {
      name          : "region-1-subnet_local"
      ip_cidr_range : "cidr-for-region-1-for-local-obj"
      region        : "region-1"
    }
  ]

  transform-var     : [
    {
      name          : "region-1-subnet_var"
      ip_cidr_range : "cidr-for-region-1-for-var-obj"
      region        : "region-1"
    }
    {
      name          : "region-2-subnet_var"
      region        : "region-2"
    }
  ]
}


text:
Q: .NET Core build with dll reference I am trying to get .NET core to work with the build system at my work, which had been designed with Java in mind. But it is sadly so integrated into our pipelines that there is no way we can be without it. So if I want to use .NET at work will it have to be with this build system.
Each project is built into a package, with their own git repository.
Given a program like below where MyConsoleApp has a dependency on MyLibrary.
MyProgram-Solution
 - MyConsoleApp
 - MyLibrary

At build time the source code would be placed in
/build/packages/MyConsoleApp/
/build/packages/MyLibrary/

However I can only build one at the time, and I cannot move the source code.
Which means that I would need to build MyLibrary first, with the DLL ending up in
/build/packages/MyLibrary/out/MyLibrary.1.0.dll

When I then build MyConsoleApp, I need a way to tell the .NET Core build tool that the MyLibrary.1.0.dll file can be found at
/build/packages/MyLibrary/out/MyLibrary.1.0.dll

Storing packages in Nuget is not an option, as the package may not be ready for release at the build time, and the build system works in a sandbox mode, meaning it has no external connections.
I can edit the MyConsoleApp.csproj if that makes it possible.

A: You can add assembly references using Visual Studio, same as with .NET Framework projects.
If you want to modify the project file by hand, you'll need something like the following:
<ItemGroup>
  <Reference Include="MyLibrary">
    <HintPath>..\..\..\MyLibrary\out\MyLibrary.1.0.dll</HintPath>
  </Reference>
</ItemGroup>


text:
Q: Модальные окна Здравствуйте!
Я хотел спросить, можно ли как-то убрать с модального окна кнопку закрытия (крестик в углу), то есть чтобы оно закрывалось нажатием какого-то баттона. Сам я пользуюсь плагином на jQuery - fancyBox, но в параметрах я такой функции не находил.
Если кто знает, как это реализовать помогите. Заранее спасибо!
A: Открываете firebug и кликаете по кнопке, берете и смотрите ее класс или id. Кнопка имеет id fancybox-close (посмотрел на демостраничке). И пишете через цсс ей visibility:hidden (для скрытия элементов можно использовать display:none, но с fancybox это не сработает, т.к. скрипт навешивает закрывающему элементу display:inline на атрибут style).
A: Fancybox API
$("#link").fancybox({"showCloseButton": false});

Данное действие скроет кнопку закрытия окна.

A: Как вариант - скрыть после генерации окна :)


text:
Q: java, json, align the start date and end date in each object I want to compare the dates for each objects in the price object and make sure that the dates are not overlapping nor have gaps in between. In the following json, the dates are correct. When you read the first object, the last object, and the second object, you will see that the dates are aligned. Is there an algorithm that can help be accomplish this?
  "prices": [
        {
            "effectiveFrom": "",
            "effectiveUntil": "2015-12-01T05:00:00.00Z",
            "priceAmount": 11,
        },
        {
            "effectiveFrom": "2016-01-01T05:00:00.00Z",
            "effectiveUntil": "",
            "priceAmount": 11,
        },
        {
            "effectiveFrom": "2015-12-01T05:00:00.00Z",
            "effectiveUntil": "2016-01-01T05:00:00.00Z",
            "priceAmount": 5,
        }

Right now, I am checking index by index but this is not ideal because I can have more then 3 objects and then the logic will be messed up...
        if (i==0)
        {
            if (!endDate.equals(promoStartDate)) correctDates = false;
        }
        //after promotion ends
        if (i==1)
        {
            if (!startDate.equals(promoEndDate)) correctDates = false;
        }
        //during promotion period
        if (i==2)
        {
            if (!startDate.equals(promoStartDate) && !endDate.equals(promoEndDate)) correctDates = false;

        }

A: You just need to sort all objects by startdate and then iterate throw them and check if enddate of one object equals startdate of the next.
In pseudo code:
prices = sort(...);
for (i = 0; i < prices.size()-1; i++) {
    if (prices[i].enddate != prices[i+1].startdate) return false;
}
return true;


text:
Q: SQL- Join Same Table with Filters I have a single table (Tracker) containing 2 columns; (ID and Status). I would like to retrieve a list of ID's without the status approved, however a status can go from pending to approve and the original data will not be removed. See below example and desired outcome.
Tracker Table:

ID
Status

123
Pending

123
Approved

456
Pending

678
Denied

894
Approved

Desired Outcome:

ID
Status

456
Pending

678
Denied

123 is not present due to the second status being 'Approved' and 894 is not present because the only status in 'Approved'
Was thinking along the line of something like below:
Select ID
FROM Tracker b
WHERE Status = 'Approved'

Right Join

Select ID
FROM Tracker a

USING ID

A: You can use aggregation:
select t.id
from tracker t
group by t.id
having sum(case when t.status = 'Approved' then 1 else 0 end) = 0;

A: SELECT T.ID,T.STATUS
FROM YOUR_TABLE AS T
WHERE NOT EXISTS
(
   SELECT 1 FROM YOUR_TABLE AS T2 WHERE T.ID=T2.ID AND T2.STATUS='APPROVED'
 )

A: Try this SQL.
SELECT t.id
       ,t.status
FROM tracker t
GROUP BY id
HAVING sum(
    CASE t.status
        WHEN 'Approved' THEN 1
        ELSE 0
    END
) = 0
;


text:
Q: How to determine tcp client is connect or not in c++ I save all IP of clients/sockets that are connected and after that I want to know when I write something from server to client, whether a client in CONNECT status or not. When I use Write function, it is possible to send data from server to clients discarded because one or more clients may disconnect, connection will be closed and data don't send. My code is:
void *connection_determine(void *ptr){

  while (1) {

    putchar(x[0]);

    std::list<int>::iterator it;

    it=list_client_sockets.begin();

    while (it!=list_client_sockets.end()){
        printf("%d\t",*it);
        if (read(*it, x, 1) < 1) {
            cout<<"yes"<<endl;
            perror("Error on write to client socket!\r\n");
            fflush(stdout);
            fflush(stderr);

            close(*it);
            it=list_client_sockets.erase(it);
            --it;
            //return 0;
       }
      it++;

    }
    //printf("0x%02X ",x);
    fflush(stdout);

   }
 }

 // function for read data from pipe and send it to clients
void *pipeRead_thread_func(void *ptr) {
  int fd_pipe = *((int *) ptr);
  while (1) {
    char x[1];
    if (read(fd_pipe, x, 1) < 0) {
        perror("Read Error");
        return 0;
    }
    putchar(x[0]);

    std::list<int>::iterator it;

    it=list_client_sockets.begin();

    while (it!=list_client_sockets.end()){
        printf("%d\t",*it);

        if (send(*it, x, 1,0) < 0) {
            cout<<"yes"<<endl;
            perror("Error on write to client socket!\r\n");
            fflush(stdout);
            fflush(stderr);

            close(*it);
            it=list_client_sockets.erase(it);
            --it;
            //return 0;
       }

      it++;

   }
    //printf("0x%02X ",x);
    fflush(stdout);

  }
}

A: The usual way a client decides if a connection is to be closed is check if it has timed-out, if it hasn't received any messages for a specified time it closes the socket.
You detect if a socket is open by trying to read from it, if it fails the socket is closed.  You can use Keep Alive messages to keep the socket open.
You can use separate threads for socket status detection and/or keeping the socket alive.


text:
Q: How can you create two triangles next to an image? How can you create two triangles next to an image?
As you can see in the jsfiddle, the triangles are not tounching the image. I want them to touch the image and the blue bar above.
I tried this post: How can I have an image float next to a centered div? didn't work.

.content {
 width: 960px;
 margin: 0 auto;
}

ul.producten {
 margin-top: 4%;
 list-style-type: none;
}

ul.producten li {
 width: 315px;
}

ul.producten li img {
 display: inline-block;
 width: 295px;
}

.producten_top {
 width: 315px;
 height: 40px;
 background: #3bcdff;
}

.producten_top h1 {
 font-size: 30px;
 color: #fff;
 text-align: center;
 padding: 5px 0;
}

.arrow_left {
 display: inline-block;
 width: 0;
 height: 0;
 border-left: 5px solid transparent;
 border-right: 5px solid transparent;
 border-top: 5px solid #1c1c1d;
 transform: rotate(225deg);
 float: left;
}

.arrow_right {
 display: inline-block;
 width: 0;
 height: 0;
 border-left: 5px solid transparent;
 border-right: 5px solid transparent;
 border-bottom: 5px solid #1c1c1d;
 transform: rotate(315deg);
 float: right;
}

Test

jsfiddle
what it needs to be:

A: Use position: absolute instead of display: inline-block and give 8px border for triangles instead of 5px and set display: block and margin: auto for make img center. of course you need to set position: relative; for parent (ul.producten li).

.content {
    width: 960px;
    margin: auto;
}

ul.producten {
    margin-top: 4%;
    list-style-type: none;
}

ul.producten li {
    width: 315px;
    position: relative;
}

ul.producten li img {
    display: block;
    width: 295px;
    margin: auto;
}

.producten_top {
    width: 315px;
    height: 40px;
    background: #3bcdff;
}

.producten_top h1 {
    font-size: 30px;
    color: #fff;
    text-align: center;
    padding: 5px 0;
}

.arrow_left {
    width: 0;
    height: 0;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    border-top: 8px solid #1c1c1d;
    transform: rotate(225deg);
    position: absolute;
    left: 0;
    top: 39px;
}

.arrow_right {
    width: 0;
    height: 0;
    border-left: 8px solid transparent;
    border-right: 8px solid transparent;
    border-bottom: 8px solid #1c1c1d;
    transform: rotate(315deg);
    position: absolute;
    right: 0;
    top: 39px;
}

Test

A: This technique makes a square div with a linear gradient alpha background that resembles a triangle.  As a bonus, by adjusting the distance between alpha=1 and alpha=0 (the percentages) in the gradients you can change the anti-aliasing of the diagonal line (the left arrow has more anti-aliasing in this example).

.content {
 width: 960px;
 margin: 0 auto;
}

ul.producten {
 margin-top: 4%;
 list-style-type: none;
}

ul.producten li {
    width: 315px;
    position: relative;
}

ul.producten li img {
    display: block;
    width: 295px;
    margin: auto;
}

.producten_top {
 width: 315px;
 height: 40px;
 background: #3bcdff;
}

.producten_top h1 {
 font-size: 30px;
 color: #fff;
 text-align: center;
 padding: 5px 0;
}

.arrow_left {
    width: 10px;
    height: 10px;
    background: linear-gradient(225deg, rgba(28,28,29,1) 44%,rgba(28,28,29,0) 56%);
    position: absolute;
    left: 0;
    top: 40px;
}

.arrow_right {
    width: 10px;
    height: 10px;
    background: linear-gradient(135deg, rgba(28,28,29,1) 48%,rgba(28,28,29,0) 50%);
    position: absolute;
    right: 0;
    top: 40px;
}

Test

A: I have modified your css. The changes I made are:

*

*Set the same width for the blue header and image

*Set position fixed for image and right arrow

*Set the arrows degrees values in negative

Check it out...


text:
Q: navigate to BottomSheetDialogFragment using jetpack navigation Im trying to use jetpack navigation to navigate from a Fragment to a BottomSheetDialogFragment but every time I try to navigate it just crash the app saying it cannot find the class name.
mobile_navigation.xml
<fragment
  android:id="@+id/home_dest"
  android:name="TestProject.Fragment.HomeFragment">
    <action
            android:id="@+id/action_home_to_bottom_sheet"
            app:destination="@id/bottom_dialog"
            app:enterAnim="@anim/slide_in_right"
            app:exitAnim="@anim/slide_out_left"
            app:popEnterAnim="@anim/slide_in_left"
            app:popExitAnim="@anim/slide_out_right" /></fragment>

<dialog
  android:id="@+id/bottom_dialog"
  android:name="TestProject.Dialog.BottomDialog" />

BottomDialog.cs
namespace TestProject.Dialog
{
    public class BottomDialog : BottomSheetDialogFragment
    {
        public override View? OnCreateView(LayoutInflater inflater, ViewGroup? container, Bundle? savedInstanceState)
        {
            base.OnCreateView(inflater, container, savedInstanceState);
            return inflater.Inflate(Resource.Layout.bottom_sheet_layout, container, false);
        }
    }
}

HomeFragment.cs button click navigation
private void OnButtonClick(object sender, EventArgs e)
{
    var nav = Navigation.FindNavController(Activity, Resource.Id.my_nav_host_fragment);
    nav.Navigate(Resource.Id.action_home_to_bottom_sheet);
}

Error
AndroidX.Fragment.App.Fragment+InstantiationException: Unable to instantiate fragment TestProject.Dialog.BottomDialog: make sure class name exists ---> Java.Lang.ClassNotFoundException: TestProject.Dialog.BottomDialog ---> Java.Lang.ClassNotFoundException: Didn't find class "TestProject.Dialog.BottomDialog" on path: DexPathList[[zip file "/data/app/~~aFH8kN7HhPmbIpV2HNo5Pw==/"package_name"-iUb68ulDoLpefgk2DFn_XQ==/base.apk"],nativeLibraryDirectories=[/data/app/~~aFH8kN7HhPmbIpV2HNo5Pw==/package_name-iUb68ulDoLpefgk2DFn_XQ==/lib/arm64, /data/app/~~aFH8kN7HhPmbIpV2HNo5Pw==/package_name-iUb68ulDoLpefgk2DFn_XQ==/base.apk!/lib/arm64-v8a, /system/lib64, /system_ext/lib64]] 12-21 23:38:50.355 E/AppCenterXamarinCrashes(21237):    --- End of inner exception stack trace --- 12-21 23:38:50.355 E/AppCenterXamarinCrashes(21237):    --- End of inner exception stack trace ---
With all of this, I get a crash saying it can't find the class named BottomDialog which is impossible because if I change on the mobile_navigation the tag from <dialog to <fragment it can indeed navigate but lose all the behavior that a bottom Sheet must have.
I dont know if im missing something or if it's just something regarding xamarin that does not work.
Does anyone knows what might be causing this and why? im out of ideas
Already tried to clean/rebuild, and reinstall nuggets, and still no good.

A: @doczic,
At first glance, I don't see anything wrong. The usual reason for the Java.Lang.ClassNotFoundException is a typo in your nav_graph - (I've had a heap of them) not matching the fully qualified fragment class name. I only use Fragments in my nav_graphs as I don't like the extra stuff, like animations and actions etc. I prefer to do animations via NavOptions, which allows you to have more than one sort of animation etc and allows a lot of flexibility. I found too many things I didn't like about graphs and so now I restrict it to just the fragments and then write extra code to Navigate.
I use BottomDialogs as HelperDialogs in many places in my production apps to explain not-so-obvious features and allow the user to optionally turn them off once they know the app.
I've got a bunch of tutorials on the NavigationComponent called NavigationGraph(x) where x equals a number, which demonstrates how I evolved from the standard stuff to do more stuff via code as the number increments.
It may not fix your particular problem, but it does demonstrate how to use a BottomSheetDialogFragment. NavigationGraph7 is the project where I first introduced BottomDialogs. There is also a Navigation7Net7 project but that is the same project converted to a Net7 project, whereas the NavigationGraph7 is xamarin.android classic.

A: @doczic
its something kinda simple and it does not work no matter what I do, hence why Im starting to believe it might be something related with Xamarin
I wouldn't get hung up on something like the dialog not working, as in the long run, I doubt you'll end up wanting that functionality in the nav_graph anyway. However, I doubt that particular problem has anything to do with Xamarin.
Google had a very good idea when it came up with the NavigationComponent, but maybe they took the nav_graph concept just a little too far. The major idea was to get away from multiple activities and fragment transactions.  Fragment transactions being the most difficult thing to work with. Step back a bit and think of the overall structure of any Android app and consider the 3 important layouts that every android app is likely to use. activity_main, app_bar_main and content_main. The most important one is content_main. It contains the FragmentContainerView which holds the NavHostFragment. Every single fragment in your app fits in that FragmentContainerView, no matter how big your app grows. That enabled them not so much to do away with FragmentTransactions, but to hide the complexity of fragment transactions. You won't find a single fragment transaction in any of those NavigationGraph projects.
The nav_graph should in my opinion just hold the fragments in other words a placeholder. You can even use it as a prototype tool – have a list of fragments that don't even exist in code yet. That has no ill effect on building a project. So, if say you are converting an old project you can spec it out in the nav_graph of the new project. Where they went off the rails a touch was including stuff like bundles, animations, actions and info about how the back stack should pop etc in the nav_graph. Someone on their team must have also come up with NavOptions class because it is that class that gives us developers the ability to manually do what we want to do without having to pollute the nav_graph with all that extra stuff.
If you check out the NavigationGraph projects, you will see that I started off doing it their way (there is even a Xamarin converted NavigationCodeLab in there) and then as the projects increment I swapped away from their approach. I really doubt you are going to miss one particular dialog in a nav_graph when you can use something like the BasicDialogFragment which inherits from AppCompatDialogFragment allowing flexibility anywhere.
I've successfully converted two of my production apps and can say that they are far better and more reliable than the originals.
Just a note – some of the NavigationGraph projects have already been converted to Net7 projects, so you may want to concentrate on the ones without the net7 suffix to start with.
There are also problems with AndroidX.Navigation.Fragment and Navigation.Ui, that relate to their dependencies that become apparent as you increment both that need to be sorted out at Xamarin.Android. So don't automatically update those packages to the latest versions, use the versions noted in each project. Later projects may use updated versions though when stuff got fixed. However, nothing really that can't be worked around.
Forgot to mention where they are https://github.com/gmck


text:
Q: How to Correctly Bind wx.MenuItems not stored in a variable Premise:
I'm creating a little wx.Frame were i have a wx.SubMenu with a variable number of wx.MenuItems, and i want to bind they to a method, so i used this code:
self.selectworkout = wx.Menu()
self.x = 110
y = []
for elem in self.workout_list:
    y.append(self.selectworkout.Append(int(self.x), elem.title, elem.title + " | " + elem.description))
    index = self.workout_list.index(elem)
    self.Bind(wx.EVT_MENU, lambda event: self.OnSelectWorkout(event, elem), y[index])
    self.x+=1

to have a pointer to the wx.MenuItems, i stored them in a list and then i bind they using the corrispondent list item
Issue:
The problem is that when i click them, the call the method but they pass the same parameters, like if i have been bindin the same wx.MenuItem
Question:
Do you know where th problem is or what is the optimal way to do what i need?

A: The problem with
self.Bind(wx.EVT_MENU, lambda event: self.OnSelectWorkout(event, elem), y[index])

is that the elem in the lambda expression is actually the variable from the surrounding function. If it is changed by the for-loop it is changed for all created lambdas.
Simple solution: Change it to:
self.Bind(wx.EVT_MENU, lambda event, elem=elem: self.OnSelectWorkout(event, elem), y[index])


text:
Q: reusing android code (native Java) in a frame inside web app or desktop app as per this answer it is possible to reuse android java code inside web app or desktop app frame.
so how its done step by step?
I wonder if there is a special tool to do so.

A: I don't think there is a complete tutorial, as it's tedious work. The example you linked shows
Android -> Swing conversion. So I will illustrate this with some examples:

*

*If you have a View in your android app, you replace it with JPanel for swing.

*If you have a Button, you replace it with JButton

*Sometimes elements may look similar, but they do different things, like CardView and CardPane. This complicates things.

*There might be android Views that has no matching pair in swing, so you will have to improvise there

But it's not this simple of course. Setting the properties of the views is going to be completely different. Moreover, Android uses XML, while in Swing you have to set everything programmatically.
The only thing common is basically they are both built on Java. So my best advice is that you shouldn't try to "convert" your code. Maybe you can reuse some pure Java parts, but other than that, I suggest you re write the application using the other platforms tools.

A: you can't use android code in web app or desktop,
first you have to separate the business code from the ui code
the business code can be in a pure java module (completely reusable)
when i speak about business code i mean network calls (using retrofit for example) and any code that is pure java ..
the ui and android specific code (like Views ...) should be rewritten entirely because will not have access to android packages containing views (recycler, layouts...)


text:
Q: File paths right by me and phpStorm but wrong in real world phpStorm and I agreee this is crazy but "wrong" file paths work while "right" ones fail. Basic structure.
  |
  |------classes(directory)
  |         |
  |         |
  |         Person.php
  |
  |------include(directory)
  |         |
  |         |
  |         db-connect.inc.php
  |         autoloader.inc.php
  |         helper.inc.php
  |
  |
  |index.php
  |etc.php

In index I use: (1)
include_once "include/autoloader.inc.php";
include_once "include/db-connect.inc.php";
include_once "include/helper.inc.php";

and in Person.php I would expect to use: (2)
include_once "../include/autoloader.inc.php";
include_once "../include/db-connect.inc.php";
include_once "../include/helper.inc.php";

But that gets is:
"Warning: include_once(../include/autoloader.inc.php): failed to open stream:
No such file or directory in C:\xampp\htdocs\dummy\classes\Person.php on line 2"

Bizarely (3)
include_once "/../include/autoloader.inc.php";
include_once "/../include/db-connect.inc.php";
include_once "/../include/helper.inc.php";

works and even more bizarely so does (4)
include_once "include/autoloader.inc.php";
include_once "include/db-connect.inc.php";
include_once "include/helper.inc.php";

even though we are up one directory level!
phpStorm flags 3 and 4 as errors (says "Path include/autoloader.inc.php not found" and "Include expression is not resolved") while (2), which is what I thought was "right", gets a nice big green tick but fails at debug or if directly accessed via http://localhost etc.
I always struggle with these path things but how come phpStorm and I agree and the real world say nope!
Guess I will have to put $_SERVER['DOCUMENT_ROOT'] in all over the place (lot easier with Storm instead of longhand!) but still a pain!

A: This is correct behaviour.
The page you loaded is in /
There you included a file from /includes
And now the file you have included is part of the page in /
So all includes in the included file are seen as relatives from / not from /includes
and so on...