Insert method with GenericRepository

Question: I try to insert an object with a genericrepository:
I have this:
GenericRepository:
public class GenericRepository<TEntity> where TEntity : class
    {
        internal LolaBikeContext context;
        internal DbSet<TEntity> dbSet;

        public GenericRepository(LolaBikeContext context)
        {
            this.context = context;
            this.dbSet = context.Set<TEntity>();
        }

        public virtual IEnumerable<TEntity> GetWithRawSql(string query, params object[] parameters)
        {
            return dbSet.SqlQuery(query, parameters).ToList();
        }

        public virtual IEnumerable<TEntity> Get(
            Expression<Func<TEntity, bool>> filter = null,
            Func<IQueryable<TEntity>, IOrderedQueryable<TEntity>> orderBy = null,
            string includeProperties = "")
        {
            IQueryable<TEntity> query = dbSet;

            if (filter != null)
            {
                query = query.Where(filter);
            }

            foreach (var includeProperty in includeProperties.Split
                (new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(includeProperty);
            }

            if (orderBy != null)
            {
                return orderBy(query).ToList();
            }
            else
            {
                return query.ToList();
            }
        }

        public virtual TEntity GetByID(object id)
        {
            return dbSet.Find(id);
        }

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

        public virtual void Delete(object id)
        {
            TEntity entityToDelete = dbSet.Find(id);
            Delete(entityToDelete);
        }

        public virtual void Delete(TEntity entityToDelete)
        {
            if (context.Entry(entityToDelete).State == EntityState.Detached)
            {
                dbSet.Attach(entityToDelete);
            }
            dbSet.Remove(entityToDelete);
        }

        public virtual void Update(TEntity entityToUpdate)
        {
            dbSet.Attach(entityToUpdate);
            context.Entry(entityToUpdate).State = EntityState.Modified;
        }
    }

UnitOFwork:
public class UnitOfWork : IDisposable
    {
        private LolaBikeContext context = new LolaBikeContext ();
        private GenericRepository<UserProfile> userRepository;
        private GenericRepository<Route> routeRepository;
        private GenericRepository<Climb> climbRepository;
        private GenericRepository<Country> countryRepository;
        private GenericRepository<Difficult> difficultRepository;
        private GenericRepository<ClimbViewModel> climbViewModelRepository;

        public GenericRepository<UserProfile> UserRepository
        {

            get
            {

                if (this.userRepository == null)
                {
                    this.userRepository = new GenericRepository<UserProfile>(context);
                }
                return userRepository;
            }
        }

        public GenericRepository<Route> RouteRepository
        {
            get
            {
                if (this.routeRepository == null)
                {
                    this.routeRepository = new GenericRepository<Route>(context);
                }
                return routeRepository;
            }
        }

        public GenericRepository<Climb>ClimbRepository
        {
            get
            {

                if (this.climbRepository == null)
                {
                    this.climbRepository = new GenericRepository<Climb>(context);
                }
                return this.climbRepository;
            }

        }

        public GenericRepository<ClimbViewModel> ClimbViewModelRepository
        {
            get
            {
                if (climbViewModelRepository == null)
                {
                    this.climbViewModelRepository = new GenericRepository<ClimbViewModel>(context);
                }
                return this.climbViewModelRepository;

            }
        }

        public GenericRepository<Country>CountryRepository
        {

            get
            {

                if (this.countryRepository != null)
                {
                    countryRepository = new GenericRepository<Country>(context);
                }
                return this.countryRepository;
            }
        }

        public GenericRepository<Difficult>DifficultRepository
        {

            get
            {

                if (difficultRepository != null)
                {
                    difficultRepository = new GenericRepository<Difficult>(context);
                }
              return  this.difficultRepository;
            }

        }

        public void Save()
        {
            context.SaveChanges();
        }

        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    context.Dispose();
                }
            }
            this.disposed = true;
        }

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

CLass Climb:
public class Climb
    {

        [Key]
        public int climbID { get; set; }
        public string Name { get; set; }
        public int Points { get; set; }

        public int? UserProfileID { get; set; }
        public int? CountryId { get; set; }
        public int? DifficultId { get; set; }

        public virtual UserProfile userProfile { get; set; }
        public virtual Country country { get; set; }
        public virtual Difficult difficult { get; set; }

    }

the Insert method:
public ActionResult Create()
    {
    var queryCountry = unitOfWork.ClimbRepository.Get(
        orderBy: q => q.OrderBy(c => c.country.country_name));
    var queryDifficult = unitOfWork.ClimbRepository.Get(
        orderBy: qd => qd.OrderBy(d => d.difficult.DifficultName));

    ViewBag.CountryId = new SelectList(queryCountry, "CountryId", "country_name");
    ViewBag.DifficultId = new SelectList(queryDifficult, "DifficultId", "DifficultName");
    return View();
}

But then I will get this error in the Razor Create method:
An exception of type 'System.Web.HttpException' occurred in System.Web.dll but was not handled in user code

Additional information: DataBinding: 'System.Data.Entity.DynamicProxies.Climb_0568B2C1C64C1C347E3DF33E87F37C8D672D9794887F77C523EB7B16E9399FCE' does not contain a property with the name 'country_name'.

on this line:

            Country
            @Html.DropDownList("CountryId", ViewBag.countries as SelectList, new { @class = "form-control", style = "width: 250px;" })

Thank you
If I try it like this:
    var queryCountry = unitOfWork.CountryRepository.Get(
        orderBy: q => q.OrderBy(c => c.country_name));
    var queryDifficult = unitOfWork.ClimbRepository.Get(
        orderBy: qd => qd.OrderBy(d => d.difficult.DifficultName));

    ViewBag.CountryId = new SelectList(queryCountry, "CountryId", "country.country_name");
    ViewBag.DifficultId = new SelectList(queryDifficult, "DifficultId", "difficult.DifficultName");
    return View();

I get a null refenect exception
Comment: Somebody some ideer? Thank you
Comment: ?? can nobody give me some advise??
Answer: The error is telling you what's wrong. queryCountry doesn't contain a "country_name". "country_name" is a property of country, not Climb. Try
ViewBag.CountryId = new SelectList(queryCountry, "CountryId", "country.country_name");

You'll have the same problem with the next line of code as well, should be
ViewBag.DifficultId = new SelectList(queryDifficult, "DifficultId", "difficult.DifficultName");

Include country in your Get() call:
var queryCountry = unitOfWork.ClimbRepository.Get(
    orderBy: q => q.OrderBy(c => c.country.country_name),
    includeProperties: "country");

Comment: But the problem is then, I get the countries of the already insert climbs back and not the list of countries
Comment: I think you need to pass country as the include parameter in your Get call. My Guess is, if you set a breakpoint on ViewBag.CountryId line, you'll see that query.country is null. Personally I would change your includes to an Expression>, or better yet, IEnumerable>>, see edit for how I've implemented mine (thanks https://genericunitofworkandrepositories.codeplex.com/)
Comment: Thank you. But where is your edit? And I think you mean the Get method?
Comment: Yes, I mean Get. You will need to include 'countries'. Forget the edit. probably easier to just look at the link I added in the comment above as I'll probably miss something. Look at the Repository.Pattern.Ef6.QueryFluent and Repository.Pattern.Ef6.Repository classes in the source when you download the package as I was only going to post a cut down version of these classes

Insert method with GenericRepository


Where can I find difficult trigonometric formulas?

Question: I understand simple trigonometric formulas like $ \sin^2 \alpha + \cos^2 \alpha = 1.$ I've found ones in books but I've not found more difficult like
$$ \sin^2 \frac{\alpha}{2} = \frac{1 - \cos \alpha}{2} $$ or inverse trigonometric functions. Is there anywhere it?
Comment: https://en.wikipedia.org/wiki/List_of_trigonometric_identities has a lot. If you want a more extensive list, I don't know.
Comment: there are only statement/identities but i seek parsing something like $$ \sin^2 \alpha + \cos^2 \alpha = 1 => b^2 + a^2 = c^2 => \frac{b^2}{c^2} + \frac{a^2}{c^2} = 1 $$
Answer: Once you get past the introductory right angle approach to trigonometry, and identities such as Pythagorean and  complimentary angle identities, you should start seeing that "trig" triangles and arbitrary $(a,b,c)$ triangles as all similar.

After some practice, we only consider the "trig" triangles when doing proofs.
Later on, we take the unit circle approach, so that we can analyse and prove identities for angles larger than a quarter revolution, as well as negative angles.
To actually look up proofs, it may be productive to learn their names (e.g. Pythagorean identity, double angle formula, sum of angles formula, half angle formula, etc.), then just Google it.


How to extract p-values from BigQuery linear regression

Question: I am running a simple linear regression model in Google BigQuery, but when evaluating the model output I cannot seem to find/extract p-values or other information normally outputted from a linear regression model (e.g., confidence intervals). Can anyone advise how to achieve this? I find the output somewhat confusing.
Answer: Unfortunately computing p-values, t-values, etc for BigQuery ML models is not currently supported.
Comment: If possible, could you please provide some documentation to support this?
Comment: You can probably try to import the model into python and calculate it there.


make a hierarchical structure for instances of a model in laravel

Question: In the User model I added a column named supervisor that can hold another user_id for each user.
In fact each User can have a supervisor user that specified by that column.
For that I added a hierarchical method like this :
    protected function hierarchical($users)
    {
        $users = $users->toArray();

        $nestedKeys = array();

        foreach ($users as $key => $node) {
            $supervisor_id = $node['supervisor']['user_id'];
            $index         = array_search($supervisor_id, array_column($users, 'user_id'));

            if (!is_null($supervisor_id) && $index != -1) {

                $users[$index]['children'][] = $node;

                $nestedKeys[] = $node['user_id'];
            }
        }

        return $users;
    }

That method accepts a $users that is a collection comes from User::all() for example, that created a response like this But the result is not what I want:
[
    {
        "user_id": 1,
        "supervisor": null,
        "name": "ahmad",
        "family": "badpey",
        "full_name": "ahmad badpey",
        "children": [
            {
                "user_id": 7,
                "supervisor": {
                    "user_id": 1,
                    "name": "ahmad",
                    "family": "badpey",
                    "full_name": "ahmad badpey"
                },
                "name": "ali",
                "family": "nasiri arani",
                "full_name": "ali nasiri arani"
            },
            {
                "user_id": 8,
                "supervisor": {
                    "user_id": 1,
                    "name": "ahmad",
                    "family": "badpey",
                    "full_name": "ahmad badpey"
                },
                "name": "مصطفی",
                "family": "زاهدی",
                "full_name": "مصطفی زاهدی"
            }
        ]
    },
    {
        "user_id": 7,
        "supervisor": {
            "user_id": 1,
            "name": "ahmad",
            "family": "badpey",
            "full_name": "ahmad badpey"
        },
        "name": "ali",
        "family": "nasiri arani",
        "full_name": "ali nasiri arani"
    },
    {
        "user_id": 8,
        "supervisor": {
            "user_id": 1,
            "name": "ahmad",
            "family": "badpey",
            "full_name": "ahmad badpey"
        },
        "name": "مصطفی",
        "family": "زاهدی",
        "full_name": "مصطفی زاهدی",
        "children": [
            {
                "user_id": 9,
                "supervisor": {
                    "user_id": 8,
                    "name": "مصطفی",
                    "family": "زاهدی",
                    "full_name": "مصطفی زاهدی"
                },
                "name": "حسین",
                "family": "قناتی",
                "full_name": "حسین قناتی"
            }
        ]
    },
    {
        "user_id": 9,
        "supervisor": {
            "user_id": 8,
            "name": "مصطفی",
            "family": "زاهدی",
            "full_name": "مصطفی زاهدی"
        },
        "name": "حسین",
        "family": "قناتی",
        "full_name": "حسین قناتی"
    }
]

As you can see created structure is not correct because subordinate users comes Separate again.
What is the best approch to create what I want for model with similar structure?
Comment: so basically are you looking for a query whereIn you can get a supervisor for any employee and all employees for a supervisor?
Comment: yes, but not only for a specific user. may a user has some employees that each or them have their own
Comment: so you always  want a supervisor of a user  ? either he's a user or a supervisor right ?
Answer: This is something which I tried in ruby on Rails but not laravel but I think it should work here also.. basically you need a self join..so in the User model you can have 2 relationships..
public function supervisor(){
   App/User::belongsTo(App/User::class, 'supervisor_id')
}
public function reportees(){
   App/User::hasMany(App/User::class)
}
Please correct any syntax errors and try this and see if that does what you are looking for
Comment: in this case if I want to get reportees of a supervisor should call $user->with('reportees') that returns only level 1 of those and if to get other nested reportees must call something like $user->with('reportees.reportees'). I thinks your solution is not appropriate for nested hierarchical.
Answer: This type of relationship is a Tree Structure or Nested Set, with the user's represented as nodes and leaves. At the top is the boss man, or the root node, and everyone else branching out below him.
Here is a package I'd suggest you consider: eloquent-tree
You can traverse a tree in both directions from any node using:
$collection = $node->findAncestors()->get();

$collection = $node->findDescendants()->get();

Fetching all relationships is simply:
Tree::getLeaves();

And the outcome of generating a tree:
 Tree::mapArray(
    array(
        array(
            'children' => array(
                array(
                    'children' => array(
                        array(
                            'children' => array(
                                array(
                                    'children' => array()
                                ),
                                array(
                                    'children' => array()
                                )
                            )
                        ),
                        array(
                            'children' => array()
                        )
                    )
                ),
                array(
                    'children' => array()
                )
            )
        ),
        array(
            'children' => array()
        ),
        array(
            'children' => array()
        )
     )
 );

Another popular solution can be found here: laravel-nestedset


Using both Drupal Core Contact Form and contributed Webform module

Question: I have a Drupal 8 site already utilizing core Contact Form. However, we now need a more complex form and thinking about installing a contributed module: Webform (https://www.drupal.org/project/webform).
My concern is that having both Contact form and Webform enabled, will there be an issue like one impacting the other?
Thanks.
Answer: It is fine to use both. If you are not using the Contact Storage module, it should be very easy to convert your contact forms to webforms.
Comment: Thank you @jrockowtz.


Showing a model is logistic

Question: If we suppose that the true relationship between the probability of disease ($D=1$) and the level of risk factor $X$ is given by the logistic model
$$P(D=1|X=x) = \frac{e^{\alpha + \beta x}}{1 + e^{\alpha + \beta x}}.$$
If we introduce a new random variable $Z$, where $Z$ is $0$ or $1$. Further, if $P(Z=1|D=0,x)=\pi_0$, and $P(Z=1|D=1,x)=\pi_1$, and $\pi_0$ and $\pi_1$ are independent of $x$. How can I show that the model for $P(D=1|Z=1,x)$ is still logistic?
I've tried using the fact that
$$P(Z=1|D=1,x) = \frac{P(Z=1,D=1|X=x)}{P(D=1|X=x)}=\pi_1$$
which implies that
$$P(Z=1,D=1|X=x) = \pi_1\frac{e^{\alpha + \beta x}}{1 + e^{\alpha + \beta x}}$$
but this seems to lead me nowhere. I'm not sure if I am missing something or have made a mistake somewhere, but any pointers on how to get started would be greatly appreciated. Thanks.
Comment: Are $\pi_0$ and $\pi_1$ known constants?
Comment: No, they are unknown, but I don't think that should matter.
Answer: \begin{aligned}
P(Z=1|X=x) &= P(Z=1|D=1,X=x)P(D=1|X=x)\\
&\quad+ P(Z=1|D=0,X=x)P(D=0|X=x)\\
&= \pi_1\dfrac{e^{\alpha + \beta x}}{1+e^{\alpha + \beta x}}+\pi_0 \dfrac{1}{1+e^{\alpha + \beta x}}
\end{aligned}
Combine this with your final result to see that
\begin{aligned}
P(D=1|Z=1,X=x) &= P(Z=1,D=1|X=x) / P(Z=1|X=x)\\
&= \pi_1\dfrac{e^{\alpha + \beta x}}{1+e^{\alpha + \beta x}} / \left(\pi_1\dfrac{e^{\alpha + \beta x}}{1+e^{\alpha + \beta x}}+\pi_0 \dfrac{1}{1+e^{\alpha + \beta x}}\right)\\
&=\dfrac{\pi_1e^{\alpha + \beta x}}{ \pi_0 + \pi_1e^{\alpha + \beta x}}\\
&= \dfrac{e^{\mu + \beta x}}{ 1 + e^{\mu + \beta x}}
\end{aligned}
where $\mu = \log(\pi_1/\pi_0) + \alpha$
Comment: How do we know what P(D=0|X=x) equals?
Comment: I assumed D is binary so $P(D=0|X=x)= 1-P(D=1|X=x)$

Showing a model is logistic


Passing current node ID to the block template

Question: I have a module with a custom block MyCustomBlock.php that get the nid of the current page and pass the value to the block template:
<code>$node = \Drupal::routeMatch()->getParameter('node');
$nid = $node->nid->value;
return array(
  'currentnid' => $nid,
);
</code>
Inside the template I print the passed value {{ currentnid }}, but it only works cleaning the cache! For example, if I load the page with nid 5 it prints 5, but if I move to page with nid 3 it prints 5. Cleaning the cache and reloading page with nid 3 I get the value 3 printed. I think it is a problem with the template caching system in D8, do you have any idea about this?
Comment: If you have page_cache enabled then nothing will help you for anonymous users. If you have only dynamic_page_cache enabled or the user is logged in you should use the cache context as mentioned below or you can use lazy builder(still only for dynamic_page_cache / no cache).
Answer: The proper way to do this would be use contexts. Plugin contexts, not cache contexts.
Similar to NodeType condition plugin, put something like this in your plugin annotation:
<code>* context_definitions = {
*  "node" = @ContextDefinition("entity:node", label = @Translation("Node"))
* }
</code>
And then get the node using $this->getContextValue('node').
This has two advantages:

Your block doesn't rely on global state directly. It could for example be used also in page manager, with a different node.
Drupal automatically understands that your block varies by whatever node is passed in. If using the current node, it will vary by route, if it would e.g. be a node from a static page manager context, it wouldn't. It will also include cache tags, in case the node is changed in a way that would affect your output.
Comment: Thank you, I will try implementing this solution as well and if I will be able to get it works I'll keep it.
Comment: Oh, this is really nice to know! +1
Comment: I tried this method but it stops working overall, the block doesn't seem to execute, I can't even print a string out. Log messages don't say anything and no PHP errors. The marked answer worked for me though.
Answer: Blocks are cached. However blocks are also context-aware in Drupal 8. Per the documentation page regarding Cache Contexts:

Cache contexts provide a declarative way to create context-dependent
  variations of something that needs to be cached. By making it
  declarative, code that creates caches becomes easier to read, and the
  same logic doesn't need to be repeated in every place where the same
  context variations are necessary.

The Cache API documentation page is a good read for everyone.
A Block plugin should implement getCacheContexts. I think that in this case it should either be "route.name" or "url.path". You may need to delve into this a bit more for your particular use case.
<code>  public function getCacheContexts() {
    return array('route.name');
  }
</code>
Comment: Thanks a lot! I have read the documentation about the cache context and it is quite clear now. In my specific case I have solved using "url.path" as context. It works fine now! @mradcliffe
Comment: See also my response. You can do it like this, but I'd recommend to at least call the parent::getCacheContexts() too and merge those together.


Image within an image

Question: I've tried a snippet found here on stack overflow.
I would like to find an image inside another, doesn't matter if is rotated or resized.
import matplotlib.pyplot as plt
import numpy as np
import cv2
import os
import pathlib

os.chdir(pathlib.Path(__file__).parent.resolve())

image = cv2.imread('picture.png')
template = cv2.imread('penguin.png')

heat_map = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)

h, w, _ = template.shape
y, x = np.unravel_index(np.argmax(heat_map), heat_map.shape)
cv2.rectangle(image, (x,y), (x+w, y+h), (0,0,255), 5)

cv2.imshow("pippo",cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
cv2.waitKey(0)

The result is not as expected.
I got
pippo
Thanks for an explanation.
Following the snippet i expected clearly that the penguin is inside the blue box
Comment: Please add edit your question and add the original `picture.png` and `penguin.png`. Please add the images, and not a screenshot of the images.
Answer: The white cloud better matches the template than the penguin.
Since there are no brightness and contrast differences between the image and the template, we don't have to apply normalized correlation.
Selecting cv2.TM_SQDIFF instead of cv2.TM_CCOEFF_NORMED is going to give better matching for the above case.

Replace heat_map = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED) with:
heat_map = cv2.matchTemplate(image, template, cv2.TM_SQDIFF)

The reason it works better is that the black part of the penguin is going to have much greater weight in the squared difference, compared to other methods.

Code sample:
import numpy as np
import cv2

#os.chdir(pathlib.Path(__file__).parent.resolve())

image = cv2.imread('picture.png')
template = cv2.imread('penguin.png')

heat_map = cv2.matchTemplate(image, template, cv2.TM_SQDIFF)

# Show the heat_map for testing:
cv2.imshow("heat_map", cv2.normalize(heat_map, None, 0, 255, cv2.NORM_MINMAX, cv2.CV_8U))

h, w, _ = template.shape
y, x = np.unravel_index(np.argmax(heat_map), heat_map.shape)
cv2.rectangle(image, (x,y), (x+w, y+h), (0,0,255), 5)

cv2.imshow("pippo", image)
cv2.waitKey(0)
cv2.destroyAllWindows()

Input image:

Input template:

Output:

Headmap with cv2.TM_CCOEFF_NORMED:

Headmap with cv2.TM_SQDIFF:

Image within an image


How do we decide on how to fill missing values in data?

Question: I have a data set with NA values in many predictor variables.
How do we impute the best values ?
I have 302 variables in total. Out of them 236 belong to some abstract category, 37 to other, 9 to other category.
PS: I am solving the following regression problem from Kaggle
https://www.kaggle.com/c/liberty-mutual-fire-peril
Comment: I'd suggest searching CV on "imputation" and possibly "Multiple inputation" or "hot-deck imputation."
Comment: This might help too, I asked this awhile back, the comments are helpful. https://stats.stackexchange.com/questions/458230/how-do-you-code-missing-values-if-0-is-meaningful
Answer: As mentioned before, you can impute the missing values using means, medians KNNs or even more sophisticated models. We sometimes choose to omit the whole row if the NAs are not that many.
I would go a step back and I would get the % of missing values for each column and try to treat each column in a different way or group "similar" columns together. What I usually do afterwards is for categorical or numerical values with a lot or NAs is that I create a new category "No info" with the missing values. If that variable was numerical, then you will have to make it categorical by cutting it at different cut off points based on quantiles or "reasonable" points depending on what this variable is about. Again you lose some info but it's sometimes better than losing the whole row or biasing the models with imputations.
Comment: I like this:  `I would go a step back and I would get the % of missing values for each column and try to treat each column in a different way or group "similar" columns together.` Could you kindly share a citable reference?
Comment: Not sure I have one on top of my head..I usually use my intuition with these things to be honest ;) I would say either group them based on similar context or categories they include or group them after getting the % and for the once with few missing values run a PCA and for the ones with more deep dive to combine their information or impute them (try stratified sampling/agent based modelling too). If the NA % is very high consider even dropping the column from your modelling. I would never use a mean or median to impute variables with more than 90% missing values.
Comment: I like your approach but to use it I need a source to cite.
Comment: Many methods seems to be there. But what is the right way to choose which method might be really appropriate and more suitable for a specific problem?
Answer: @hvedrung has already suggested few good methods for missing value imputation,
1)Replace missing   values with mean,mode,median.
2)If data is categorical or text one can replace missing values by most frequent observation.
3)EM algorithm is also used for these purpose.
4)In R language,
   4.1)package DMwR has  "knnImpute" method.
   4.2)base packages has "with" method, mice package has "complete" methode.
through which missing value imputation can be done.
Comment: I was going through the Kaggle forum in which one guy imputed all the missing values with -9999. Then he found many features to be highly correlated and removed a lot of features. I am not getting idea how is it done. That post can be found in the link:
Answer: I would not try to fill in values for predictive variables, I would simply eliminate them from your analysis.  My main concern is if these unknown values follow some sort of pattern, then you are going to introduce bias into your model.  With 550MB of data, this should not cause a problem of reducing your dataset.
However, the danger of using a method to replace these values is that you can create a model that picks up on your replacement technique, not the data.  Your model will produce artificial predictions that will fit your "fixed" data, but perform poorly against new data.
Also note that this contest was over last September.
Answer: Dont forget to check for things like serial correlation and correlation between x variables (you might be able to just remove the most deficient x variable if it is supplying redundant information)
One of the better substitution methods I have found is to create a random dataset with a similar distribution to the variable with the missing values, and then sample from that dataset to fill in the missing values.
If you know that the previous measurement is related to the next measurement, you could perform an interpolation over the values you have and estimate the missing values that way.
Comment: Welcome to our site! Note that your username, identicon, & a link to your user page
are automatically added to every post you make, so there is no need to sign
your posts. In fact, we prefer you don't.
Answer:
Simplest way but often not very efficient - delete data with missing values in any column.
Substitute with average value. Average for entire data set or set grouped by features you know is important.
Useful trick - add feature which is true if your value is missing and false otherwise.
Comment: The inefficiency of (1) can reach 100%, when at least one variable in each observation has a missing value, so you're correct to warn against that. (2) sounds like a great way to bias any estimates of variability as well as predictions. How would one exploit the "useful trick" in (3)?
Comment: It is obvious that ignoring missing values could hugely reduce data set. It is quickiest way though.
I often use substitution with average values. If you could share more correct and simple and fast method I would be very thankful.
Useful trick feature could be used for example by decision tree algorithm and help determine if the parameter (with missing values) is useful or not in this case.


Autenticação de usuario Firebase

Question: Utilizo o recurso de autenticação de email e senha do firebase, porem queria obter mais info do usuario como um telefone. Tem como fazer isto?
Answer: Você tem que utilizar isto juntamente com o Firebase Database. Os dados do Auth não tem como inserir chaves customizadas.
Crie uma chamada para o banco de dados, e ao logar o usuario, acrescente as informações extras dele dentro de uma referencia no banco.

Autenticação de usuario Firebase


Is there any Eclipse virgo simple project?

Question: I'm trying to check out osgi on web applications. I googled and found out the best way to go would be using spring osgi and virgo. I can't find an easy to setup sample project. Can anyone help me?
update- I should have mentioned that I have a little experience in OSGi(Equinox). And I checked some OSGi frameworks such as Apache Felix, Eclipse Equinox(with the tomcat bundle),... But I want to have my first experiment with Virgo.
Comment: OK, but I thought you have done the things you said! So I was wondering how to switch from felix to the Virgo. (you said that's easy).
Answer: I'd recommend taking a look at the Virgo Snaps project, using the 3.0.2.RELEASE of Virgo.
It takes a little bit extra time to configure Snaps (adding it to Virgo, and editing the org.eclipse.virgo.kernel.userregion.properties file, as mentioned in the docs). But then you have a simple yet modular web application running with a single spring controller.
There's also the Greenpages example that shows how to build a fully working, yet more complex webapp connected to a database. But I think taking a look at the snaps example (not concentrating too much on the Snaps internals) is a good way to start.
Good luck! :)
Comment: tnx. Just another question! Is there an eclipse plugin or something like that for virgo bundle developement?
Comment: I'd recommend using Springsource Tool Suite + Virgo server adapter (is part of the virgo tooling): http://wiki.eclipse.org/Virgo/Tooling. Oh and btw, in the meantime virgo 3.5 M2 is also working with the Virgo Tooling, so you might want to try that version.


Equals Method not working in string[]

Question: public String modUsernames[] = {"Test", "Test2"};
public String adminUsernames[] = {"Mod Jack", "Mod Demon"};

if (username.equals(modUsernames)) {
    rights = 1;
}
if (username.equals(adminUsernames)) {
    rights = 2;
}

How come this isn't working, and what would I do to get it working?
Comment: you simply need to learn code concept of java . BTW you could more understand by this link http://stackoverflow.com/questions/767372/java-string-equals-versus
Answer: (username.equals(modUsernames))

You should not compare String to Array and if username is an array than you can't check whether both are eqaul like this.
Use Arrays.equals(ar1,ar2) for this.
Or use array index and use loop to check one by one.
username.equals(modUsernames[0])

Or you can use Arrays.toString() and use contains method
Arrays.toString(modUsernames).contains(username);

Comment: You can - it's just always `false` :-)
Comment: @Sebastian  Yes I agree because equals takes `Object` as an argument and that's why it allows this comparison.Thanks!!
Answer: Assuming username is a String: The variable modUsernames is an array of Strings, it's not a single String. You have to compare the String username with one elemenet of that array:
if (username.equals(modUsernames[0]))

for example.
Note: The way you access to an element of an array is using an index:
someArray[index]

Index in most programming languages start in 0. So, if the length of the array is 2 (i.e. it has two elements), you can only use the index 0 and 1.
Comment: What's `username`? What is its value? (you can see this using `System.out.println`)
Comment: I don't really understand, I tried that and it still isn't working. :/
Comment: Username is `private transient String username;`
Comment: And what's its content?
Answer: As stated by others you cannot compare a String to an String[], what you can do is to check whether the String is contained in the String[], e.g.:
if (Arrays.asList(modUsernames).contains(username)){
   rights = 1;
}

Answer: Here what is your intention to compare . If it is to compare arrays then you may go with Arrays.equal(arr1,arr2). or if your intention to compare the index vales then you can go string.equals(str2);

Equals Method not working in string[]


How can I access an element in a list for prolog?

Question: So I'm having trouble trying to obtain a single element from a list using Prolog without using recursion, only relying on loops, such as foreach, foreachelem, etc....
So I have a list Xs = [1,2,3], and I want to obtain each element individually. The best I've come up so far is this...
sumOfList(Xs, Max) :-
    ( foreach(List, Xs), count(I, 1, _), param(Xs)
         do
            ( foreach(List2, Xs), count(J, 2, _), param(Xs, I, List)
                do
                   ( List =< List2
                     -> Max is List2;
                     Max is List1
                   )
            )
    ).

This is the best I've got so far... So I'm wondering, how do I create some kind of placeholder for Max that can be used for the final calculation?
Comment: Yup! Any help would be appreciated...
Comment: I suppose you want to learn the loop construct, but if you really just want the max of a list, simply write `Max is max(Xs)`.
Answer: Your question is not very clear for me. That's how you can find the max in the list of non-negative elements with ECLiPSe declarative loops:
max_with_loop(Xs, Max) :-
    ( foreach(Xi, Xs), fromto(0, MaxPrev, MaxCurr, Max) do
        MaxCurr is max(MaxPrev, Xi) ).

The interesting part is fromto(0, MaxPrev, MaxCurr, Max). Using this part you can transmit information between iterations. Initially MaxPrev becomes 0, after each iteration MaxCurr becomes MaxPrev, after the loop MaxCurr becomes Max.
BTW, declarative loops in ECLiPSe are kind of syntactic sugar, they are translated to recursive calls by the system.
Update: variant, suggested by @false in the comments, that also works with negative numbers:
max_with_loop([First | Xs], Max) :-
    ( foreach(Xi, Xs), fromto(First, MaxPrev, MaxCurr, Max) do
        MaxCurr is max(MaxPrev, Xi) ).

Comment: HET! `max_with_loop([I|Xs],Max) :- ... fromto(I, ...) ...`
Comment: `max_with_loop([-2,-1],-1).` fails
Comment: @false Yes, as I wrote, it will work for non-negative elements only.
Comment: Why don't you define it correctly? It isn't even more complex
Comment: @false To work with negative numbers it should be initialized to -Infinity or to the value of the first element. I thinks it adds unnecessary details, my goal was to show how to transmit information between iterations.
Comment: @false Yes, like I said, initialize with first element. In elegant way, though. I've updated my answer with your variant.


Objective C - app works in simulator and on other iPhones, but won't run on my own iPhone 4

Question: My app works fine in the simulator, and on other devices.  I have an iPhone 4 with the latest iOS update, and the app refuses to run on my device.
It seems to be a problem surrounding retina-display images.  The error spew I get when attempting to run on the phone is:
2012-01-11 09:27:47.404 rr_game1[1569:707] cocos2d: cocos2d v1.0.1
2012-01-11 09:27:47.413 rr_game1[1569:707] cocos2d: Using Director Type:CCDirectorDisplayLink
2012-01-11 09:27:47.845 rr_game1[1569:707] cocos2d: OS version: 5.0.1 (0x05000100)
2012-01-11 09:27:47.849 rr_game1[1569:707] cocos2d: GL_VENDOR:   Imagination Technologies
2012-01-11 09:27:47.853 rr_game1[1569:707] cocos2d: GL_RENDERER: PowerVR SGX 535
2012-01-11 09:27:47.856 rr_game1[1569:707] cocos2d: GL_VERSION:  OpenGL ES-CM 1.1 IMGSGX535-63.14.2
2012-01-11 09:27:47.861 rr_game1[1569:707] cocos2d: GL_MAX_TEXTURE_SIZE: 2048
2012-01-11 09:27:47.864 rr_game1[1569:707] cocos2d: GL_MAX_MODELVIEW_STACK_DEPTH: 16
2012-01-11 09:27:47.867 rr_game1[1569:707] cocos2d: GL_MAX_SAMPLES: 4
2012-01-11 09:27:47.871 rr_game1[1569:707] cocos2d: GL supports PVRTC: YES
2012-01-11 09:27:47.874 rr_game1[1569:707] cocos2d: GL supports BGRA8888 textures: YES
2012-01-11 09:27:47.877 rr_game1[1569:707] cocos2d: GL supports NPOT textures: YES
2012-01-11 09:27:47.880 rr_game1[1569:707] cocos2d: GL supports discard_framebuffer: YES
2012-01-11 09:27:47.883 rr_game1[1569:707] cocos2d: compiled with NPOT support: NO
2012-01-11 09:27:47.886 rr_game1[1569:707] cocos2d: compiled with VBO support in TextureAtlas : YES
2012-01-11 09:27:47.889 rr_game1[1569:707] cocos2d: compiled with Affine Matrix transformation in CCNode : YES
2012-01-11 09:27:47.892 rr_game1[1569:707] cocos2d: compiled with Profiling Support: NO
2012-01-11 09:27:48.012 rr_game1[1569:707] Game manager singleton, init
2012-01-11 09:27:48.031 rr_game1[1569:707] cocos2d: WARNING: Image (1024 x 4096) is bigger than the supported 2048 x 2048
2012-01-11 09:27:48.035 rr_game1[1569:707] cocos2d: Couldn't add image:grid.png in CCTextureCache
2012-01-11 09:27:48.047 rr_game1[1569:707] cocos2d: WARNING: Image (1024 x 4096) is bigger than the supported 2048 x 2048
2012-01-11 09:27:48.050 rr_game1[1569:707] cocos2d: Couldn't add image:bg-circuits.png in CCTextureCache
2012-01-11 09:27:48.054 rr_game1[1569:707] *** Assertion failure in -[CCParallaxNode addChild:z:parallaxRatio:positionOffset:], /Users/kevin/code/rr_game1/rr_game1/libs/cocos2d/CCParallaxNode.m:91
2012-01-11 09:27:48.058 rr_game1[1569:707] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Argument must be non-nil'

The odd thing is that the images it is puking on are in the app.

Again, the app works on other devices and in the simulator.  Here is the code that loads the images:
backgroundNode = [CCParallaxNode node];
[self addChild:_backgroundNode z:-1];

_backgroundGrid1 = [CCSprite spriteWithFile:@"grid.png"];
_backgroundCircuits1 = [CCSprite spriteWithFile:@"bg-circuits.png"];

_backgroundGrid1.anchorPoint = CGPointMake(0,0);
_backgroundCircuits1.anchorPoint = CGPointMake(0,0);
CGPoint gridSpeed = ccp(0.05, 0.05);
CGPoint circuitSpeed = ccp(0.1, 0.1);

[_backgroundNode addChild:_backgroundGrid1 z:1 parallaxRatio:gridSpeed positionOffset:ccp(0,-winSize.height)];
[_backgroundNode addChild:_backgroundCircuits1 z:0 parallaxRatio:circuitSpeed positionOffset:ccp(0,-winSize.height)];

I've deleted the app from my phone, run a "clean," restarted Xcode, and restarted my computer.  Still no luck.  I've also re-provisioned my phone.  I've also deleted and re-added the assets to the project.
Comment: It says the image is to big. It's just strange that, that only happens with the iPhone 4...
Comment: Don't use the @2x extension with cocos2d. Use the -hd suffix instead. See: http://www.cocos2d-iphone.org/wiki/doku.php/prog_guide:how_to_develop_retinadisplay_games_in_cocos2d
Answer: To be honest, it does say within your log file that the image size of 1024 x 4096 is far greater than the supported 2048 x 2048:
2012-01-11 09:27:48.031 rr_game1[1569:707] cocos2d: WARNING: Image (1024 x 4096) is bigger than the supported 2048 x 2048
2012-01-11 09:27:48.035 rr_game1[1569:707] cocos2d: Couldn't add image:grid.png in CCTextureCache
2012-01-11 09:27:48.047 rr_game1[1569:707] cocos2d: WARNING: Image (1024 x 4096) is bigger than the supported 2048 x 2048
2012-01-11 09:27:48.050 rr_game1[1569:707] cocos2d: Couldn't add image:bg-circuits.png in CCTextureCache

You say it runs on other devices but what devices are they? If they are not retina enabled, I imagine the respective image size would be 512x2048 thus fitting the 2048x2048 maximum size.
If your retina-display images are beyond those dimensions, it simply will not work - the 2048x2048 should already encompass the retina-sized images. You may need to revise your game to use smaller dimensions.
Comment: Or the other devices may have been iPhone 4Ss, maybe? Maximum texture size has gone up to 4096x4096 on those. Also, if backwards compatibility is a concern then it's worth being aware that it was 1024x1024 on all the PowerVR MBX devices (ie, the iPhone, iPhone 3G and associated iPods).
Comment: One of the other devices is another regular iPhone 4, as well as an iPhone 4s.
Comment: Just did some more digging - the file it's having a problem with isn't 1024x4096 - it's 640x2292
Comment: Oddly, even though it works as-is on another iPhone 4, reducing the file size to 640x2048 fixed the problem on _my_ device.
Answer: You should really look into cutting down your images into smaller chunks and possibly placing them in a sprite sheet for performance. Then you can simply add the images slices next to each other using something like this
    for (int i = 0; i < amountOfSprites; i++){
        CCSprite *sprite = [CCSprite spriteWithSpriteFrameName:spriteName];
        sprite.anchorPoint = ccp(0,0);

        sprite.position = ccp((i * sprite.contentSize.width),0);

        [yourBatchNode addChild:sprite];
    }

if you need any help with creating sprite sheets check out this guide http://www.raywenderlich.com/2361/how-to-create-and-optimize-sprite-sheets-in-cocos2d-with-texture-packer-and-pixel-formats


How to spell half whole dim scale?

Question: How do I spell these scales? I know there are three of them, but I don't know the accepted way to spell them. It's an 8 note scale so I assume one note is doubled. Which one?
Answer: It will depend on exactly how you are looking at it and what exactly is going on when it is used. Typically, you'll see the 2nd doubled especially when playing over altered dominants like a 7♯9 or a 7♭9♯11 like so:
<code>X: 1
M: C
K: Cmaj
L: 1/8
C_D^DE ^FGA_B||
</code>
The scale itself since it is fairly flexible and you'll get a lot of different combination of vastly different chords through the enharmonic combinations and you'll want the notes of the scale to represent the harmony at that point. So for example if you were playing a half-diminished chord, you wouldn't represent the 3rd note as a ♯2, but instead a ♭3.
Comment: Ok. So it is ok to have a mixture of sharps and flats?
Comment: @kolobcanyon Yeah. It happens all the time. G harmonic minor has 2 flats in the key signature, but the F will be sharp when explicitly using the harmonic or melodic scale.

How to spell half whole dim scale?


Distance measurement in chords and harmony

Question: I've been searching and thinking about this a lot since my mind got opened up to this possibility.
Is there any musical theory "formalism"/framework that deals with measuring the distance between two chords, note clusters or any 2 harmonies.
The premise is that such a notion of distance exists quasi universally in all domains, in different forms, but in harmony I haven't come across anything trying to define what the notion of distance would even mean, except maybe within the circle of fifths (distance between keys) or in modulations. Certain musician do talk about distance, but it's still blurry, and it is always based on some more fundamental assumptions.
I have come across nothing in particular that would describe such a notion at a "low-level", first principles derived, I've been toying with the idea of relative distance based on pitch alone and seeing everything from a chromatic scale POV, let's say we have a CMaj triad, Both Cmaj and Amin would represent "distance = 0", altering any tone within the triad up or down a semitone, for example augmenting the fifth would yield a distance of 1/3 (we altered 1 tone of the 3 possible) but then again how would such computation be if the distance is greater than a semitone?
I have some ideas about how I would elaborate on this, but it still feels too arbitrary, and maybe not very informative in the long run concerning what could be done with the results... And how they're interpreted...
I hope anyone can help me with this query since I'm not the biggest theory oriented person, I'm pretty sure someone somewhere has already done some research on a similar topic but I couldn't find anything no matter how much I searched.
Ps: completety forgot about the closest thing (maybe) to what I'm looking for, which is Tonnetz grid, but it doesn't feel like the most encompassing general proposition which I'm lookign for..
Comment: How would a C major chord and an A minor chord have a distance of 0 between them? They literally don't share all their notes.
Comment: What would you do with such a distance metric? For example, with a driving distance metric, taxi drivers try and optimize their routes to consume less time and/or fuel. What is your goal? What are you trying to achieve?
Comment: Sorry that was a blunder of mine, I guess I wanted to refer to scales Cmaj and Amin being the same pitch class set just offset to consider the tonic differently
Comment: @piiperiReinstateMonica Good question!
I'm actually trying to come up with a framework that would allow people to generate their own "meta-language" (depending on their needs, background, instrument, playing style...) and from that "formalism", they could express all their ideas, It's hard to explain and a bit blurry so far, but think something like mDecks Mapping Tonal Harmony but more open ended, and less biased towards a certain style (i.e jazz)
Comment: To elaborate on your question, this distance is something I'm toying with so far, since I'm trying to create/implement my own meta-language (as a first test) and I wanna "refer to chords in the spectrum of difference/similarity"
Comment: People have to resort to explaining ideas in terms of things they do and how they experience the world when doing those things. "I put my fingers on the bouzuki like this, and if I move my index finger to the left, then if feels nicer than if I move it to the right" is a possible framework for theoretical reasoning, though that style doesn't satisfy many Western people of today who like their theory in a more abstract form. But talking about music is ultimately connected to practicing music. Music theory belongs to humanistic, not natural sciences.
Answer: Short answer: no
Long answer: yes, but it gets arbitrary complicated the more you know
Am (a c e) -> C (c e g), one note changed in the set, distance 1, but as a triad movement all notes 'changed', if you play it not as a clustered chord but as an arpeggio. So is it 3 or 1?
looking at C -> F -> G: all notes changed between F and G, tension is raised, but the sound is neat.
However, what about a cadence? The transitions sound smooth, so the distances should be all 1, which is obviously not true for IV to V in the Am-C model. Or the progression Am -> G -> F -> E. Sounds smooth to me, even if the last chord is one half step distant. Depending on the style of music you will find even a deeper rabbit hole. Jazz progressions like to throw in altered chords to create chromatic lines with circle of fifth lines combined and in counterpoint theory we get absorbed by a black hole...
Worked out solutions:
If you want to follow something pretty much worked out I'd consider to study the approach of mdecks.com: Mapping Tonal Harmony Pro. IMHO the best practical program to get an idea of distances between chords. Here a screenshot of part of the user interface: https://mdecks.com/mapharmony2022assets/images/mapposter.jpg
Also this author has something worked out, more of a practical approach instead of formalising everything:  http://stevenmuschalik.com/MusicTheoryPoster-LowRes.png  In this case I like the triad structure tension and release model which can be formalised easier.
Deep dive:
The most extensive research of this thematic (AFAIK) is by Guerino Mazzola, in his book "The Topos of Music" https://link.springer.com/book/10.1007/978-3-0348-8141-8 . It is heavy stuff, very theoretical and extensive but it might be what you are looking for if you want to take a real deep dive worth of several years of study. I for myself have to admit to understand less than 10% of it.
An old book of this researcher is much more approachable but I am not aware of an english translation (Geometrie der Töne). He is also widely disputed,  just to get an idea check out this paper: https://dmitri.mycpanel.princeton.edu/files/publications/mazzola.pdf .
HTH
Comment: If you've not read it, you might be interested in Emmanuel Amiot's [*Music through Fourier Space"](https://link.springer.com/book/10.1007/978-3-319-45581-5).
Comment: @Aaron thanks, I didn't read that and looks very interesting to me. I did in the 90's a master thesis on a similar topic using geometric approaches with reverse fourier synthesis to generate sound pattern (not music).
Comment: Also found this, close to the ideas we're approaching from different angles
https://www.youtube.com/watch?v=UcIxwrZV10A
Answer: This is one of the typical questions that "Music Information Retrieval" deals with, and there are a number of possible approaches. I guess that you are thinking of a symbolic representation of chords, not the acoustics (which would make the chord distance dependent on the temperament). A simple approach is to represent a chord as a 12 dimensional vector and use metrics for vector spaces. See section 1.2 of the following article for a limited overview over some literature:

Maršík, L.: "Using chord distance descriptors to enhance music information retrieval: student research abstract." SAC '17: Proceedings of the Symposium on Applied Computing, pp. 963-964 (2017). (There is a selfarchived version accessible on researchgate)

For measuring the distance between entire sequences of harmonies, see the following OpenAccess article:

de Haas, W.B., Wiering, F. & Veltkamp, R.C.: "A geometrical distance measure for determining the similarity of musical harmony." Int J Multimed Info Retr 2, 189–202 (2013). https://doi.org/10.1007/s13735-013-0036-6
Comment: This is quite an elegant solution, Yes I'm more interested in pitch classes/notes descriptions (which could be analysed, described through functional or even atonal analysis)
This idea is basically setting a fixed orthogonal space, in which dimensions (orthogonality) comes from the fact that we're refering to any harmonic information from the 12dimesional space which is the "chromatic scale", so it becomes our reference point
Comment: The way I was thinking about this so far was flawed in the sense that I was considering any harmonic informaiton through an arbitrary n-dimensional space which makes the whole problem of comparison (difference) have no basis (literally),
It gave some results but it didn't feel as solid as a well made mathematical/theoretic model could be


How to extract a specific value from the linq query?

Question: I am building a NET 5 API and am unable to extract and calculate something. I have a table StockTransaction which among other has property Quantity (I skipped some properties for brevity):
public class StockTransaction : BaseEntity
{
    public int Id { get; set; }
    public decimal Price { get; set; }
    public int Quantity { get; set; }
    public bool Purchase { get; set; }
    public int Resolved { get; set; }
}

Suppose I have 7 transactions, all of which are purchase:
List<StockTransaction> list = new List<StockTransaction>
{
new StockTransaction {Id = 1, Purchase = true, Quantity = 10, Resolved = 5, Price = 50},
new StockTransaction {Id = 2, Purchase = true, Quantity = 5, Resolved = 5, Price = 70},
new StockTransaction {Id = 3, Purchase = true, Quantity = 8, Resolved = 8, Price = 25},
new StockTransaction {Id = 4, Purchase = true, Quantity = 7, Resolved = 5, Price = 77},
new StockTransaction {Id = 5, Purchase = true, Quantity = 1, Resolved = 1, Price = 23},
new StockTransaction {Id = 6, Purchase = true, Quantity = 3, Resolved = 0, Price = 14},
new StockTransaction {Id = 7, Purchase = true, Quantity = 2, Resolved = 0, Price = 17},
};

And I would like to get the value of the last 7 quantities, which in this case gives 176 ((2 x 17) + (3 x 14) + (1 x 23) + (1 x 77)). (How) can this be done? Every help and hint is more then appreciated...
Comment: This should get you started: `list .Select(s => s.Quantity * s.Price).Sum();`
Comment: I assume you know the `Select()` statement. It's not really clear what keeps you from getting the results you want.
Comment: Thanks, I know that part, the problem is in extracting the value of only some quantities...
Comment: ` (3 x 14) + (1 + 23)` why is the third parenthis an addition?
Comment: I made a mistake while typing...
Comment: You can use aggregate function in linq for such things
Comment: By last 7 you mean recent 7 transactions? So I am assuming you are taking date_created in base entity?
Comment: no, just quantities, those are the last 4 transactions (the last one should fetch only 1 quantity out of 7 and give the value of 77)
Comment: I skipped datecreated for brevity, it's in the StockTransactions, the baseentity holds only id
Answer: You can use
var last3=list.OrderByDescending(x=>x.CreatedDate).Take(3).Select(x=>x.Quantity * x.Price).Sum();

var requiredSum=last3+list.Where(x=>x.id==4).Select(x=>x.Price).FirstOrDefault();

Comment: This is great start, but how to fetch the value of the fourth transaction and take only one quantity with the value of 77?
Comment: Ok modifying my answer
Comment: So you want values from 4th to 7 transaction only?
Comment: yes, but only one quantity from the fourth transaction, and the whole 5, 6, 7 transaction
Comment: you can use Skip and Take to acquire sub range of data and ElementAt to get specific records
Comment: `.Select(t => t.Price * (t.Id == 4 ? 1 : t.Quantity)).Sum()` - will satisfy OP's requirements ;)
Comment: ~Petar please check modified answer
Comment: thanks will try everything and let you know, thank you all so much!
Comment: I just had to rewrite a code a bit, used First() - list.Where(x=>x.Id==4).Select(x=>x.Price).First();
Comment: I don't know if this is what OP wanted. In his example, it might get the correct result, but if Transaction with Id = 5 had a quantity of 2 instead of 1, you would not need any item of the transaction with Id = 4. @PetarSardelic Maybe you should check my answer.
Comment: My answer also produces required result, the question was tagged with linq so I did it in linq way.
Comment: `int result = 176` also produces the required result, but only with the sample data from OP. With other data, your code will fail.
Comment: yes I agree, your answer was maybe better with regards to my question, but the answer I marked as the right one is more valuable from the point of real world problems and that is why I have chosen it, it might be more useful for others to see this answer as the right one...anyway, it was my mistake for formulating question that way, I just wanted to make things simplified. Mea culpae, thank you everybody for your efforts.
Answer: Although you have tagged your question with LINQ, do it with a normal loop:
private static decimal SumOfLastTransaction(IEnumerable<StockTransaction> stockTransactions, int max)
    {
        decimal result = 0;
        int sum = 0;
        foreach(var stockTransaction in stockTransactions.OrderByDescending(x => x.Id))
        {

            if(sum + stockTransaction.Quantity <= max)
            {
                result += stockTransaction.Quantity * stockTransaction.Price;
                sum += stockTransaction.Quantity;
            }
            else
            {
                result += (max - sum) * stockTransaction.Price;
                return result;
            }
        }
        return result;
    }

You loop over the last items in your list. You sum the amount of transactions and check whether it is smaller than your maximum. As long as they are smaller, you can add the amount of transactions. If not, you check how much is missing until your maximum is reached and substract this from your quantity.
Online demo: https://dotnetfiddle.net/9oM4pj
Comment: this is the best answer!


Rename "Read More"

Question: I wanted to rename "Read more" in teaser (node--blog--teaser.html.twig) to something like "Continue" or anything else.
How can I achieve this?
Answer: In your theme open file THEMENAME.theme, example in my case THEMENAME is bartik and file is bartik.theme add code below:
<code>/**
 * Implements hook_preprocess_links().
 */
function bartik_preprocess_links(&$variables) {
    if (isset($variables['links']['node-readmore'])) {
      $variables['links']['node-readmore']['link']['#title'] = t('Read more custom text');
    }
}
</code>
Clear all cache and see result.
About add custom class to readmore link you can check here: Add custom classes to node links
Comment: @MattFletcher, you can use [hook_node_links_alter](https://api.drupal.org/api/drupal/core%21modules%21node%21node.api.php/function/hook_node_links_alter/8.6.x), which provides the node (to get the content type) and the view mode as context. This hook only works in a module.
Comment: Only issue is that you don't have access to the node that the links are for, meaning that you can't change it conditionally based on the node type.
Comment: Another issue would be that Bartik is a core theme. And it actually should be considered a crime changing core files. See [Why don't we hack core?](https://drupal.stackexchange.com/q/59054/15055).

Rename "Read More"


How do I add a specific meta-tag to all the pages of a site?

Question: I want to prevent Google from indexing my website. I know I need this meta tag added to the header.
<meta name="robots" content="noindex" />

How can I add this meta-tag to all the pages of a site?
Answer: You can use the Metatag module for this, in order to add meta tags to every page of your site:

If you want to do it by coding, it is possible to implement the theme_preprocess_html hook to add the meta tag manually:
function theme_preprocess_html(&$variables)
{

    $noindex = [
            '#tag' => 'meta',
            '#attributes' => [
                'name' => 'robots',
                'content' => 'noindex',
            ],
        ];
    $variables['page']['#attached']['html_head'][] = [$noindex, 'noindex'];
}

(more details here: https://stackoverflow.com/questions/35913739/add-meta-tag-to-head-in-drupal-8)
Comment: @usethe23, It is also possible. I have just edited my answer to add this possibility.
Comment: Thank you for your answer, i'd prefer if i can do this by code, with a hook for example ?
Answer: You can also add a robots.txt file with the following content in your docroot:
User-agent: *
Disallow: /

You can find more information about this in The Web Robots Pages.
Comment: Note that this prevents crawling, not (necessarily) indexing ([details](http://stackoverflow.com/a/35657571/1591669)).


Efeito waves materialize

Question: Estou testando alguns componentes do materialize, por eu ser iniciante. Percebi que o efeito da classe "waves-effect waves-light" não está funcionando. Queria saber o que está acontecendo, já tentei waves-rippler mas não deu certo tbm. Também acho que pode ser o diretório, não sei ao certo.

<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>Teste</title>

    <link rel="stylesheet" type="text/css"
    href="materialize/css/materialize.css" media="screen,projection">

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

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

    Button

Comment: Seria interessante vc colocar na pergunta de forma clara o que vc quer, o que tentou e o problema que está acontecendo. Só colocar o código e um print não ajuda em nada.
Comment: Estou tentando usar esse efeito no elemento quando clica, utilizando a classe waves-effect do materialize mas não está acontecendo nada quando eu clico no link, a classe parece não estar funcionando. A questão é que eu não sei se isso pode ser algo relacionado ao JQuery ou o diretório de algum arquivo estar com o nome errado.
Answer: Aqui a referencia está errada...

Tente com SRC e não HREF

Pela sua imagem não dei para ver direito a endentação dos arquivos, mas me parece que o jQuery está na pasta de fora, então no caminho deveria ter ../

Tente dessa forma:

Efeito waves materialize


Eigenvalues of double right shift operator

Question: Consider the Operator S/ $S: l_2 →  l_2$ , $S(x_1,x_2,x_3,....)=(0,0,x_1,x_2,x_3,...)$
I know the right shift operator has no eigenvalues,but does this operator either?
I this for the same reason as for the right shift operator?
Thanks!
Answer: Consider the right-shift operator $(x_{1},x_{2},\ldots)\mapsto(0,x_{1},x_{2},\ldots)$. Suppose there exists an eigenvector $\mathbf{x}\neq0$ of the shift operator. By definition, we can find a scalar $\lambda$ such that
$$
\lambda(x_{1},x_{2},\ldots)=(0,x_{1},x_{2},\ldots).
$$
This implies that $x_{1}=0$, $\lambda x_{2}=x_{1}=0$, etc., so that
$\mathbf{x}=0$, a contradiction.

Consider now the double-shift $(x_{1},x_{2},\ldots)\mapsto(0,0,x_{1},x_{2},\ldots)$.
As above, suppose there exists an eigenvector $\mathbf{x}\neq0$ of the double-shift operator. By definition, we can find a scalar $\lambda$ such that
$$
\lambda(x_{1},x_{2},\ldots)=(0,0,x_{1},x_{2},\ldots).
$$
What can you conclude?
Comment: The $\lambda$ have to be at the LHS, I suppose.
Comment: Technically no since it is a field and I could be considering the inverse of the eigenvalue... ^_^ But that was definitely just a mistake.
Comment: No. You conclude that the eigenvector is again 0, contradiction. Hence, the double right shift operator has no eigenvalues.
Comment: @user1781301: that is indeed the hint I was trying to give the OP
Comment: I got that answer (Contradiction) but since I'm just starting with Spectral Theory, i wanted to be sure.
Thanks !!!
Answer: If $S$ is the right shift, then you want to know if there exists $\lambda\in\mathbb{C}$ and $x\ne 0$ such that $S^2 x = \lambda x$. If there were such an $x$, then
$$
         (S+\sqrt{\lambda}I)(S-\sqrt{\lambda}I)x = 0.
$$
Because $(S-\sqrt{\lambda}I)x \ne 0$ (you know $S$ has no eigenvalues,) you conclude that $y=(S-\sqrt{\lambda}I)x \ne 0$ and $Sy = -\sqrt{\lambda}y$, which is a contradiction. Hence $S^2$ has no eigenvalues.


Isotopy and Homotopy

Question: What is the difference between homotopy and isotopy at the intuitive level.Some diagrammatic explanation will be helpful for me.
Answer: Isotopies are much stricter!
A homotopy is a continuous one-parameter family of continuous functions.
An isotopy is a continuous one-parameter family of homeomorphisms.
You can think of a homotopy between two spaces as a deformation that involves bending, shrinking and stretching, but doesn't have to be one-to-one or onto. For example, a punctured torus is homotopy equivalent to a wedge of two circles (a "figure 8"), which can be pictured by sticking your fingers into the puncture and stretching the torus back onto the meridian and longitude lines.
But this map is certainly not a homeomorphism -- even the dimension is wrong, not to mention that a wedge of two circles is not a manifold.
An isotopy is a deformation that involves only bending. It must be one-to-one and onto at every step. In this way, any two handlebodies of equal genus are isotopic.
Comment: Animation of [Deformation Retract of Punctured Torus](https://www.youtube.com/watch?v=j2HxBUaoaPU) into figure 8
Comment: nice anaswer.just what i wanted to know.
Comment: No, the "middle point" is not locally Euclidean.
Comment: figure 8 is a 1-dimensional manifold, no?

Isotopy and Homotopy


Selenium: click on

Question: I have the following html code and I want to click on the second option "Plan b".

Plan a</span

Plan b

Plan c
/ul>

I tried to do somthing like this:
1.
@FindBy(css = "li:nth-child(2)")
WebElement sparpreis;
sparpreis.click();

2.
@FindBy(xpath = "//*[@class='clearfix all']/ul/li[2]")
WebElement sparpreis;
sparpreis.click();

My error messages:

org.openqa.selenium.ElementNotVisibleException: element not visible
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@class='clearfix all']/ul/li[2]"}

Perhaphs I should activate the second "class"?
Comment: `//*[@class='clearfix all']/ul/li[2]` - it gives `NoSuchElementException` because `.clearfix.all` is the `ul` element. Try removing `ul`: `//*[@class='clearfix all']/li[2]`
Comment: 'Perhaphs I should activate the second "class"? ' have you tried that?
Answer: The /ul is not needed, try the following:
@FindBy(xpath = "//ul[contains(@class, 'clearfix all')]/li[2]")

Answer: As per the HTML you have shared, to click on the second option Plan b you can use either of the following code block :

css
@FindBy(css = "ul.clearfix.all li[data-content=b] > span")
WebElement sparpreis;
sparpreis.click();

xpath
@FindBy(xpath = "//ul[@class='clearfix all']//li[@data-content='b']/span")
WebElement sparpreis;
sparpreis.click();

Selenium: click on


Taxonomy/overview of machine learning techniques

Question: My question: I'm looking for a taxonomy/bestiary/overview of machine learning techniques. I would like to learn 1) how these methods relate to each other, and 2) the relative costs and benefits (and perhaps typical applications) of the different approaches.

Background: I'm trained in statistics, and have a reasonably clear mental map of how a range of these techniques relate to each other. Understanding the costs and benefits of different techniques obviously makes it easier to select the best one to apply in different situations.
I would like to develop a similar mental map or taxonomy of the broader machine learning field. It's most important for me to understand the highest levels in the technique taxonomy, but I also recognise that there are major lower-level developments in some areas I should be aware of (e.g. neural networks seem to have a huge number of sub-classes).
I'm not looking for in-depth explanations of each method - though references would be great - but instead a framework I can use to focus my learning efforts in a more informed way.
This question focussed on statistical techniques is similar, in that the goal is to understand relationships between methods. But I'm looking for more than a 'cheat sheet'. I'd like to understand each at least at a basic level, and not just follow a set of rules on a flow chart.
Comment: [Scikit-learn's documentation](http://scikit-learn.org/stable/index.html) can serve for this. It is organized in topics (classification, regression, dim. reduction etc). Also see this map: [Choosing the right estimator](http://scikit-learn.org/stable/tutorial/machine_learning_map/index.html).
Comment: Probably you already know this, but Elements of Statistical Learning is a good read for the smooth transition from statistics into (parts of) Machine Learning, and available online as a pdf. https://web.stanford.edu/~hastie/Papers/ESLII.pdf
Comment: See https://stats.stackexchange.com/questions/12386/machine-learning-cookbook-reference-card-cheatsheet
Answer: You can find a very good taxonomy of the most important ML methods in the table of contents of the book Machine Learning: a Probabilistic Perspective by Kevin Patrick Murphy.
Given your background in statistics, I'm pretty confident that you will find that book resourceful. It has both introductory descriptions and in-depth explanations of almost any kind of ML method.
Answer: Tree-based methods
A group of regression and classification methods built around decision trees. In a decision tree, data is recursively partitioned based on its predictors, and new predictions are generated by averaging data points at the relevant tips ('leaves') of each tree. Weaknesses of standard decision trees (such as overfitting) have been substantially overcome by bagging (in random forests) and boosting (in gradient boosting machines).
Includes: CART, C4.5, random forests, gradient boosting trees
Advantages: Flexible and relatively easy to interpret (importance scores, partial effects)
Support vector machines (SVMs)
Originally an algorithm for binary classification that identifies the hyperplane best separating two groups of data points. Subsequent extensions include multiclass SVMs (which work by reducing multiple class problems to a series of 2-class problems) and support vector regression (which uses the hyperplane to predict continuous values)
Advantages:
Artificial Neural Networks
Computing systems whose network structure is inspired by (and theoretically allows for the flexibility of) biological systems. Composed of a net of artificial neurons that can transmit signals to each other in a defined, usually hierarchical structure. Each artificial neuron takes multiple inputs, sums them based on their separate weights, and produces output based on some activation function. The weights of each input are learnt during the network's training process. Neurons are organised in layers that tend to abstract different features of the system they are trained upon.
Advantages:
Includes: Convolutional Neural Networks (CNNs), Recurrent Neural Networks (RNNs), Deep Learning
Comment: Starting this in a limited way, in the hope of building up a general resource.


Tried to run Corb in windows machine?

Question: I tried running sample corb example by following this documentation . I am having MarkLogic 9 in my machine and for that i had downloaded following jars marklogic-corb-2.4.0.jar,marklogic-xcc-9.0.4 . And created selector.xqy and transform.xqy files as specified in documentaion and kept all these in corb folder.When i tried running it , it is showing Error like below
D:\ChromeDownloads\corb\corb>java -cp "marklogic-corb-2.4.0.jar;marklogic-xcc-9.
0.4" -DOPTIONS-FILE=my.properties com.marklogic.developer.corb.Manager xcc://adm
in:admin@localhost:9000/CSV-DB
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: com/marklogic/xcc/exc
eptions/RequestException
        at java.lang.Class.getDeclaredMethods0(Native Method)
        at java.lang.Class.privateGetDeclaredMethods(Unknown Source)
        at java.lang.Class.privateGetMethodRecursive(Unknown Source)
        at java.lang.Class.getMethod0(Unknown Source)
        at java.lang.Class.getMethod(Unknown Source)
        at sun.launcher.LauncherHelper.validateMainClass(Unknown Source)
        at sun.launcher.LauncherHelper.checkAndLoadMain(Unknown Source)
Caused by: java.lang.ClassNotFoundException: com.marklogic.xcc.exceptions.Reques
tException
        at java.net.URLClassLoader.findClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
        at java.lang.ClassLoader.loadClass(Unknown Source)
        ... 7 more

Is there any other configuration changes need to be done to run CORB ?
Comment: I think you need to use semi-colon (`;`) as classpath separator on Windows. Can you try that?
Comment: @grtjn Tried giving `;` now it is showing another  `ERROR` . Updated in my quesion.
Answer: That error message is indicating that it cannot find the com.marklogic.xcc.exceptions.RequestException class, which is bundled in the XCC jar.
Your classpath is not correct and the XCC jar is not available. You forgot the .jar file extension when you set the classpath.
-cp "marklogic-corb-2.4.0.jar;marklogic-xcc-9.0.4"

should be:
-cp "marklogic-corb-2.4.0.jar;marklogic-xcc-9.0.4.jar"

Comment: Thanks @Hansen, i don't know how i forgot that simple one .
Comment: It always helps to get a second pair of eyes

Tried to run Corb in windows machine?


How to replace certain substrings in an array?

Question: I have my data set in a normal data model format:
var data = "Billing, alpha, beta"

But I want to modify this data by formatting the array by replacing "," with "/text/i"
var newData = [/Billing/i , /alpha/i, /beta/i]

Here is the code I have tried:
var data   = "Billing, alpha, beta"
var y = x.split(',')
var newData  = y.replace(",", "/i,")
console.log(newData)

Comment: what is the expected output?
Comment: This might work if you remove `y` and just run the `replace` on `data`.
Comment: var newData = [/Billing/i , /alpha/i, /beta/i]
Comment: https://jsfiddle.net/v2g1a72a/
Comment: @WiktorStribiżew the output contains space on from second string onwards
Comment: @SaurabhRaman Just `trim()` each item, see [update](https://jsfiddle.net/v2g1a72a/2/). Or [split with `,` and space](https://jsfiddle.net/v2g1a72a/4/).
Answer: Try this snippet
var data   = "Billing, alpha, beta";
var y = data.split(',');
newData=[];
for(i=0;i<y.length;i++)
  newData.push(new RegExp( y[i].replace(/(^\s+|\s+$)/g,""),"i"));
console.log(newData);

Comment: he output contains space on from second string onwards
Comment: @SaurabhRaman Please accept my solution if you are satisfied
Comment: The output is an array of strings, while OP needs an array of RegExp objects.
Comment: I appreciate your knowledge many thanks for your help....but there is little correction the output should also not contain ' " ' (double quotes)..... it should look like            ....  [/Billing/i,/alpha/i,/beta/i]
Comment: See my edit I've used Regex objects
Comment: I think this solves the problem, please upvote my answer


Decide on the number of adversarial samples to include during training

Question: A sample is considered adversarial if it drastically changes classifier's confidence $\in [0,1]$ when given as input. For example, if a spam/ham binary classifier considers some input $X$ to be 0.9 spam, then an adversarial input $X + \varepsilon$ (for some carefully crafted noise $\varepsilon$) may change the confidence to 0.01.
A common approach to make a model robust to such adversarial attacks is to include adversarial samples in the original dataset (essentially data augmentation). Here lies my question: what would be an informed / scientific way of deciding how many adversarial samples to include?
For instance, given a binary-labelled dataset, I can think of several factors that can decide the number of adversarial samples to be included:

Vulnerable sample selection: generate a bunch of adversarial instances only for testing, then find such positive instances $X$ on which the model drastically changes its confidence, i.e. $f(X) - f(X+\varepsilon) \approx 1$. Finally, generate more adversarial examples for such vulnerable instances $X$.
Try to balance the dataset by including $\approx \text{neg} - \text{pos}$ adversarial samples. This should make the training easier, but the real-world neg/pos distribution is discarded.
Add as many adversarial samples as necessary so as to cover most of the noise; or in other words, make each adversarial method as likely as possible. For example, in the spam/ham problem, some methods may include: altering the punctuation, change upper/lower case, misspelled words etc.
Answer: There is no single answer.  It all depends on what your goals are.
Adversarial training uses exclusively adversarial examples.  TRADES uses 50% clean samples and 50% adversarial samples.  Mixed adversarial training uses a mixture of clean samples and adversarial samples; the proportion can be anything.
The proportion of clean vs adversarial samples is a hyperparameter that you can adjust; adjusting it changes the tradeoff between accuracy on clean samples, vs robustness (accuracy on adversarial samples).  Where on that tradeoff curve you want to live will depend on your application and how the model is used.


Error when creating Picturebox at Runtime - Mono

Question: I'm new on Mono development, but I could do it before. Last year I tried to run the same project and worked, but now it gives the follow error when I try to create a picturebox at runtime (this "Erro X100" was me who added):

That is my code:
using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.IO;
using System.Data;
using MySql.Data.MySqlClient;

(...)

MarkArray[y] = new PictureBox();
var _with1 = MarkArray[y];
_with1.Tag = "mark";
_with1.Size = new Size(22, 45);
_with1.Location = new Point(pos_left - 22, pos_top - 45);
_with1.Parent = PictureBox_Map;
_with1.Visible = true;
_with1.BringToFront();
_with1.Image = new Bitmap(Directory.GetCurrentDirectory() + "imagens/mark_icons/bk" + bicicletas_qtd.ToString() + ".gif");
_with1.BackColor = Color.Transparent;

I'm using .NET Framwork 2.0 (I tried 4.0 but it gives the same error). The folder "imagens" is at the same dir. It works perfectly on Windows, and as I said before, was working last year in other distro. I remember I updated "Xamarim Studio". Does anyone know how can I solve this problem? Thanks since now!
Answer: GDI+ can't find the file, it is a zero byte file, or doesn't match a file type that it can display.
If it is related to not being able to find the file, check to see which directory Directory.GetCurrentDirectory() is actually pointing to.
Comment: Thank you very much! It was really a problem about directory. Directory.GetCurrentDirectory() returns another path, not where the executable was. I added the folder with those images and it worked fine.
Comment: Glad to be able to help!


How to use FXG as mx:Button icon

Question: I'm trying to use a FXG image as the icon for a button that also contains a caption. My FXG file is located at resources/SpeakerIcon.fxg and my attempted usage looks like this in my mxml file:
     <mx:Button id="audioButton" label="Audio"
                   ....
                   icon="{resources.SpeakerIcon}"/>

When I try to use this I get "TypeError: Error #1034: Type Coercion failed: cannot convert resources::SpeakerIcon@41fa0e1 to mx.core.IFlexDisplayObject." My research indicates that FXG files should be s:Graphics which do implement IFlexDisplayObject http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/spark/primitives/Graphic.html.
What simple thing am I missing?
Answer: The <s:Graphics/> object is different than the <Graphics/> tag in an FXG document.
<s:Graphics/> is the base class for Spark primitive shape components (like <s:Rect/>). These are not as lightweight as their FXG counterparts. As such they do not implement the IFlexDisplayObject interface (as @Flextras has just posted :)
FXG assets can be treated as SpriteVisualElement in your Flex code, which technically means FXG assets implement the IVisualElement interface.
If you can, use the Spark <s:Button/> class instead of mx. I don't think <mx:Button/> works with FXG.
Comment: @www.Flextras.com `s:Button` has an [icon](http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/spark/components/supportClasses/ButtonBase.html#style:icon) style since Flex 4.5: no custom skin required.
Comment: +1 for the 'graphic' description.  If he uses s:Button instead of mx:Button he'll probably have to create a custom button skin to display the image as part of the button.  I didn't think the spark Button allows for an icon in the same way the MX Button does.
Comment: @RIAstar Awesome; I must have missed that addition.
Comment: +1 for "FXG assets can be treated as SpriteVisualElement in your Flex code". I got it working for me just by casting the fxg to a SpriteVIsualElement.
Answer: For an FXG you should use a Sprite or [in your case] a SpriteVisualElement.  I don't believe either of those classes implement IFlexDisplayObject.
You may consider wrapping your FXG element up in this FXGImage class from my Apache Flex whiteboard.  FXGImage extends UIcomponent which is an IFlexDisplayObject.
Here is a direct link to the source code for the class.

How to use FXG as mx:Button icon


Bootstrap navbar layout and background picture too small

Question: I am trying to create a Bootstrap 5 web page according to a supplied design. I am facing few issues.
This is the design:

My current progress:

The first issue is the navbar. I have troubles to position the elements at the same distance from the sides as it was designed. The second issue is that when I open the menu, the menu is moved to top and left.

The third issue is the size of the hero section. I want it to be higher to show the complete image.
The last issue is the width of the headings. I would like to wrap it on too big displays.
Source code snippets:
  <meta name="viewport" content="width=device-width, initial-scale=1">

Lelisoft

              English

                  Cesky

Boost Efficiency and Productivity: Modernize Your Legacy Apps Today!

Don't let your legacy applications slow down your business.

I doubt I started correctly. I am not proficient with CSS so I seek for an advice.
Answer: Here is the improved code with explanation at the end.
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link href="https://firstname.lastname@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">

Lelisoft

          <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
            English
          </button>

Cesky

Something else

Something else

Boost Efficiency and Productivity: Modernize Your Legacy Apps Today!

Don't let your legacy applications slow down your business.

Solutions to your problems:

You have used margin auto class of bootstrap(m-auto) for anchor tag(the link) as
well as on the ul element in the nav bar. This causes it to apply a lot of margin
and causes to have a lot of space from the sides. I have made a new css class:
"nav-top" and applied custom padding of 70 px on the left and right side of the
parent container of anchor tag and ul item, you may change the amount of padding
according to your need.

Solved the menu problem by using a dropdown component. If you have any difficulty related to components, go to Bootstrap website and under "Components" you can see how different elements are implemented. Copy the code and make changes according to your requirements.

For the hero, I have given the hero div a height of 570px(you may change the height according to your needs) and I have positioned the background image in the following way:
background-position: center 0%;
This centers the image horizontally and moves the image up to the top. As you
increase the 0% value to 10% or 40%, the image will move down respectively(If 0%
then image is moved top, if 100%, image is moved to the bottom). You
may move the image up and down vertically according to your need.

For the heading, limit the width of the outer div to say maybe 70% or 80%. Such as:
div{
width: 80%;
}
Comment: Yes you may limit the div size so that the headings do not take up the whole screen and I would like to suggest to use percentage(for example 70%) and not rem.
Comment: Thanks. I created a codepan: https://codepen.io/literakl/pen/XWyjdMo.  I still need to upload the images (set up a webserver, waiting for DNS refresh). It shows the menu problem anyway.
Comment: Ad headings - I think I need to set a DIV width to 80 rem or so, as the headings are too long and hard to read.
Comment: Pictures are uploaded at codepen, but it does not show them. Weird.
Comment: Can you see the cause of this menu glitches?
Comment: Yes. I realize the menu causes it to move up


How to prove/disprove $H=\{(1),(123),(132)\}$ is normal in $G=A_5$?

Question: I can't figure out how to do this without manually computing all of the possibilities. Here are some relevant theorems I know:
$H$ is normal in $G$ iff:

$\quad\forall g\in G, gHg^{-1}=H$
$\quad\forall g\in G, gH=Hg$
$\quad\forall g\in G, gHg^{-1}\subseteq H$
Comment: Isn't $H$ just the trivial group, $\{(1)\}$?
Comment: What do you mean by $A_5$?
Comment: Of course, $A_5$ is a simple group, so it has no nontrivial normal subgroups. But you should actually compute precisely the element(s) of $H$.
Comment: @Jonathaniui $A_5$ is meant to mean the alternating group of degree 5.
Comment: Oops, it occurred to me I forgot a comma in defining the elements of $H$. See the new title for the edit. My mistake.
Comment: $H$ is not normal in $A_5$ (it's simple!)
Answer: As a tip, maybe you can construct an homeomorphism that has $H$ as its kernel and then H must be normal in $A_5$ because you know (or can easily proof) the kernel is always a normal subgroup of the domain.
Edit: Way to disprove it.
Disprove is easy, take an element in $A_5$ for example $(12345)$ now, for H to be normal $(12345)(1)(12345)=(12345)(12345)=(13524)$ should be in $H$ (because $(1)\in H$) but is obvious that $(13524)\notin H$ and then $H$ is not normal in $A_5$.
Comment: Not a constructive tip in this case.
Comment: I'm afraid I haven't learned what homeomorphisms or kernels are yet :)
Comment: This is the standard way though, in general using one of the three conditions OP gave is difficult.
Comment: @user3724404 Are you sure the proposition ask you to prove $H$ is indeed normal in there? Because $A_5$ is a simple group and it has no proper non trivial normal subgroup, so there is no demonstration because it is false.
Comment: @Jonathaniui Oops again, I had forgotten that the instructions were to prove OR DISPROVE a few hypotheses. No wonder I'd been struggling on this. Title edited again.
Comment: @user3724404 Disprove is easy, take an element in $A_5$ for example $(12345)$ now, check that $(12345)(1)(12345) \notin H$ this is because you have that $(1)\in H$ so for H to be normal  $(12345)(1)(12345)$ should be in H.


Powershell Unload Module... completely

Question: I'm working on debugging a Powershell project.  I'm using Import-Module to load the PS module from my C# dll and everything works fine.  Calling Remove-Module does not fully unload the module though as the DLL is still locked and can not be deleted.
Is there a way to get PSH to fully unload the module and release the DLL so that I can copy over it and reload it again using Import-Module without restarting the PSH console?
Update
So if you load a module into a seperate AppDomain does it still work like a normal module?  Can anyone provide an example?
Comment: I've been exploring this as well -- I want to distribute a nuget package as a powershell plugin, and in order to allow the package to be updated, it needs to be able to delete the old package version (which contains the supporting dlls).  I think wrapping the functions in an command line exe is probably going to be the best bet. :(
Answer: There is a workaround. Open up another instance of PowerShell:
PS > powershell
PS > [load DLL]
PS > [do work]
PS > exit

After the exit, you'll be brought back to the instance of PowerShell from which you made this call (assuming you made the powershell call inside and instance of PowerShell). You can pass in any of the normal arguments to powershell, so you can use -Command or -File. E.g.,
PS > powershell -Command '[load DLL]; [do work]' # Executes a command and exits
PS > powershell -Command '.\myscript.ps1 param1 param2' # Executes the script and exits
PS > powershell -File .\myscript.ps1 param1 param2 # Executes a script and exits.

When PowerShell exits, it will release the lock on the DLL, allowing you to continue working.
All of this was done from the PowerShell command line interface. I haven't tested what happens if you throw powershell in the middle of a script or if this works within ISE. (I suspect it works within ISE.) Even if if doesn't work inside a script, this is still useful during development.
Edit:
Did some checking. So this seems to work fine from within scripts and in ISE, but there's a caveat within ISE. From ISE, you can't read any input from the user while you're inside the separate PowerShell process. If you try, the script or commands stop to wait, but no input box is shown like normal, and of course, you can't type directly into the output window in ISE. So if you need to prompt for input in the middle of [do work], prompt before firing up a new instance of PowerShell, and pass it into the work as a parameter. These aren't problems at all if you're using the regular PowerShell command line.
Comment: Two benefits I can think of: First, you pass a script block to a job, which allows you to keep your script in one source file.  And second, you can pass (serializable) objects as parameters to job, instead of just text parameters.  It's a similar workaround to yours, which is why I didn't post it as a separate answer.
Comment: A few years late to the party, but a similar workaround is to do the work in a [background job](http://technet.microsoft.com/library/hh847783.aspx).  Powershell background jobs are run as separate processes.  You still can't read user input, but it's a bit more flexible than spawning a new instance of Powershell.
Comment: @JamesQMurphy Background jobs look like they're designed for async operations. If that's what you need anyway, that sounds like a great option, but if you don't, that feels a lot of added complexity when you could just run the process in line. Are there other benefits I'm not seeing?
Answer: No. As PowerShell uses .NET underneath it has the same requirements.
You cannot unload a dll from a .NET AppDomain without unloading the AppDomain itself. As the PowerShell UI lives in the same AppDomain this is not possible.
Answer: I see a few workable answers here, but here's mine, in case this is still a problem for someone (and this is pretty lazy, which is nice).
Enter-PSSession -localcomputername
[load dlls]
[execute script(s)]
Exit-PSSession

Long story short, creating a PSSession for your local computer creates a different powershell session, including what's considered "loaded", and when you exit, it cleans things up for you.
Comment: FYI this does not appear to work in PowerShell Core (tested 7.0.3 on Windows 10) unless you configure winrm first. This can be done using the command "winrm quickconfig" or "Enable-PSRemoting -Force" (force skips the confirmation)
Answer: In the context of Cmdlet development, and having issues with unloading your DLL, there are two approaches that I use.
Firstly, I develop in Visual Studio, and setup an external program (PowerShell) to load my Cmdlet.  This way, my module loads when I start debugging, and unloads when I stop debugging.
Second, on those occasions where I know I want to load a module, do some work, and ensure the module is unloaded afterwards, I use a second instance of PowerShell.  This has been discussed in other answers, and my answer below shows how I enable this workflow by using a function with an alias in my Profile. I change the prompt so I can have a visual reminder that I am in a "recursive PowerShell window".
Create a script in your profile to start PowerShell
function Start-DebugPowerShell
{
    PowerShell -NoProfile -NoExit -Command {
        function prompt {
            $newPrompt = "$pwd.Path [DEBUG]"
            Write-Host -NoNewline -ForegroundColor Yellow $newPrompt
            return '> '
        }
    }
}
Set-Alias -Name sdp -Value Start-DebugPowerShell

Edit debug settings for your Cmdlet project
Start external program:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
Command line arguments:
-NoProfile -NoExit -Command "Import-Module .\MyCoolCmdlet.dll"
Debug your Module
Now from Visual Studio, start debugger with F5, and you have a new PowerShell window with your Cmdlet loaded, and you can debug it however you like.
Use the 'sdp' alias from any PowerShell window
Since the Start-DebugPowerShell function is in our profile and we gave it an alias sdp, you can use this to start a second instance of PowerShell anytime you need it.
Comment: I can confirm that the Visual Studio debugging portion of this answer is a very good solution to this problem.
Answer: I believe this holds true for PowerShell: in the .NET world the only way to unload an assembly is to load it into a different AppDomain; once an assembly is loaded to an AppDomain it remains loaded for the lifetime of that AppDomain.

Here's an example from a thread asking pretty much the same question and showing a couple ways to create and load the module into a new AppDomain:
http://www.eggheadcafe.com/conversation.aspx?messageid=30789124&threadid=30766269
Comment: I expected this may be the case, however I don't think you can load an interact with PSH modules this way.  So the real answer is likely that what I'm trying to achieve is not possible.
Comment: It's possible to load & unload DLLs and replace the DLL using the AppDomain shadow copy feature. http://www.codeproject.com/Articles/633140/MEF-and-AppDomain-Remove-Assemblies-On-The-Fly
Comment: The link in the answer is dead.
Answer: I've had the same issues and ended up wrapping the DLL I wanted to load inside a commandline exe which I then called from the script.  In that way I avoided loading the DLL inside my application at all.
Comment: sadly, I think that is what I may end up doing as well
Answer: I use a simple script that renames target DLL and loads it as module. Here we have 2 hacks:

when module is loading from .net assembly object we got loaded module with name "dynamic_code_module_FirstPowershellModule"
so before import we unload this module and create new one from renamed file

previous assemblies stay unused in domain
script must be run after each project rebuild
Get-Module -Name "*FirstPowershellModule*" | Remove-Module
$ii++
$destPath = "D:\Dev\FirstPowershellModule\FirstPowershellModule\bin\Debug\FirstPowershellModule" + $ii+ ".dll"
Copy-Item D:\Dev\FirstPowershellModule\FirstPowershellModule\bin\Debug\FirstPowershellModule.dll -Destination $destPath
$ass = [System.Reflection.Assembly]::LoadFile($destPath)
import-module -Assembly $ass

Answer: Make a copy of the DLL and load that copy.
You can Reload DLLs.
Answer: The PS modules are .net assemblies, when you Import-Module, you load them into the AppDomain of the PowerShell Host(the application). Remove-Module just removes modules from the current session.
According to msdn,
http://msdn.microsoft.com/en-us/library/ms173101(v=vs.80).aspx

There is no way to unload an individual assembly without unloading all of the application domains that contain it. Use the Unload method from AppDomain to unload the application domains. For more information, see Unloading an Application Domain.

You could start a new PowerShell host in a new AppDomain, import your module to the host and do the PowerShell job. The module is as normal as it was running in your previous host. The only difference is that it is in a host running in a different AppDomain.
Answer: I had some external module (ImportExcel) I wanted to update like this and it did not work. For this situation Install-Module -Scope CurrentUser <MyExternalModuleName> (in case it is in your users module folder, otherwise omit the -Scope ... param) worked.
(How they managed it internally - I don't know, but you keep your current PS session.)

Powershell Unload Module... completely


MI between vectors

Question: There exist a relationship between MI and entropy of two random variables i-e $$ I(X;Y)=H(Y)-H(Y|X).$$
But what if  $ \overrightarrow X \: \in \mathbb {\{0,1\}}^2$ and $ \overrightarrow Y \: \in \mathbb R^{+ \: 3}$  be the random vectors. How to specify the mutual information $I(\vec X ; \vec Y)$ between them i-e ? $$I(\overrightarrow X \: ; \overrightarrow Y)= ?$$
I suspect that KL divergence may be one possible answer but then how to define it for vectors?
Comment: A "random vector" is a "random variable". You seem to believe that a random variable is a scalar - in general, it doesn't need to be, it can be multidimensional - and in particular, in the MI definition, it can well be multidimensional
Comment: @leonbloy I know that random vector is a random variable. What I didn't explain in question was that how to expand $I( \overrightarrow X;\overrightarrow Y)=H(\overrightarrow X)-H(\overrightarrow X| \overrightarrow Y) $ in terms of components. (if $ \overrightarrow X$ is 2D and $\overrightarrow Y $ is in 3D)
Answer: Mutual information  applies to probability distributions. Since a random vector is still just a probabilities distribution (albeit one where the random variables are multi-dimensional) then it doesn't need any special treatment. You'd simply take each vector (e.g., $x=(0,0)$,$P(x=(0,0))=0.4$) as a possible value of the random variables $X$ and $Y$ and then add them up in the usual way for mutual information.

MI between vectors