Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding, when trying to install packages on venv

Question: I created a virtual environment through python -m venv env in python and tried to install packages with pip on it. I've got this error:
Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding
Python runtime state: core initialized
ModuleNotFoundError: No module named 'encodings'

I'm using Windows, does it has something to do with the environment variables? (PYTHONPATH, PYTHONHOME)
Comment: how do you create venv ? What system do you use (Windows/Linux/MacOS) ? What module do you try to install ? On Linux I don't need `PYTHONPATH, PYTHONHOME` to use `venv` and install modules in venv but maybe your system need it.
Comment: I created the venv using `python -m venv venv`
Comment: I wouldn't use name `venv` because it can make conflict with module `venv`
Answer: Turns out that you have to reinstall python and check Add Python to environmental variables in Advanced Options.
Comment: That option doesn't appear when installing from the Store.


Calculating distance between two points using dictionary in python

Question: I am trying to calculate a distance between two locations, using their coordinates. However I don't know how I can access the coordinate values, since they are in a dictionary.
I am very new to coding, and didn't understand any of the code I found regarding this problem, since it's too advanced for me. I don't really know where to start. My main function creates the dictionary: (Edit)
def main():
    filename = input("Enter the filename:\n")
    file= open(filename, 'r')
    rows= file.readlines()
    d = {}
    list = []
    for x in rows:

        list.append(x)
    #print(list)
    for elem in list:

        row = elem.split(";")

        d[row[3]] = {row[0], row[1]} #these are the indexes that the name and latitude & longitude have in the file

{'Location1': {'40.155444793742276', '28.950292890004903'}, 'Location2': ... }
The dictionary is like this, so the key is the name and then the coordinates are the values. Here is the function, which contains barely anything so far:
def calculate_distance(dictionary, location1, location2):

    distance_x = dictionary[location1] - dictionary[location2]
    # Here I don't know how I can get the values from the dictionary,
    # since there are two values, longitude and latitude...

    distance_y = ...
    distance = ... # Here I will use the pythagorean theorem

    return distance

Basically I just need to know how to work with the dictionary, since I don't know how I can get the values out so I can use them to calculate the distance.
--> How to search a key from a dictionary and get the values to my use. Thank you for answering my stupid question. :)
Comment: [This one](https://stackoverflow.com/questions/19412462/getting-distance-between-two-points-based-on-latitude-longitude) might be helpful.
Comment: Could you give us a) the part of the main function where the dict is created and b) the value of type(dictionary[location1]) please?
Comment: euclidean distance on latitude / longitude coordinates is not a good idea: for example points `(0, 90)` and  `(180, 90)` are exactly at the same position on the sphere but a euclidean distance returns `180`. Use the haversine formula instead.
Answer: Well you are starting out, its normal that this makes it more difficult for you.
So lets see, you have a function that outputs a dictionary where the keys are locations and the values are coordinate pairs.
First lets talk about the data types that you use.
location_map={'Location1': {'40.155444793742276', '28.950292890004903'}, 'Location2': ... }

I think there is an issue with your values, it seems that they are sets of strings. This has 2 main advantages for your goal.
First, set objects do not support indexing, this means that you cannot access location_map['Location1'][0] to get the first coordinate. Trying this would give you a TypeError. Instead, by using tuples when creating your map would allow you to index. You can do this by defining the coordinates as tuple([longitude,latitude]) instead of {longitude,latitude}.
Second, it seems that your coordinates are strings, in order to perform arithmetic operations with your data you need a numeric type such as integers or in your case floats. If you are reading longitude and latitude values as strings you can convert them by using float(longitude) and float(latitude).
Answer: There are multiple ways to do it, few are listed below:
# option 1
for i, v in data.items(): # to get key and value from dict.
    for k in v: # get each element of value (its a set)
        print (k)

# option 2
for i, v in data.items(): # to get key and value from dict.
    value_data = [k for k in list(v)] # convert set to list and put it in a list
    print (i, value_data[0], value_data[1]) # use values from here

I would suggest you to go through the python documentations to get more in-depth knowledge.


Supremum of a very simple sequence of functions

Question: Given $f_n(x)=nx$ with $x \in \mathbb{R}$ and $n \in \mathbb{N}$, what is $\sup_n\{f_n(x)\}$.
I argue that the $\sup$ is $+\infty$.
My friend argue that it is
$$
\sup= \begin{cases} -\infty, & \mbox{if } x<0 \\ 0, & \mbox{if } x=0 \\ +\infty, &\mbox{if } x>0 \end{cases}
$$
We can't seem to understand this concept.
Comment: The $\sup$ cannot be $-\infty$, since the set is never empty.
Answer: We have that, assuming $0\not \in \mathbb N$

for $x>0 \implies f_n(x)=nx \to \infty$
for $x=0 \implies f_n(x)=nx =0$
for $x<0 \implies \max(f_n(x))=-x \implies \sup(f_n(x))=-x$

assuming $0 \in \mathbb N$ we would obtain

for $x<0 \implies \max(f_n(x))=0 \implies \sup(f_n(x))=0$

Refer also to the related

Is $0$ a natural number?
Answer: Let us define for $x \in \mathbb R$:
$$A_x:=\{nx: n \in \mathbb N\}.$$

If $x=0$, then $A_0=\{0 \}$, hence $ \sup A_0=0.$

If $x>0$, then $A_x$ is not bounded from above, hence $\sup A_x= \infty.$

If $x<0$, then $t <0$ for all $t \in A_x.$ Hence $0$ is an upper bound of $A_x.$ It is your turn to show that $\sup A_x=0$ , if $x<0.$


Convert array of string to array of Json objects in Postgresql Jsonb

Question: i have a jsonb column like
{
    "foo":{"bar" :["b","c","d"]}
}

Which I want to convert all items of "bar" array to a json with a "name" key result shall be:
{
    "foo":{"bar" :[{"name":"b"},{"name":"c"},{"name":"d"}]}
}

I wish to do it using postgresql queries in all rows of my table.
I tried various queries and functions but my main issue is at wrapping part of my strings.
Tips and helps are appriciated
Comment: Are you actually using `Postgres 9.1`?  It looks like native `JSON` support wasn't added until 9.2 and `JSONB` wasn't added until 9.4.
Comment: `["name":"b","name":"c","name":"d"]` is invalid because it is not an object notation. Also same keys in the object is not allowed
Comment: And `jsonb` wasn't added until 9.5
Answer: Assuming you're using a version of Postgres with JSON support (9.4+), this should get you close:
WITH cte(myJSON) AS (
  SELECT CAST('{"foo":{"bar" :["b","c","d"]}}'AS JSONB) AS MyJSON

  UNION ALL

  SELECT CAST('{"foo":{"bar" :["e","f","g"]}}'AS JSONB) AS MyJSON
)

SELECT
  JSON_AGG(
    (SELECT ROW_TO_JSON(_) FROM (SELECT name) AS _)
  ) myrow
FROM (
  SELECT JSONB_ARRAY_ELEMENTS(myjson->'foo'->'bar') AS name,
    ROW_NUMBER() OVER() AS RowNum
  FROM cte
) src
GROUP BY src.RowNum

This will return [{"name":"b"},{"name":"c"},{"name":"d"}].
You can then construct your final JSON as needed.
SQL Fiddle
Reference
Update
This is very hacky and I'm sure there's a cleaner way, but I updated the query above to handle multiple rows.  Just replace the CTE references with your actual table name and myjson with the name of your JSON column.
Output:
[{"name":"b"},{"name":"c"},{"name":"d"}]
[{"name":"e"},{"name":"f"},{"name":"g"}]

Let me know if that works.
Updated Update
Here's an UPDATE statement you can use:
UPDATE t1 tgt
SET jsoncol = JSONB_SET(
  jsoncol, -- Source JSON
  '{foo,bar}', -- Target node to update
  src.new_json -- New value
)
FROM (
  SELECT
    ID,
    JSONB_AGG(
      (SELECT TO_JSONB(_) FROM (SELECT name) AS _) -- Convert new row to JSON
    ) new_json
  FROM (
    SELECT
      ID,
      JSONB_ARRAY_ELEMENTS(jsoncol->'foo'->'bar') AS name -- Convert array to rows
    FROM t1
  ) src
  GROUP BY src.ID
) src
WHERE tgt.ID = src.ID -- Update "tgt" table with rows from "src" table
;

DB-Fiddle
Comment: It works only for a single row, any idea how can I loop over all rows ?
Comment: It works charm, but now I face another issue, I am updating this table which only bar supposed to change ,  any clue on how to write the update ?
Comment: You can use something like this: `UPDATE MyTable SET jsoncol = JSONB_SET(jsoncol, '{foo,bar}', )`.  This will replace the value in `foo->bar` with `new_JSON_value`.  If you want to use the query above you'll need to do an `UPDATE FROM` and join the "src" table to the "tgt" table.  What is the `PK` of the table you want to update?
Comment: It has an ID as primary key. I tried your approach but it is copying all rows
Comment: what do you mean by "tgt" table ?
Comment: "tgt" = target table, "src" = source table.  See above.  Let me know if it works


Binding TabControl ItemsSource to an ObservableCollection of ViewModels causes content to refresh on focus

Question: I'm creating an WPF application using the MVVM framework, and I've adopted several features from Josh Smith's article on MVVM here...
Most importantly, I'm binding a TabControl to an ObservableCollection of ViewModels.  This means that am using a tabbed MDI interface that displays a UserControl as the content of a TabItem.  The issue I'm seeing in my application is that when I have several tabs and I flip back and forth between tabs, the content is being refersh each time I change tabs.
If you download Josh Smith's source code, you'll see that his app has the same problem.  For example, click on the "View All Customers" button and scroll down to the bottom the ListView.  Next click on the "Create New Customer" button.  When you switch back to the All Customer view you'll notice that the ListView scrolls back to the top.  If you switch back to the New Customer tab and place your cursor in one of the TextBoxes, then switch to All Customers tab and back, you'll notice that the cursor is now gone.
I imagine that this is because I'm using an ObservableCollection, but I can't be sure.  Is there any way to prevent the tab's content from refreshing when it receives the focus?
EDIT:
I found my problem when I ran the profiler on my application.  I'm defining a DataTemplate for my ViewModels so it knows how to render the ViewModel when it is displayed in the tab... like so:
<DataTemplate DataType="{x:Type vm:CustomerViewModel}">
    <vw:CustomerView/>
</DataTemplate>

So whenever I switch to a different tab, it has to re-create the ViewModel again.  I fixed it temporarily by changing my ObservableCollection of ViewModels to an ObservableCollection of UserControls.  However, I would really still like to use DataTemplates if possible.  Is there a way to make a DataTemplate work?
Answer: The default behavior of WPF is to unload items which are not visible, which includes unloading TabItems which are not visible. This means when you go back to the tab, the TabItem gets re-loaded, and anything not bound (such as a scroll position) will get reset.
There was a good site here which contains code to extend the TabControl and stop it from destroying it's TabItems when switching tabs, however it no longer seems to exist now.
Here's the code I use to prevent that issue. It initially was from that site, although I've made some changes to it. It preserves the ContentPresenter of TabItems when switching tabs, and uses it to redraw the TabItem when you go back to the page. It takes up a bit more memory, however I find it better on performance since the TabItem no longer has to re-create all the controls that were on it.
// Extended TabControl which saves the displayed item so you don't get the performance hit of
// unloading and reloading the VisualTree when switching tabs

// Obtained from http://eric.burke.name/dotnetmania/2009/04/26/22.09.28
// and made a some modifications so it reuses a TabItem's ContentPresenter when doing drag/drop operations

[TemplatePart(Name = "PART_ItemsHolder", Type = typeof(Panel))]
public class TabControlEx : System.Windows.Controls.TabControl
{
    // Holds all items, but only marks the current tab's item as visible
    private Panel _itemsHolder = null;

    // Temporaily holds deleted item in case this was a drag/drop operation
    private object _deletedObject = null;

    public TabControlEx()
        : base()
    {
        // this is necessary so that we get the initial databound selected item
        this.ItemContainerGenerator.StatusChanged += ItemContainerGenerator_StatusChanged;
    }

    ///
    /// if containers are done, generate the selected item
    ///
    /// <param name="sender"></param>
    /// <param name="e"></param>
    void ItemContainerGenerator_StatusChanged(object sender, EventArgs e)
    {
        if (this.ItemContainerGenerator.Status == GeneratorStatus.ContainersGenerated)
        {
            this.ItemContainerGenerator.StatusChanged -= ItemContainerGenerator_StatusChanged;
            UpdateSelectedItem();
        }
    }

    ///
    /// get the ItemsHolder and generate any children
    ///
    public override void OnApplyTemplate()
    {
        base.OnApplyTemplate();
        _itemsHolder = GetTemplateChild("PART_ItemsHolder") as Panel;
        UpdateSelectedItem();
    }

    ///
    /// when the items change we remove any generated panel children and add any new ones as necessary
    ///
    /// <param name="e"></param>
    protected override void OnItemsChanged(NotifyCollectionChangedEventArgs e)
    {
        base.OnItemsChanged(e);

        if (_itemsHolder == null)
        {
            return;
        }

        switch (e.Action)
        {
            case NotifyCollectionChangedAction.Reset:
                _itemsHolder.Children.Clear();

                if (base.Items.Count > 0)
                {
                    base.SelectedItem = base.Items[0];
                    UpdateSelectedItem();
                }

                break;

            case NotifyCollectionChangedAction.Add:
            case NotifyCollectionChangedAction.Remove:

                // Search for recently deleted items caused by a Drag/Drop operation
                if (e.NewItems != null && _deletedObject != null)
                {
                    foreach (var item in e.NewItems)
                    {
                        if (_deletedObject == item)
                        {
                            // If the new item is the same as the recently deleted one (i.e. a drag/drop event)
                            // then cancel the deletion and reuse the ContentPresenter so it doesn't have to be
                            // redrawn. We do need to link the presenter to the new item though (using the Tag)
                            ContentPresenter cp = FindChildContentPresenter(_deletedObject);
                            if (cp != null)
                            {
                                int index = _itemsHolder.Children.IndexOf(cp);

                                (_itemsHolder.Children[index] as ContentPresenter).Tag =
                                    (item is TabItem) ? item : (this.ItemContainerGenerator.ContainerFromItem(item));
                            }
                            _deletedObject = null;
                        }
                    }
                }

                if (e.OldItems != null)
                {
                    foreach (var item in e.OldItems)
                    {

                        _deletedObject = item;

                        // We want to run this at a slightly later priority in case this
                        // is a drag/drop operation so that we can reuse the template
                        this.Dispatcher.BeginInvoke(DispatcherPriority.DataBind,
                            new Action(delegate()
                        {
                            if (_deletedObject != null)
                            {
                                ContentPresenter cp = FindChildContentPresenter(_deletedObject);
                                if (cp != null)
                                {
                                    this._itemsHolder.Children.Remove(cp);
                                }
                            }
                        }
                        ));
                    }
                }

                UpdateSelectedItem();
                break;

            case NotifyCollectionChangedAction.Replace:
                throw new NotImplementedException("Replace not implemented yet");
        }
    }

    ///
    /// update the visible child in the ItemsHolder
    ///
    /// <param name="e"></param>
    protected override void OnSelectionChanged(SelectionChangedEventArgs e)
    {
        base.OnSelectionChanged(e);
        UpdateSelectedItem();
    }

    ///
    /// generate a ContentPresenter for the selected item
    ///
    void UpdateSelectedItem()
    {
        if (_itemsHolder == null)
        {
            return;
        }

        // generate a ContentPresenter if necessary
        TabItem item = GetSelectedTabItem();
        if (item != null)
        {
            CreateChildContentPresenter(item);
        }

        // show the right child
        foreach (ContentPresenter child in _itemsHolder.Children)
        {
            child.Visibility = ((child.Tag as TabItem).IsSelected) ? Visibility.Visible : Visibility.Collapsed;
        }
    }

    ///
    /// create the child ContentPresenter for the given item (could be data or a TabItem)
    ///
    /// <param name="item"></param>
    /// <returns></returns>
    ContentPresenter CreateChildContentPresenter(object item)
    {
        if (item == null)
        {
            return null;
        }

        ContentPresenter cp = FindChildContentPresenter(item);

        if (cp != null)
        {
            return cp;
        }

        // the actual child to be added.  cp.Tag is a reference to the TabItem
        cp = new ContentPresenter();
        cp.Content = (item is TabItem) ? (item as TabItem).Content : item;
        cp.ContentTemplate = this.SelectedContentTemplate;
        cp.ContentTemplateSelector = this.SelectedContentTemplateSelector;
        cp.ContentStringFormat = this.SelectedContentStringFormat;
        cp.Visibility = Visibility.Collapsed;
        cp.Tag = (item is TabItem) ? item : (this.ItemContainerGenerator.ContainerFromItem(item));
        _itemsHolder.Children.Add(cp);
        return cp;
    }

    ///
    /// Find the CP for the given object.  data could be a TabItem or a piece of data
    ///
    /// <param name="data"></param>
    /// <returns></returns>
    ContentPresenter FindChildContentPresenter(object data)
    {
        if (data is TabItem)
        {
            data = (data as TabItem).Content;
        }

        if (data == null)
        {
            return null;
        }

        if (_itemsHolder == null)
        {
            return null;
        }

        foreach (ContentPresenter cp in _itemsHolder.Children)
        {
            if (cp.Content == data)
            {
                return cp;
            }
        }

        return null;
    }

    ///
    /// copied from TabControl; wish it were protected in that class instead of private
    ///
    /// <returns></returns>
    protected TabItem GetSelectedTabItem()
    {
        object selectedItem = base.SelectedItem;
        if (selectedItem == null)
        {
            return null;
        }

        if (_deletedObject == selectedItem)
        {

        }

        TabItem item = selectedItem as TabItem;
        if (item == null)
        {
            item = base.ItemContainerGenerator.ContainerFromIndex(base.SelectedIndex) as TabItem;
        }
        return item;
    }
}

The TabControl template I usually use looks something like this:

Answer: It has nothing to do with the ObservableCollection. It's because the View for the Customer is reused instead that WPF creates a new View for every Customer.
You might have a look at the Writer sample application of the WPF Application Framework (WAF). It implements the TabControl for a tabbed MDI interface as well but doesn't suffer from the issue you mentioned in your post. The issue is solved in Writer by creating an own UserControl for every document 'tab'.
Comment: When I started with the MVVM pattern I have used the DataTemplate mechanism of WPF as well for wiring the View with the ViewModel together. But I ran into a few issues like the one you mention here. That's the reason why I wire them with MEF together. WPF just gets the Views (UserControls) and so I don't need the DataTemplate for this scenario anymore.
Comment: Thanks @jbe, I know that I could solve the problem using an ObservableCollection of UserControls, but I'd prefer to use an ObservableCollection of ViewModels if possible.  I've updated my question... let me know if you can give any input.  Thanks.
Answer: I believe this has something to do with binding mode- did you try {Binding Mode=OneWay}?
Also binding to any of the 'DataSource' objects will cause the same issue.
Im not sure if oneway binding will be the desired behavior you are looking for but i would start there.
Comment: I tried that, but it didn't work.  I've updated my question... let me know if you can give any input.  Thanks.


Bootstrap 5.2 Navbar Dropdown doesn't work

Question: I apologize for the topic! I've found many similar topics and advises, however nothing help. I want to create dropdown  menu inside the navbar. The code is:

    <link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">

    <link href="css/navbar.css" rel="stylesheet" />

                        About

                            One

                            Two

Answer: Change the "data-bs-toogle="dropdown" to "data-bs-toggle="dropdown".
Check the spelling of toggle.
Try this:

<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://email@example.com/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">

    <link href="css/navbar.css" rel="stylesheet" />

                    About

                        One

                        Two


Integrate vuex into express-vue

Question: Im using express-vue (https://github.com/express-vue/express-vue)
(A package that should do the ssr for me).
Now I wanted to integrate vuex into my project and I'm little confused on how to do that.
I can use the cdn link, but I dont know where I should put this code:
<code>const store = new Vuex.Store({
    state: {
       count: 0
    },
 mutations: {
    increment (state) {
        state.count++
    }
  }
})
</code>
(from here: https://vuex.vuejs.org/en/getting-started.html)
So that vuex is availible in every component(and mixins if possible) of mine.
(If you have a good suggestion on the usage of npm packages in express-vue I would be happy too, but as far as I know node-modules is not availible for express-vue)
Answer: It's not possible yet.
As their core team said:

Support for vuex and other plugins is coming in express-vue@5
It's been prematurely published so please don't use it just yet. But
  yes soon.
Comment: Thats unfortunate. Thought it was possible because I was able to integrate some features that supported cdn links. Do you have any idea when this update might be released?
Comment: I am sure as soon as possible
Comment: By the way, @telion, was my answer helpful?
Comment: well you answered the question^^. I wanted to use it to control the variables on the client. Its getting anoying to bind and emit them for every component, and I will need mixins also to have acces to them.
Comment: but Sorry I forgot to mark it as the answer. My bad.
Comment: Well, my suggestion is to use another variants to build server-side rendering with Vue.js
Comment: But, again, I understand that it will take a time to rewrite the project

Integrate vuex into express-vue


Is 1/2 inch OSB strong enough for subfloor

Question: We just found out that the subfloors in our rental property are only 1/2 inch thick OSB.  It has some moisture damage but we fixed what caused it and are replacing damaged ones.
We can't really afford to put down all new subfloors, and  I am either installing 5 mm LVP or possibly even a peel and stick.  Would a 1/2" OSB subfloor be sufficient for this?
Comment: I've removed the rant (though I get your pain) because it doesn't help the question, and have attempted to distill this down to the facts and the question. If you feel I've removed any relevant, important details please [edit] to reinsert them.
Comment: I _seriously_ doubt that's what you have. It wouldn't be legal in any modern jurisdiction. What's your evidence?
Comment: At least it wasn't particleboard ...
Answer: Half-inch OSB seems to be rated at 16 inch centers, but it's pretty much the minimum.
https://codes.iccsafe.org/s/IRC2021P2/part-iii-building-planning-and-construction/IRC2021P2-Pt03-Ch05-SecR503.2.1.1
Comment: Not as a sole subfloor. Maybe in conjunction with another layer.
Answer: I have had the same issue. Not with criminal tenants, but with the subfloor.
I hate OSB, but sometimes it's there and has to be used.  In one of my rentals I placed 4x8 sheets of 1/4 Durock over the OSB. glued and screwed. I taped the seams just to fill in the edges.  Then installed a 6 mil vapor barrier and the LVP.
Pricing on here is verboten, but I found a good quality LVP with a 5mm total thickness, for less than $2/ sq ft. US.
Comment: Pricing, as an example of how one method may be more economical than another isn't verboten in answers. Asking about pricing (especially for contractors) in the _question_ **is verboten**.


Symfony5 easyAdmin - vichUploader

Question: I'm with symfony5. I opted for the easyAdminBundle. In order to upload the images, I try to use vichUploaderBundle. The problem is that it only works once. For example for the Service entity, it only works when I create a new service (ex: seo, website or print). When I change the image of a service that already exists, it no longer works. I followed the tutorial on the official site ...
<code># config/services.yaml
parameters:
    app.path.website_images: /images

# config/packages/vich_uploader.yaml
vich_uploader:
    db_driver: orm
    mappings:
        website_images:
            uri_prefix:         '%app.path.website_images%'
            upload_destination: '%kernel.project_dir%/public%app.path.website_images%'

?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\HttpFoundation\File\File;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * @ORM\Entity(repositoryClass="App\Repository\ServiceRepository")
 * @Vich\Uploadable
 */
class Service
{
    [...]

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $image;

    /**
     * @Vich\UploadableField(mapping="website_images", fileNameProperty="image")
     */
    private $imageFile;

    /**
     * @ORM\Column(type="datetime")
     */
    private $updatedAt;

  [...]

}

# config/packages/easy_admin.yaml
Service:
    label:           'Service'
    class:           App\Entity\Service
    list:
        fields:
            - { property: 'title' }
            - { property: 'image', type: 'image', base_path: '%app.path.website_images%' }
    form:
        fields:
            - { property: 'title' }
            - { property: 'imageFile', type: 'vich_image' }
            - { property: 'content', type: 'fos_ckeditor' }
</code>

Symfony 5.02
EasyAdminBundle 2.x

Sometimes it works, but most of the time it doesn't ...
Answer: <code>public function setImage(string $image): self

=>

public function setImage(?string $image): self
</code>
The location error was at the setter level. You must add a question mark to accept null.

Symfony5 easyAdmin - vichUploader


count by on window function

Question: I have created this sqlfiddle which executes this query:
SELECT "emails".*
FROM (
    SELECT "emails".id, sender_contact_id, sender_user_id,
    rank() OVER (PARTITION BY "sender_contact_id" ORDER BY "sent_at" DESC) AS "contact_rnk",
    rank() OVER (PARTITION BY "sender_user_id" ORDER BY "sent_at" DESC) AS "user_rnk"
    FROM "emails"
    WHERE ("folder" = 'INBOX')
) AS "e"
INNER JOIN "emails"
ON ("emails"."id" = "e"."id")
WHERE ((contact_rnk = 1 or user_rnk = 1) AND folder = 'INBOX')
ORDER BY sent_at DESC;

The point of the query is to return only 1 row for each contact or user that has sent an email.
What is missing from the query is a count of the emails that have been sent for each partitioned user or contact.
I could do multiple with queries and join at the end e.g.
with main as (
  select blbah, etc.
),
cnt_users as (
  select count(sender_user_id) inner join main etc.
),
cnt_contacts as (
  select count(sender_contact_id) inner join main etc.
)
select main.*, cntusers etc.

But is it possible to include the count in the first query without having to use group by?
Answer: The rows may be counted inside each partition without GROUP BY, the trick being to use the proper framing.
For instance, the query could be modified as:
SELECT "emails".*, e.*
FROM (
    SELECT "emails".id, sender_contact_id, sender_user_id,
    rank() OVER (w1) AS "contact_rnk",
    count(*) OVER (w1 ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS contact_count,
    rank() OVER (w2) AS "user_rnk",
    count(*) OVER (w2 ROWS BETWEEN UNBOUNDED PRECEDING AND UNBOUNDED FOLLOWING) AS user_count
    FROM "emails"
    INNER JOIN email_participants ep
    ON emails.id = ep.email_id
    WHERE (folder = 'INBOX') and user_id = 220
    WINDOW
    w1 as (PARTITION BY sender_contact_id ORDER BY sent_at DESC),
    w2 as (PARTITION BY sender_user_id ORDER BY sent_at DESC)
) AS e
INNER JOIN emails
ON (emails.id = e.id)
WHERE ((contact_rnk = 1 or user_rnk = 1) AND folder = 'INBOX')
ORDER BY sent_at DESC

Then e.contact_count and e.user_count should contain the message counts for respectively each different sender_contact_id and sender_user_id.
Comment: @dagda1: sorry, sqlfiddle was down at the time of writing. Now fixed (moved window clause into the subquery)

count by on window function


The elif wont work when I try it and this wont work when it worked in my last code

Question: year_born = input('what year were you born? ')
year = (2019)
age = (year - int(year_born))
if age <= 18:
  if age <= 65:
    print('Here is your pensioners ticket.')
  print('Here is your child's fare ticket.')
else:
  print('here is your ticket.')

I tried and elif statement on "if age <= 65:" but it shows syntax error. this works in my last code bellow. so i'm not for sure what is wrong or what I could do to make this work correctly. the problem with this is it does not initiate the "print('Here is your pensioners ticket.')". thanks for the help love you all.
first_name = input('first name only: ')
if len(first_name) >= 5:
  if first_name[-1] == 'a':
    print('you won $1000!!')
  else:
    print('you did not win $1000')
else:
  print('you did not win $1000')

Comment: Please format the code properly.
Comment: You logic is off; a pensioner should be someone with age *greater* than 65, which cannot be someone whose age is less than 18.
Comment: I think you've confused `<` for `>`... If someone's age is less than 18, it's obviously less than 65, no need to check.
Comment: how exactly it is when I put it in format but it wont when i post??
Comment: Indent your code then check for where you are forgetting to type cast
Comment: You are making `year` a `tuple`, is there a reason for this?
Comment: @jab `(2019)` is not a tuple, `(2019,)` would be.
Comment: Correct, my mistake
Comment: @KianAlford what is the result of running this code, if not printing "here is your pensioners ticket"? What did you input when asked "what year were you born"?
Comment: i did this the other way so did not work in age 18 the opposite the the correct one. dont know why but.
Answer: The error is likely at print('Here is your child's fare ticket.') because you use ' without escaping it. Possible solutions:
print('Here is your child\'s fare ticket.')

Or
print("Here is your child's fare ticket.")

The way I would approach it:
year_born = input('what year were you born? ')
year = 2019
age = (year - int(year_born))
if age <= 18:
    print('Here is your child\'s fare ticket.')
elif age >= 65:
    print('Here is your old person ticket.')
else:
    print('here is your general adult ticket.')

Comment: @KianAlford well that was the syntax error, so clearly you did not properly fix it, or there were multiple errors. You can even see it is the error in your post because the text changes colors when it thinks the string is over.
Comment: @KianAlford No problem. We all started somewhere.
Answer: From a logic standpoint you want prisoners to be 65+ and children are 18 and below. Otherwise they get a regular ticket. If this is correct then I would use the following:
year_born = int(input('what year were you born? '))
year = 2019
age = year - year_born

if age >= 65:
    print('Here is your pensioners ticket.')
elif age <= 18:
    print('Here is your child\'s fare ticket.') #need to escape the backslash here btw
else:
    print('here is your ticket.')

As for the other code you want to check the last letter first, then see if the length is above 5:
first_name = input('first name only: ')

if first_name[-1] == 'a':
    print('you won $1000!!')
else:
  print('you did not win $1000')


couchdb : Depends: couchdb-bin (>= 1.6.1-0ubuntu4) broken packages

Question: I encountered a problem trying to install couchdb on my Ubuntu 14.10 (GNU/Linux 3.10.23-xxxx-std-ipv6-64 x86_64) server.
When I run  apt-get install couchdb,
I've got the following mistakes :
<code>The following packages have unmet dependencies.
     couchdb : Depends: couchdb-bin (>= 1.6.1-0ubuntu4)
     but it is not going     to be installed
E: Unable to correct problems, you have held broken packages.
</code>
I followed a lot of steps found on the net to try to fix it, but nothing worked...
I hope someone will be able to find out what's going wrong...
Thanks
EDIT:
Here are the steps I have already done :

I tried to use Aptitude, but it installed Couchdb 1.0.1 instead of 1.6.1
I tried to remove completely the installation using "apt-get remove couchdb couchdb-bin erlang-base erlang-base-hipe erlang-solutions" But the result was the same.
The problem occurs when I add the PPA of couchdb to install the last version. If I remove the .plist, installation works, but it installs the 1.0.1 version.
I tried all the possible solutions to update apt-get or to clean it...

Do you think that if I update my Ubuntu 14.10 to 15 it could fix the problem ?
Comment: Could you be specific about what steps you have already tried? Otherwise people are likely going to suggest things you know don't work. On that note, have you tried using `aptitude`?
Comment: @TheSchwa, I edited my question, thank you for the remark.
Comment: According to [Launchpad](https://launchpad.net/ubuntu/utopic/+source/couchdb) the `couchdb` version for Utopic is `1.6.0-0ubuntu4`. On my 15.10 installation, the package `couchdb` is version `1.6.0-0ubuntu7`. So neither of those meet the requirement `(>= 1.6.1-0ubuntu4)`. It sounds like a broken dependency. See if either of [the solution to this answer](http://askubuntu.com/q/696930/205638) work.
Comment: As I precised, I already tried both answers which are given in this post... :(
Comment: I have this problem too (for a long time).
Answer: Updating my Ubuntu release worked (I upgraded it from 14 to 15.10 doing do-release-upgrade).
Now I was able to install 1.6.0 couchdb version. Still have to look for installing the 1.6.1.


What is the best wire (material, construction and gauge) for a 30 meter wire telephone?

Question: I am asking about constructing a non-electric telephone made of two thin plastic cups (these seem to resonate the best) and wire between them to exchange secret messages with my neighbor across the fence.
I've looked into cotton but I've found negligible scientific evidence that this is the most effective engineering solution.
The wire will be fully free floating but support can be arranged along its route.
Comment: Science fair aka homework?
Comment: Supporting the wire will dampen or interrupt the sounds, a "tin can phone" must have the "wire" floating in free air, so the less it weighs the better.
Comment: Genuine DIY question about a common appliance. I haven't had any homework due for 8 years now (I am 31).
I've also done my research and couldn't google anything. Cotton wire sounds like a bad solution and there's no support to indicate it is even "above average" from all available strings and wires.
Comment: Google "tin can phone" there are many search results, including: https://en.m.wikipedia.org/wiki/Tin_can_telephone
Comment: @Tyson, thanks. I did but it did not provide any information about the qualities of the wire.
Answer: You want very stiff taut wire.  Otherwise you will have to pull it VERY tight to pull it to the limits of its springiness so the sound won't get dampened by that spring action.
Also preferably nonconductive.   Maybe something in the FRP/carbon fiber family.
My vote is for fiberglass electrician's pulling tape.   Nonconductive, stiff and mad tensile strength.
Comment: I'm afraid I can't vote this up but I will purchase some of this wire and perform benchmarking using a sound level monitor


Kubernates Node port services in on premise rancher cluster

Question:
I have 5 microservices in 5 pods and have deployed each service using specific port using NODE PORT service.
I have a UI app as one service inside another pod which is also exposed using node port service.

Since I can't use pod IP to access urls in UI app as pods live and die so deployed as nodeport service and can I access all 5 services inside UI app seamlessly using respective node port?
Please advise - is this approach going to be reliable?
Answer:
Yes, you can connect to those Node port services seamlessly.

But remember, you may need higher network bandwidth card and connection (to master nodes) if you get too much traffic to these services.
Also if you have a few master nodes, you can try dedicated master node-ip and nodeport for a service.(If you have 5 master nodes, each service is accessed from one master node's IP etc. This is not mandatory, you can connect to each service using any masterIP:nodeport)
Highly recommend to use load-balancer service for this. If you have baremetal cluster try using MetalLB.
Edit : (after Nagappa LM`s comment)

If its for QA, then no need to worry, but if they perform load test to all the services simultaneously could be a problematic.
Your code change means, only your k8 - deployment is changed, not Kubernetes service. k8 service is where you define nodeport
Comment: I have one master node,2worker nodes and in worker nodes I am deploying, actually we are exposing to QAs not external world.Thanks.We can redeploy as many times as we want without changing any ports, only code change,no more things to change in k8 cluster?


What is the distinction between sparse and dense graphs?

Question: I read it is ideal to represent sparse graphs by adjacency lists and dense graphs by an adjacency matrix. But I would like to understand the main difference between sparse and dense graphs.
Comment: (http://en.wikipedia.org/wiki/Dense_graph)  has enough information
Answer: Dense graph is a graph in which the number of edges is close to the maximal number of edges.
Sparse graph is a graph in which the number of edges is close to the minimal number of edges. Sparse graph can be a disconnected graph.
Comment: I think a graph with n vertices is considered to be sparse if it has O(n) or less edges.
Comment: Conversely, a graph with n vertices is dense if the number of edges is O(n^2)
Answer: As the names indicate sparse graphs are sparsely connected (eg: Trees). Usually the number of edges is in O(n) where n is the number of vertices. Therefore adjacency lists are preferred since they require constant space for every edge.
Dense graphs are densely connected. Here number of edges is usually O(n^2). Therefore adjacency matrix is preferred.
To give a comparison, let us assume graph has 1000 vertices.
Irrespective of whether the graph is dense or sparse, adjacency matrix requires 1000^2 = 1,000,000 values to be stored.
If the graph is minimally connected (i.e. it is a tree), the adjacency list requires storing 2,997 values. If the graph is fully connected it requires storing 3,000,000 values.
Comment: How adjacency list for 1000 vertices requires 2997 values? Can you elaborate more pls?
Comment: @SuryaTejaVemparala  sparse graph is considered a tree here. consider the tree as 1-2-3-4- .... - 1000, for every vertice from 2 - 999, there would be 2 entries, one for previous vertex and other for next one. First and last will have one entry each, and then extra space for all the keys in the adjacency list if constructed through Hashmap. I believe this can be reduced down to 1998 if used list of lists.
Answer: From Data Structures and Algorithms with Object-Oriented Design Patterns in C++
, p. 534, by Bruno P. Reiss:

Informally, a graph with relatively few edges is sparse, and a graph with many edges is dense.
Definition (Sparse Graph): A sparse graph is a graph G = (V, E) in which |E| = O(|V|).
Definition (Dense Graph) A dense graph is a graph G = (V, E) in which |E| = Θ(|V|2).
Answer: Main graph integral characteristics are number of vertices V and number of edges E. The relation of these two determines whether graph is sparse or dense (wiki page here).
The whole theory behind choosing graph in-memory representation is about determining the optimal access time vs memory footprint tradeoff, considering subject domain and usage specifics.
Generally you want to have O(1) access time (and thus store the graph as a dense adjacency matrix) unless you can't tolerate memory footprint, in which case you choose the most appropriate sparse matrix representation (wiki page here).
Answer: In mathematics, a dense graph is a graph in which the number of edges is close to the maximal number of edges. The opposite, a graph with only a few edges, is a sparse graph. The distinction between sparse and dense graphs is rather vague, and depends on the context.
Comment: Several examples of sparse graphs are:
Transportation and road networks where the intersections are vertices and roads are edges. For such networks, the number of roads is  not significantly larger than the number of intersections (in other words E~=c * V, where c is in the range of 2-3).
While in many cases real-world graphs are sparse, it is possible to create weighted graphs that are highly dense with the edge weight representing some sort of relationship - such as a large edge weight if two people visited the same store at the same time or had coffee at the same coffee-shop.
Comment: Another example might be to take a "sub-graph" of a sparse graph that represents a community of people that are highly connected.
Answer: If the number of the edges is close to the maximum number of edges in a graph, then that graph is a Dense graph. In a dense graph, every pair of vertices is connected by one edge.
The Sparse graph is completely the opposite. If a graph has only a few edges (the number of edges is close to the minimum number of edges), then it is a sparse graph.
There is no strict distinction between the sparse and the dense graphs. Typically, a sparse (connected) graph has about as many edges as vertices, and a dense graph has nearly the maximum number of edges.
Answer:
Adding to above answers, A Simpler explanation can be,

Dense Graph
If all vertices or nodes in a graph is densely connected (i.e. a node that connects with all neighbour nodes with all possible edges). Here possibly, total number of edges > total number of nodes.

Sparse Graph
Its an vice versa of dense graph, Here we can observe that a node or vertices is not fully connected to its neighbouring nodes (i.e. it has unconnected/remaining edges). Here possibly, total number of edges <= total number of nodes.
Answer: Sparse Graphs - Graphs with relatively few edges (generally if it edges < |V| log |V|) are called sparse graphs.
Dense Graphs- Graphs with relatively few of the possible edges missing (as compared to complete graph) are called dense graph.


How to ask "Are you sure?" before close JInternalFrame?

Question: I made a java swing application with JInternal frames. When I close a internal frame, it should show a pop message "Are you sure?" in a Option pane. How can i put event in the close operation of JInternal frame? Please help me.
Comment: Take a look at [InternalFrameListener](http://docs.oracle.com/javase/7/docs/api/javax/swing/event/InternalFrameListener.html)
Answer: Please see http://docs.oracle.com/javase/tutorial/uiswing/events/internalframelistener.html for information on how to write an InternalFrameListener. You can put all your code for the closing inside the internalFrameClosing(InternalFrameEvent e) method.
Then, simply add a new instance of your newly created InternalFrameListener to your JInternalFrame with the JInternalFrame method addInternalFrameListener, as you can see on the previous link.
Here's information on the addInternalFrameListener method: JavaDoc
Code:
public class InternalFrameEventDemo implements InternalFrameListener{
    JInternalFrame frame;
    public InternalFrameEventDemo() {
        frame = new JInternalFrame("Event Generator",
                                                      true,  //resizable
                                                      true,  //closable
                                                      true,  //maximizable
                                                      true); //iconifiable
        //so that you can decide whether to close it or not
        frame.setDefaultCloseOperation(JInternalFrame.DO_NOTHING_ON_CLOSE);
        frame.addInternalFrameListener(this);
    }
    public void internalFrameClosing(InternalFrameEvent e) {
        //YOUR CODE HERE
        int option = JOptionPane.showConfirmDialog(null, "Really Close?", "Exit", JOptionPane.YES_NO_OPTION);
        if (option == JOptionPane.YES_OPTION){
            //call dispose to really close it
            dispose();
        }
    }
    public void internalFrameClosed(InternalFrameEvent e) {

    }
    public void internalFrameOpened(InternalFrameEvent e) {

    }
    public void internalFrameIconified(InternalFrameEvent e) {

    }
    public void internalFrameDeiconified(InternalFrameEvent e) {

    }
    public void internalFrameActivated(InternalFrameEvent e) {

    }
    public void internalFrameDeactivated(InternalFrameEvent e) {

    }

    public static void main(String[] args) {
        new InternalFrameEventDemo();
    }
}

Comment: Not a problem, good luck with your implementation.
Comment: Is there a reason why you used a Listener, and not a Adapter?


Ubuntu 12.04 on Samsung Galaxy?

Question: I have Samsung Galaxy Pocket (full model name: Samsung Galaxy gt-s5300)
Is there way to install Ubuntu  properly on this device? If so, how to do so?
thanks.
Answer: I dont think so that's an good idea of doing it. U need to wait untill the Ubuntu becomes available for the tablets. Still there more than the rough edges not applicable in the ubuntu to be working on the Tablet. I installed it in Nexus 7 .. I am not satisfied with it. But i hope canonical along with mark can pull it back.. But my only worry is they need to pull back as soon as possible..
Kindly do it before this may (That means they should be ready with the ubuntu 13.04)

Ubuntu 12.04 on Samsung Galaxy?


Why is my Python code getting 401 access denied from the Microsoft Dynamics 365 CRM API?

Question: I am trying to download some data from a customer's Microsoft Dyanmics 365 CRM API. Below is my code written in Python 3.7, using MSAL (Microsoft Authentication Library) for Python.
import msal
import requests

class Downloader:

    AUTHORITY = 'https://login.microsoftonline.com/common'
    SCOPES = ["https://admin.services.crm.dynamics.com/user_impersonation"]

    def __init__(self, client_id, client_credential, refresh_token):
        self.client_id = client_id
        self.client_credential = client_credential
        self.refresh_token = refresh_token

    def download(self):

        application = msal.ConfidentialClientApplication(
            client_id=self.client_id,
            client_credential=self.client_credential,
            authority=self.AUTHORITY,
            token_cache=None)

        response = application.acquire_token_by_refresh_token(self.refresh_token, self.SCOPES)

        instances = requests.get(
            'https://globaldisco.crm.dynamics.com/api/discovery/v1.0/Instances',
            headers={'Authorization': 'Bearer ' + response['access_token']},
        )

        return response

When I run the download() method I successfully get a response that contains an Access Token but when I use it to GET instances I get back HTTP Status Code 401 Access Denied.
My question is: Why am I getting 401 Access Denied and how can I fix my code to get 200 OK?
More data:

client_id and client_credential identify a multi-tenant Azure App Registration I've setup. This app registration is not verified yet. It has these API Permissions (scopes) configured:

https://admin.services.crm.dynamics.com/user_impersonation
https://graph.microsoft.com/User.Read

refresh_token has been generated based on Quickstart: Add sign-in with Microsoft to a Python web app. The quickstart goes through setting up a small Flask web application where a person can sign in via Microsoft Identity and grant permission for my app registration to impersonate them when later accessing the Dynamics 365 CRM API. I've setup the Flask app to use my App Registration and the two scopes above.

Because my App Registration is not verified yet, I had an admin of the target tenet sign in via the Flask app, approve and give consent for my app registration to be used by the tenet org. I've tried both their refresh token and another non-admin person's refresh token. Both yield 401.

The tenet org (to which my customers' identities belong) is linked to a Dynamics 365 account.

Update:
When I view my app registration in my customer's (i.e. tenet's) Azure Portal under Enterprise Applications I can see the Common Data Service user_impersonation permission under the Admin consent tab but it's missing from the User consent tab.

I'm trying to figure out whether this might explain why users are denied access and how to add the missing permission to User consent.
Answer: Has the user been added to CRM? The identity you are using should still have full roles assigned within CRM. Someone should have added that app registration to the list of users in CRM. Settings->Security (change the list view to "Application Users") press "New", change the form from "user" to "Application User".
Set the Name, copy the application Id from the Application registration. The email can exist or not.


Why do most Create Account forms clear the password fields upon wrong validation?

Question: In most Create Account forms that I've used, when you enter in something wrong (username not long enough, passwords don't match, invalid email, etc.), it'll keep all the fields but erase the password field(s). Is there any real reason behind this? I can understand it if the passwords are causing the invalidation, but if the email address is the problem, why clear the passwords?
Answer: The simple rule is that a password should never be stored in a retrievable format.
To be able to leave the password fields as they are, the password would have to be stored somewhere locally in a readable format - somewhere like the browser cache or a cookie.  That is poor security as someone could later retrieve the password from one of these sources.

Jeff Atwood wrote an excellent blog post many years ago titled: You're Probably Storing Passwords Incorrectly.  It is mostly dealing with how you store passwords on databases, but the same rules apply for any storage system (even temporary storage).  The key points that he makes are:

Do not invent your own "clever" password storage scheme.
Never store passwords as plaintext.
Add a long, unique random salt to each password you store.
Use a cryptographically secure hash.
Comment: If the "ok" buttons uses AJAX or some client side validation (the latter might be dangerous though since it can be tampered with) and something is reported to be wrong, then the password could be left where it is - since the place where the password is "stored" in is the very textbox(es) that were used to start from. The password fields won't simply be refreshed - hence they can be left where they are.
Comment: -1: This is a purely technical answer, and not reasoned from the UX perspective. From the UX perspective,  @Brendon gives a convincing example of alternative designs that show it is not needed to make the user jump through the hoop of re-entering a password (and to add insult to injury, do that twice).
Comment: This is absolutely correct. If stackexchange allowed some form of cross-posting, I would immediately re-post this to security.stackexchange.com
Comment: @HenrikEkblom There is the additional use case where a person submits a form, and does something else, thinking that it has validated.  If the password remains on the screen there, you are exposing them to unnecessary security risks.
Comment: @André Could you please explain how security is not part of UX?
Comment: I am not saying that security can't be an aspect to consider for UX, but I _am_ saying that your answer only contains _technical_ considerations, and says nothing on how that impacts the end user. You make it sound like in order to work in a secure way, the only option is to indeed clear the password fields. That is simply not the case.
Comment: @André Perception of security is as real (if not more real) an issue to UX as security.  If a user sees that you aren't clearing the password, what makes you think they will automatically assume that whatever you've done is secure?  I most definitely wouldn't if a site did that, as it is the most logical explanation.
Comment: Of course perception of security is a UX consideration. But _perception of_ security isn't identical to real security. I doubt your assessment that users will find alternative solutions non-secure. I'd like to see some evidence for that. What makes you think that users will even connect the fact that they need to re-enter the password fields with security? And what makes you so sure that they value that perceived security (it doesn't say much about it in the end) above the ease of use of the system?
Comment: @André there are many examples of new products that failed due to incorrect perception issues, or succeeded because the perception was that they were better, even when they weren't.
Answer: As JohnGB said, this is really a security precaution. However, there is an alternative way which is usable and secure at the same time. Rather than sending back the password mypassword, you can:

Send back a hidden field indicating the password is saved on the server (hashed, of course).
In the password field, assign the value ********.
The user will see ******** in the password field. If the user attempts to change the password, clear the field and prompt for a new password (change the hidden field indicator).

This will obviously require client-side scripting. Alternatively, you can replace the password field with Password: ******** and add new fields for New Password and Confirm New Password. Then you only update the server-stored password if the user enters a new password.
Other than the password length being different, the user will only see the obfuscated form and will assume that their actual password is in the field. To this extent, their behaviour does not change.
One issue with this approach is that users cannot see their passwords so will be unable to use the show password option, if you provide it. One possibility is disabling the field with a 'Change password' button to allow the user to enter a new password.
Comment: Interesting ideas.  I'm interested to know what key you would use in the database if there is no username to associate the password with (yet).  Also, can you point to any examples that have implemented this?
Comment: @JohnGB: I'd probably store it (already hashed and salted) in a temporary, time limited store keyed against a session token or something like that. But again: that's a technical consideration, not a UX one.
Comment: +1. I really appreciate the effort you put into this. I have never seen any of this implemented, but it sounds like a massive improvement to just deleting the password "for security reasons". Security does not demand me typing in the same information multiple times, it just needs a bit more thought and work as you clearly show. In fact, I'd argue your approach to be more secure than requiring re-typing the password.
Comment: @André Technical feasibility is a UX consideration.  I've never seen this implemented, and I can think of many situations where this may be problematic.  So I'd still like to see an example of it implemented to test whether it fails or not under certain circumstances.
Comment: @JohnGB: Well, I guess we disagree there. Not everything is UX, otherwise the term becomes meaningless. It is up for the engineers to determine if a proposed solution is technically feasible, not for UX designers. And yes, of course it needs testing and a proper review from a security specialist: yet another field that is relevant for choosing the end solution. UX isn't everything, but for me from a UX perspective Brendon is thinking in the right direction.


Libsvm alyways predicting the same class

Question: I'm using Libsvm to resolve a binary classification problem. My dataset has ~50K attributes and 18 samples. I'm using a leave one out validation (training on 17 samples and test on the remaining sample). I'm normalizing the data by using:
svm-scale -s scaling_parameters Train$i > TrainScaled$i
svm-scale -r scaling_parameters Test$i > TestScaled$i

the training and the prediction is done as:
svm-train -s 0 -c 5 -t 2 -g 0.5 -e 0.1 TrainScaled$i model
svm-predict TestScaled$i model predicted.out

The model always predict the same class (majority one). So I obtain 75% accuracy, but the model is useless because it always predict the same class for each sample. I tried different type of kernels and paramenters but I still have the same result. What could it be? Are the data so hard to "divided" by the hyperplane?
Comment: My dataset has ~50K attributes and 18 samples I think you need more sample to train a model, you can try to analysis is there any feature in the 50K dimensions will help in discriminate the two class in you sample
Comment: I tried to apply a feature selection but nothing changed, even applying a drastic reduction to only 100 attributes
Answer: Its likely that given the ratio of features to classes, that your algorithm may be overfitting your input even with a significant amount of regularization.  Have you tried using dimensionality reduction techniques such as PCA and working with a smaller number of features?  You could also try some sort of feature selection algorithm to get a small subset of features.
Comment: I tried to apply a feature selection but nothing changed, even applying a drastic reduction to only 100 attributes
Comment: Try training with one feature at a time and see what happens
Comment: Even with one feature...always predicting the same class (majority class)
Comment: Is it possible that the features have no signal?
Answer: I have encountered the same problem in my application, I used libsvm in my c++ project to perform binary classification, but it always predicts only one class for all samples.
The followings are some information about my application.
(1) I have 260 training samples in total and set 80% for train and cross validation, and 20% for test.
(2) While number of my features is 7218, which is much bigger than the sample number.
(3) For binary classification, my class labels are set as 0 and 1.
After repeated trials, I found that the failure of SVM classification in my application is primarily caused by the inefficiency of used features, which makes the overfitting of SVM classification model, especially when there are large amounts of features.


Ember: use this.get() in a validation function

Question: I have a date validator for an input field:
export default Ember.Component.extend({
moment: Ember.inject.service(),
dateValidation: [{
    message: 'invalid date',
    validate: function(inputDate) {
      if (!inputDate) {
        return true; //allow empty date
      }
      return this.get('moment').moment(inputDate, 'YYYY-MM-DD', true).isValid();
    }
  }],
});

I use ember-moment to validate the date. Usually I use this.get('moment').moment(...) but in the function this.get() is not defined (the get() function is not defined, because this refers to the validator function, not to the ember component, which have got a get() function).
I know that this refers to the function instead of my component, but how can I fix it? Using Ember.get() didn't work for me.
I am using ember-paper and the paper-input has got a customValidations-attribute which has to be an array (dateValidation in my case)
e.g:
{{paper-input
   type="date"
   value=atDate
   onChange=(action (mut atDate))
   customValidations=dateValidation}}

Comment: Hi Ben. `this.get` is undefined, or `this.get('moment')` is undefined?
Comment: @vothaison this.get(), also updated question
Comment: I think the problem is in the code that uses dateValidation. If you have control over that code, you can past `this` (component instance) into each `validate()` call.
Answer:
First option like @vothaison mentioned in comments, you can pass this reference to validation method.
You can inject moment inside your object definition.
export default Ember.Component.extend({
moment: Ember.inject.service(),
dateValidation: [],
init() {
    this._super(...arguments);
    var objectValidation = {
        message: 'invalid date',
        myMoment: this.get('moment'),
        validate: function(inputDate) {
            if (!inputDate) {
                return true; //allow empty date
            }
            return this.get('myMoment').moment(inputDate, 'YYYY-MM-DD', true).isValid();
        }
    };
    this.get('dateValidation').pushObject(objectValidation);
}

});
Comment: @vothaison & kumkanillam: I cant pass a reference of this to the function because it will be called from the template every time the value(date) from input field changes.
Comment: your way is working, but in my opinion it is a bit bad coding. Just having the dateValidation array without using init() would be better
Comment: You can pass `this` reference from template just like passing arguments to action in template. why this structure `dateValidation: [{}]` is required ?
Comment: it is required by ember-paper. I updated the question
Comment: Acutally in my app, I am using `moment` without importing and injecting as service ?. can you try it directly by removing injecting service? ie., `moment(inputDate, 'YYYY-MM-DD', true).isValid()`
Comment: I know that this will work but it will cause to use the global moment object and in ember-cli there will be a js hint saying moment isnt defined. Also see the readme on github https://github.com/stefanpenner/ember-moment
Comment: the function would be working, but there is a jshint error, saying 'moment is not defined'.
Comment: you can ignore jshint error for moment. if you dont want this to be listed then you can add `"moment":true` to `.jshintrc` file located in root of application directory
Answer: I'm not in a position to test this, but a simple bind looks like it should fix the problem:
export default Ember.Component.extend({
moment: Ember.inject.service(),
dateValidation: [{
    message: 'invalid date',
    validate: function(inputDate) {
      if (!inputDate) {
        return true; //allow empty date
      }
      return this.get('moment').moment(inputDate, 'YYYY-MM-DD', true).isValid();
    }.bind(this)
  }],
});

Comment: sorry, this isnt working. Same error: 'TypeError: this.get is not a function(…)'
Comment: Is there any chance you can get an Ember Twiddle of the code posted so we can have dig into the code?


Prove $O(2)$ is non-abelian?

Question: $$O(2) = \{Q\in \mathbb{F}^{2\times 2} | Q^TQ= QQ^T=I\}$$
What is the most elegant way to prove that $O(2)$ is non-Abelian?
Here is my thinking: I know that $O(2)$ can be generated by reflections and moreover two reflections result in a rotation. Rotations commute with each other, but reflections do not
$$
ROT(\theta/2)=
\begin{bmatrix}
\cos\theta & \sin\theta \\ \sin\theta & -\cos\theta
\end{bmatrix}
$$
It suffices to show that $$ROT(\phi/2)ROT(\theta/2)\neq ROT(\theta/2)ROT(\phi/2)$$ for some $\phi,\theta\in (0,2\pi)$.
$$
\begin{bmatrix}
\cos\phi & \sin\phi \\ \sin\phi & -\cos\phi
\end{bmatrix}
\begin{bmatrix}
\cos\theta & \sin\theta \\ \sin\theta & -\cos\theta
\end{bmatrix}
=\begin{bmatrix}
\cos\phi\cos\theta + \sin\phi\sin\theta
&
\cos\phi\sin\theta-\sin\phi\cos\theta
\\
\sin\phi\cos\theta-\cos\phi\sin\theta
&
\sin\phi\sin\theta+\cos\phi\cos\theta
\end{bmatrix}
$$
$$
\begin{bmatrix}
\cos\theta & \sin\theta \\ \sin\theta & -\cos\theta
\end{bmatrix}
\begin{bmatrix}
\cos\phi & \sin\phi \\ \sin\phi & -\cos\phi
\end{bmatrix}
=\begin{bmatrix}
\cos\phi\cos\theta + \sin\phi\sin\theta
&
\sin\phi\cos\theta-\cos\phi\sin\theta
\\
\cos\phi\sin\theta-\sin\phi\cos\theta
&
\sin\phi\sin\theta+\cos\phi\cos\theta
\end{bmatrix}
$$
We see that indeed the two matrices do not commute since their top-right and bottom-left elements switch signs.

My question: Is there a purely algebraic proof that does not need geometric consideration? If not, what is the most common proof of this result?
Comment: All you need to show is that $gh \ne hg$ for a *single* pair $g,h \in O(2).$ Try some simple ones!
Comment: In fact $O(2)$ is abelian whenever $\mathbb{F}$ has characteristic $2$.
Comment: Didn't you just say it yourself. You can expand $O(2) = Rot(\phi)+Ref(\theta)$ which you can now apply with the knowledge of how they work. Or do you want to see a proof why rotation don't commute?
Comment: @MichaelParis I was wondering if there was a proof that followed simpily from the fact that $Q^TQ=QQ^T=I$ without any geometric considerations.
Comment: In some sense there cannot be a purely algebraic proof that works over any field, because if $\mathbb{F}$ is the field with two elements then $O(2)$ is the cyclic group with two element.
Comment: One contradiction will do, there are obviously instances where commutativity will hold ($\phi=\theta-\pi n$, $n\in \mathbb{Z}$) but if you show one contradiction, the group isn't Albelian. (You can just pick a  $\phi$ & $\theta$ that don't satisfy the above.)
Answer: Take for example
$$\begin{pmatrix}1&0\\0&\!-1\end{pmatrix}\begin{pmatrix}0&1\\1&0\end{pmatrix}=\begin{pmatrix}0&1\\\!-1&0\end{pmatrix}\neq\begin{pmatrix}0&\!-1\\1&0\end{pmatrix}=\begin{pmatrix}0&1\\1&0\end{pmatrix}\begin{pmatrix}1&0\\0&\!-1\end{pmatrix}$$
...over any field with characteristic$\,\neq2\;$
Comment: @ArnaudD. Thanks. Your comment came while I was adding the info.

Prove $O(2)$ is non-abelian?


Laraval Breeze: page or props is not defined in Vue component

Question: Goodmorning,
I'm building a web app with Laravel Breeze. Which uses Laravel, Vue.js and Inertia.js.
Im pretty far already, but I'm not able to use my data that I pass from my controller.
My controller looks like this:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Inertia\Inertia;

use App\Models\Language;
use App\Models\Section;
use App\Models\SectionBlock;
use App\Models\BlockField;

class OverviewController extends Controller
{
    public function index()
    {
        $languages = Language::orderBy('id', 'asc')->get();
        $sections = Section::orderBy('id', 'asc')->get();
        $sectionBlocks = SectionBlock::with('section')->orderBy('id', 'asc')->get();
        $blockFields = BlockField::with('sectionBlock.section')->orderBy('id', 'asc')->get();
        return Inertia::render('Overview', [
          'languages' => $languages,
          'sections' => $sections,
          'sectionBlocks' => $sectionBlocks,
          'blockFields' => $blockFields,
      ]);
    }
}

?>

Then my Overview.vue page looks like this:

<template>

    <AppLayout>

This is my main layaout for this page!

{{ JSON.stringify($page.props.languages, null, 2) }}

    </AppLayout>
</template>

However, when I use $page.props.languages inside of my template, it works perfectly. I can see the Languages output data on my page:

But in the console, I still get an error that $page is not defined:
Overview.vue:10 Uncaught (in promise) ReferenceError: page is not defined
    at Overview.vue:10:5

Also when I use props.languages, page.languages.
Does anybody know how I use my props that are passed from my controller on my page?
Answer: If I'm not wrong, the problem here is how you use the $page object.
The $page object can only be used inside the <template></template> just like the $props, $attrs or $data in vue:
<template>
    {{ $page.props.languages }}
</template>

If you want to access the content of $page inside the  you need to use the usePage().

you can also explicitly declare the data you pass from the controller as a props

<template>
    {{ languages }}
</template>

Controller Data using defineProps
How to properly use the $page object


Why doesn't my camera work when there's a kernel module for the driver?

Question: I have a Lenovo Miix 510. That machine has an ov2680 CMOS sensor for one of its cameras. There's been an ov2680.c in the Linux kernel for a little while, and that's definitely translated into a driver that I can find:
djrscally@valhalla:/lib/modules/5.4.0-37-generic$ find . -name *2680*
./kernel/drivers/media/i2c/ov2680.ko

and even modprobe and lsmod successfully:
djrscally@valhalla:/lib/modules/5.4.0-37-generic$ sudo modprobe ov2680
djrscally@valhalla:/lib/modules/5.4.0-37-generic$ lsmod | grep ov2680
ov2680                 24576  0
videodev              184320  1 ov2680
mc                     40960  2 videodev,ov2680

And that translates to a /sys/bus/i2c/devices/i2c-OVTI2680:00 directory. So it's at least partially working...but as far as I can tell never actually grabbing the device. For example dmesg | grep ov2680 returns nothing at all, and starting Cheese simply tells me "There was an error playing video from the webcam".
What's going on? Device has a driver, why isn't it working?
Answer: Do you have "access" (the file permissions kind of "access") to /dev/video?
ls -l /dev/video

will show you.
sudo adduser $USER $(stat -G /dev/video)

followed by logout/login will give you "group" access to /dev/video.
Comment: Thanks; I've tried that, I definitely have permissions to the video devices as a member of the video group, but no dice.
Answer: Answer: the existing driver isn't designed for an x86 platform, and is intended to be discovered via i2c matching, so the device is never paired to the driver. sysfs directories for the devices are not created by the driver; just by the subsystem following instructions from ACPI.
Changing the driver to perform ACPI matching allows it to be found, but it's not functional as a driver currently.
Comment: Hi, could you please detail in your answer, how you did "Changing the driver to perform ACPI matching", and whether current kernels 5.9+ change something? I have a front and rear camera on an Intel-based tablet that i can see the ACPI nodes for them in /sys/, but no v4l devices. Thank you
Comment: @AlexStragies Hello - Kernel 5.9 doesn't change anything, but actually I and others have done a bunch of work on updating the kernel to fix the problem we were having that stopped this working. It's quite a niche issue though; if you tell me the model of your device I'll check if it's in scope.
Comment: @Dan Scally: Would a Lenovo Miix 310 be part of the devices for which you've found a workaround?
Comment: @Lorenz late reply; sorry. Not at present, but we can probably do it. If you can make a post at https://github.com/linux-surface/linux-surface/issues/91 I can collect the info we need to see what needs to be done


Swift: How do I print out the value of a dictionary key inside a string expression?

Question: For some reason, I just can't make this expression work:
let expandedBio: Dictionary<String,AnyObject> = ["name":"Saurabh", "profession":"developer", "language":"java", "employed": true]

if let employed : AnyObject = expandedBio["employed"] {
    println("\(expandedBio[\"name\"]) is not available")
}

How do I output the println statement? I get the error
Unexpected "" character  error in string interpolation

How do I do this right?
Comment: This problem is solved in swift 2.1
Answer: In current version of Swift you have to put value in its own constant/variable first, then use that.
if let employed : AnyObject = expandedBio["employed"] {
    let t = expandedBio["name"]
    println("\(t) is not available")
}

Comment: I had to use `let t : AnyObject? = expandedBio["name"]`
Comment: not necessarily but recommended for a better readability.
Comment: While the "if let employed" already expects that "employed" might be nil (and so can handle that situation), the simple assignment of "t" might result in a nil value -> "Because it is possible to request a key for which no value exists, a dictionary's subscript returns an optional value of the dictionary's value type." -> Thus you should make that optional clear by defining t as "AnyObject?"
Comment: This problem is solved in swift 2.1


JSON Exception sending data

Question: Error:
Value <title>Apache of type java.lang.String cannot be converted to JSONObject
org.json.JSONException: Value <title>Apache of type java.lang.String cannot be converted to JSONObjectat org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONObject.<init>(JSONObject.java:158)
at org.json.JSONObject.<init>(JSONObject.java:171)
at com.avilyne.android.MainActivity.handleResponse(MainActivity.java:107)
at com.avilyne.android.MainActivity$WebServiceTask.onPostExecute(MainActivity.java:216)
at com.avilyne.android.MainActivity$WebServiceTask.onPostExecute(MainActivity.java:1)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)

Code:
public void handleResponse(String response)
{
    EditText edFirstName = (EditText) findViewById(R.id.first_name);
    EditText edLastName = (EditText) findViewById(R.id.last_name);
    EditText edEmail = (EditText) findViewById(R.id.email);

    String firstName=edFirstName.getText().toString();
    String lastName=edLastName.getText().toString();
    String email=edEmail.getText().toString();

    edFirstName.setText("");
    edLastName.setText("");
    edEmail.setText("");

    try
    {

        JSONObject jso = new JSONObject(response.toString());

        String jfirstName = jso.getString(firstName);
        String jlastName = jso.getString(lastName);
        String jemail = jso.getString(email);

        edFirstName.setText(jfirstName);
        edLastName.setText(jlastName);
        edEmail.setText(jemail);
    } catch (Exception e)
    {
        Log.e(TAG, e.getLocalizedMessage(), e);
    }
}

Comment: `JSONException: Value ` You are not getting the JSON for some reason, you are reaching an HTML page
Comment: So how do I solve the problem
Comment: Well At least you should find a way to log the response before attempting to parse it
Comment: I tried that and the response that is going is printed as org.apache.http.message.BasicHttpResponse@414dd928
Comment: thats not it, you need to see if you app can even reach the url, This could be a 404 not found page because your response contains html. You should run the script in your browser or something to make sure it is correct
Comment: I checked the url in the browser the url is reachable and working . It is the problem with the response string
Comment: what is the server side language, share that script
Comment: http://avilyne.com/?p=105

PersonResource.java &Person.java are the server side classes
Comment: Have you tested creating a request outside the application using something like Postman? http://www.getpostman.com/
Comment: I had solved the error their was the error with the url i was using
Answer: The logs tell you the reason:
Value <title>Apache of type java.lang.String cannot be converted to JSONObject

Strip the html tags to get the raw Json string, and pass it to JSONObject constructor.

Raw Json string looks like this:
{
    "glossary": {
        "title": "example glossary",
        "GlossDiv": {
            "title": "S",
        }
    }
}

Comment: How excatly do I do that
Comment: Yeas I tried to check the string which is passed using Log.d(); it has printed the html tags ... how to convert that to JSON string
Comment: Do you have that full string which is returned?

JSON Exception sending data


"Use of plus() is ambiguous" error

Question: I am trying to write a function which takes two numbers and prints out their sum.
#include <iostream>

using namespace std;

int plus(int, int);

int main () {
 int a, b, result;
 cout << "2 numbrs";
 cin>>a>>b;
 result = plus(a,b);
 cout << result;
 return 0;
}

int plus(int a,int b) {
 int sum;
 sum = a+b;
 return sum;
}

and error I get:
use of `plus' is ambiguous

It´s my first C++ program and in fact I am getting blind finding an error.
Comment: We need to declare all-out war on `using namespace std;`.
Comment: @Jac08H Well that is kinda my point... If you read an "explanation" and it doesn't explain why it is a problem, then it really isn't a "good explanation".
Comment: @FredLarson Is curious how almost all introductory programming books/tutorials employ

         using namespace std;
without properly explaining what that means, and when you should actually use it. (Most of the time you shouldn't)
Comment: In fact I read good explanation what is happening when using using namespace std, but I didn´t realize that can cause this problem.
Answer: Either do
result = ::plus(a,b);

Or rename the function. This is a good lesson on why using namespace std is not considered good practice.
Comment: @Jac08H Read http://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
Comment: @Jac08H There's no need to marked your question as fixed. You can just accept the appropriate answer.
Comment: `using namespace std` is considered bad practice only in header files, and it's OK in implementation files. (because it does not ooze into other modules) `using namespace std` is OK here. The real problem here is that the `plus` function is uselessly reinventing functionality, and uses a common word to do so, and this word happens to already be loaded with semantics by the Standard Library. I'd advocate to either directly use operator `+` instead of defining a function, or to define the function in the project's namespace.
Answer: There is already a function object in the std namespace called plus. Because of using namespace std; this std::plus is put in the global namespace, which is also where your plus() is named. When you attempt to call your plus() the compiler can't tell whether you are referring to std::plus or your plus() because they are both in the global namespace.
You have the following options:

Remove using namespace std; (you'll then need to qualify other functions in the std namespace -- e.g. std::cout).
Put your plus() in its own namespace (say, mine), and call it using mine::plus(a, b).
Call your function with ::plus() as suggested (assuming you don't put it in its own namespace).
Rename the function so that there is no name collision.
Comment: `std::plus` is not a function, it's a function object. If you want to call it, you need to do `std::plus()(a,b)` or `std::plus{}(a,b)`.
Comment: @LaurentLARIZZA Fixed. Thanks.

"Use of plus() is ambiguous" error


How to pass the email id that to be synchronized into create event calendar in android?

Question: How to pass the mail id of the calendar that to be synchronized into the create event through email?
I have a spinner that shows the list of accounts to be synchronized as below picture. Now, as usual passing title,description to create event in calendar application, i use following code.
<code>ContentValues values = new ContentValues();
    values.put("calendar_id", 1);
    values.put("title", title1);
    values.put("allDay", 0);
    values.put("dtstart", settime);
    values.put("dtend", cal.getTimeInMillis()+60*60*1000);
    values.put("description", desc1);
    values.put("???????", mail_id);
    values.put("???????", participant_mail_id);
    values.put("visibility", 0);
    values.put("hasAlarm", 1);
    event = cr.insert(EVENTS_URI, values);
</code>
What should i use to pass the key to insert email id and participant id? Any Help is really appreciated. My screen shot goes below.
Answer:
How to pass the mail id of the calendar that to be synchronized

The event is linked to a calendar by the "calendar_id". To get the "calendar_id" you should query for all the user's calendars and then search results for name in which you are interested. Here is a tutorial which should help: Working with the Android Calendar
Alternatively, you can create an event and then let the user choose to which Calendar the event should be added: Adding Calendar event through Intent
Comment: Here there is no code to insert the synchronizing attendee mail id and participant mail id into the calendar event?


how to run multiple instances of elasticsearch on one host

Question: I have several machines each with 128 GB of ram, each host is running a single instance of Elasticsearch.
I would like to run another data node on each host and allocate around 30 GB to the jvm heap.
I know I have to create a separate config file .yml and data directory..etc. My question is do I need to modify the service wrapper so that each node will be started/ stopped seperatly?
I am running ES version 1.3 on Centos 6.5
thank you
Comment: Because of [this](http://www.elasticsearch.org/guide/en/elasticsearch/guide/current/heap-sizing.html#compressed_oops), @MattBall.
Comment: jvm Garbage collection is more efficient when heap is < 32 GB
Comment: @Yasir - you'll need to copy `/etc/init.d/elastcsearch` to `/etc/init.d/elasticsearch2` to set up the additional service and modify the file as I described. Also lookup **chkconfig** to see how to automatically start the service when your server starts.
Comment: Why do this instead of running bigger single ES JVMs per host?
Comment: By service wrapper do you mean the init.d script?  if so, yes it makes sense to have one init.d script for each node - duplicate the file for each node and modify the sysconfig, lock file and pid lines.
Comment: Ah – your question didn't initially include the 128 GB figure.
Comment: possible duplicate of [Multiple nodes in ElasticSearch](http://stackoverflow.com/questions/13477303/multiple-nodes-in-elasticsearch)
Comment: @Olly Cruickshank I currently use sudo service elasticsearch start , which starts the first instance, I wanted to know whether I will need somthing like sudo service elasticsearch2 start to start the second node.
Comment: thanks Paul Sanwald that is a good link, but it does not  show how to start the different instances as a service. it shows how to run each node manually.
Comment: thanks Olly, I have got the file in /etc/rc.d/init.d/elasticsearch but not sure where the parameters are passed in for the es_config, es_home etc on this line;  `daemon --user $ES_USER --pidfile $pidfile $exec -p $pidfile -d -Des.default.path.home=$ES_HOME -Des.default.path.logs=$LOG_DIR -Des.default.path.data=$DATA_DIR -Des.default.path.work=$WORK_DIR -Des.default.path.conf=$CONF_DIR`
Answer: You need to prepare two elasticsearch.yml config files to configure settings accordingly and specify these files when startup up the two nodes.
bin/elasticsearch -Des.config=$ES_HOME/config/elasticsearch.1.yml
bin/elasticsearch -Des.config=$ES_HOME/config/elasticsearch.2.yml

At least the following should be set differently for the two nodes:
http.port
transport.tcp.port
path_data
path_logs
path_pid
node.name

The following needs to point to the other in both files to allow the nodes to find each other:
discovery.zen.ping.unicast.hosts: '127.0.0.1:9302'

EDIT: the property is now deprecated, look at : https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-discovery-settings.html
See this blog and this discussion
Comment: why should the `cluster.name` be set differently?
Comment: you are right, that is not useful, I have adjusted the answer.
Answer: elasicsearch.yml-1
cluster.name: test
node.name: node-1
path.data: /Users/musab/Desktop/elasticsearch/data
path.logs: /Users/musab/Desktop/elasticsearch/logs
node.max_local_storage_nodes: 4

elasicsearch.yml-2
cluster.name: test
node.name: node-1
path.data: /Users/musab/Desktop/elasticsearch/data
path.logs: /Users/musab/Desktop/elasticsearch/logs
node.max_local_storage_nodes: 4


Detecting when an image intersects a certain color?

Question: I am 11 years old, and I program with Java, HTML, and CSS. Well what I have is a game, and its a Minecraft 2D Platformer.
Well I have some water to the side, and what I want to do is when the player intersects that water, I want it to slow down. Here is a example if there was a method to do this, in case you still don't understand my goal.
<code>if (player.intersectsColor("0026FF"))
    playerSpeed = 2;
else
    playerSpeed = 3;
</code>
Comment: Noah, I'm sorry other users here are downvoting you instead of offering up advice or asking more clarifying questions. Are you asking whether Minecraft has such a method as intersectsColor, or are you asking if this would be a proper way to do it if the method did exist?
Comment: @BrianReindel the code that i added was the example if such a method existed in the `Image` class. What I am asking is how do I execute code when the `Image` `player` intersects some color, in this case, blue with the color code of 0026FF. What I am wanting is for when the player goes into the water (0026FF), then decrease the playerSpeed integer by one. the reason i say `playerSpeed = 2` instead of `playerSpeed--` is because this is going to be running in a loop, and what it would do is subtract to the one from it every millisecond spent in the water.
Comment: You may find that you'll have a greater response over at http://gamedev.stackexchange.com/ or even on one of the communities for Minecraft https://minecraft.net/community. It seems more specific to Minecraft than it does to Java.
Answer: I suggest you represent the water not by its color but by its location.  That way you can check whether the player is in a "tile" representing water, and adjust the speed accordingly.
This you can do with simple comparison on the x/y coordinates (adjusted for the size of the "tile"/"player")
If you don't have nice meshy tiles, but curves/polygons, you will need to read up on geometry and how to calculate (possibly curved) line intersection.  The exact algorithm will depend on the curve used.
The reason I discourage you from using the color itself for the intersection many twofold:

"Intersecting" on a single color limits your ability to dynamically color the terrain/objects later
You cannot have two different terrain.object type with the same color
Having the color (e.g. brown) of the terrain/object does not tell you which blue terrain/object the player ran into (e.g. is it the first or the second chest?)

If you really want to represent the terrain with colors, you can translate the players in-game coordinates to screen coordinates and see what color pixel you have at that coordinate on the screen (before the player was rendered on the scene), but this is messy.
Comment: Ok, well I put the water on the background image, and its curved, thats what im needing help on


svn - How to commit changes "in between two revisions"?

Question: The question:
How do I commit changes "in between two revisions"?
I'm using quotation marks because obviosly you cannot really commit anything between two revisions - they already are in repository.
The long story, i.e. why do I need this?
The question might sound awkward at first but here's a real life scenario I did encounter in my work.
We are committing development-time changes to development branches (or 'feature branches', fb's, as we also call them) and when work is done we merge to trunk.
You know, the basic workflow.
From trunk we release our SW, and we agree to have a code freeze certain days before actual release.
Now, I was foolish enough to trust our release candidate (RC) built from trunk is good since all automated tests had passed and committed a merge to trunk before we actually released the SW. And removed the feature branch.
Let's say the release candidate was in revision 42 and the version of SW we release is v1.0.3. So, r42 is RC for release v1.0.3.
So, RC looked good but before we released the SW I committed r43 to trunk. All tests in CI passed so I went and deleted branch fb14 (revision 44).
Turned out that RC wasn't good after all and needed fixing, but v1.0.3 must not contain feature 14 (implemented in fb14), i.e. r43.
The same in a sort of illustrated form:
==r42=======r43
      ^    /
      |   /
      | fb14
      |
commit fix there to get new RC

So I need to bring r42 back, commit something and then bring r43 back.
Ok, this is easy, right? Roll back to r42:
svn merge -r HEAD:42 .
svn commit -m "Reverted back to RC of v1.0.3"

Implement the needed fix and
svn commit -m "Fixed b0rken feature for v1.0.3"

Then we'll release the SW and I'll bring r43:
svn up
svn merge -c 43 .

But wait, this doesn't do anything! I went and deleted branch fb14 so do I need to dig that back from svn and merge it to trunk again? Surely I must be able to bring r43 somehow back.
So I kind of want this:
    roll back to r42
     -------------
    /             \
==r42=====r43=====r45=====r46=====r47
         /   \            ^      /
   merge/     \           |     /
       /       \         fix   /
     fb14       \             /
        |        -------------
        |        bring back changes from r43
        |
     deleted in r44

EDIT: Boo, he's answering his own question!
Read https://stackoverflow.blog/2011/07/01/its-ok-to-ask-and-answer-your-own-questions/
I want to find this later if/when I encounter similar situation again.
Answer: Anwser
svn merge -c 43 --ignore-ancestry .
svn commit -m "Introducing feature 14"

Explained
Why
svn merge -c 43 .

did not work in trunk?
Because of ancestry.
Let's say the changes in r43 went to file foo.cpp
svn merge records ancestry, this is basic stuff. With ancestry we know how to track back to older revisions. Right?
So when committing revision 43 foo.cpp@42 became an ancestor of foo.cpp@43. I then reverted back to r42 and committed r44 and foo.cpp@43 became ancestor of foo.cpp@44.
So, now being in revision 45 I want to merge revision 43 in. But I have foo.cpp@44 being merge from foo.cpp@42 so with basic merging of foo.cpp@43 to foo.cpp@45 ancestry would get messed up.
To get foo.cpp@43 to become foo.cpp@45 I need to ignore ancestry.
svn merge -c 43 --ignore-ancestry .

Further reading in http://svnbook.red-bean.com/en/1.7/svn.branchmerge.advanced.html#svn.branchmerge.advanced.ancestry
Of course the same would have been achieved by digging branch fb14 from the catacomb and make another merge to trunk:
      roll back to r42
    ----------------
   /                \
--r42-----r43-----r45-----r46-----r47
         /                ^      /
        /                 |     /
       /                 fix   /
merge fb14---                 /
             \           merge fb14
            delete fb14

i.e.
(in revision 43)
svn merge -r HEAD:42 .
svn commit -m "Reverted back to RC1 of v1.0.3"

Code like you've never coded before, we need a fix immediately!
svn commit -m "Fixed b0rken feature for v1.0.3"

Kick CI machine to build packages and release the SW.
svn cp ^/branches/fb14@43 ^/branches/fb14-2
svn up
svn merge --reintegrate ^/branches/fb14-2
svn commit -m "Introducing feature 14"
svn rm ^/branches/fb14-2

But I didn't like this approach so I read about advanced merging. ;)


bash does not work using Docker's SHELL instruction

Question: I need to use bash in the scripts of a CI/CD pipeline, so I'm trying with this simple image:
FROM alpine:3.4
RUN apk update -q && apk add --no-cache bash -q
SHELL ["/bin/bash", "--login", "-c"]
RUN echo $0

What I get in my terminal is this:
$ docker build .
    Sending build context to Docker daemon  2.048kB
    Step 1/4 : FROM alpine:3.4
     ---> b7c5ffe56db7
    Step 2/4 : RUN apk update -q && apk add --no-cache bash -q
     ---> Using cache
     ---> 18b729da453c
    Step 3/4 : SHELL ["/bin/bash", "--login", "-c"]
     ---> Using cache
     ---> 03ca0df4a543
    Step 4/4 : RUN echo $0
     ---> Running in a65419dafc4b
    /bin/bash
    Removing intermediate container a65419dafc4b
     ---> 2963f9e0e563
    Successfully built 2963f9e0e563

After that, I run that container and get this:
$ docker run -it 2963f9e0e563
/ $ echo $0
/bin/sh
/ $

(it runs as root but I changed "#" with "$" for this post)
Why is it using sh instead of bash?
Answer: The SHELL command only modifies the shell that is used to execute the instructions inside the Dockerfile.
If you want to change the shell that's used for the container runtime, you can add CMD ["/bin/bash"] to your Dockerfile in order to change the container default executable to /bin/bash. You could also specify the executable from the command line using docker run -it <image> /bin/bash.


Riccati differential equation $y'=x^2+y^2$

Question: $$y'=x^2+y^2$$ I know, that this is a kind of Riccati equation, but is it possible to solve it with only simple methods? Thank you
Comment: Are exact equations simple enough? That's what I'd try.
Comment: Looking at the [solution](http://www.wolframalpha.com/input/?i=y%27+%3D+y%5E2+%2B+x%5E2) this doesn't look promising.
Comment: @nbubis Implicitly it could be easy.
Comment: @GitGud - always happy to be proven wrong :)
Comment: @nbubis I can't be arsed $\ddot \smile$, not until the OP let's me know wether it is worth trying to transform it in an exact equation.
Answer: It can be solved (or, rather, transformed into a recognizable form) using simple methods, but the result can only be expressed in terms of special functions.

Namely, let us write $\displaystyle y=-\frac{v'}{v}$, then $\displaystyle y'=-\frac{v''}{v}+\frac{v'^2}{v^2}$ so that the equation becomes linear:
$$v''+x^2v=0.\tag{1}$$
If we further introduce
$$v(x)=\sqrt{x}\cdot f\left(\text{$\frac{x^2}{2}$}\right),\tag{2}$$
 then (1) transforms into a particular case of the Bessel equation for $f(t)$:
$$t^2f''+tf'+\left(t^2-\frac{1}{16}\right)f=0.$$
It has the general solution
$$f(t)=C_1 J_{1/4}(t)+C_2J_{-1/4}(t).\tag{3}$$
Substituting this into (2), we find $v(x)$, and then $y(x)$ is given by its logarithmic derivative. Clearly, $y(x)$ will depend only on the ratio $C_1/C_2$ (instead of $C_1$, $C_2$ separately). This ratio plays the role of integration constant for the initial first order equation $y'=x^2+y^2$.
Comment: This book is very helpful ---> Handbook of Differential Equations. Daniel Zwillinger. Academic Press 1997.
Comment: Thank you for your support.
Greetings Eu2718


java classpath variable in RHEL 5.4

Question: I am using RHEL 5.4 linux and writing my first few java test programs.
javac and java comes by default, so I have been able to run a Hello World program.
I want to check what is the current classpath.
Nothing comes in
$ echo $CLASSPATH

or
$ env | grep -i classpath

Does it mean that the classpath variable is optional and we only set it when we want to set a project specific values?
Also, how is it able to find the standard java jars? because I am able to use System.out.println ? Does it mean that classpath is used to specify non-standard java jars, because java already knows where it has installed the standard jars, so it doesn't need CLASSPATH for its internal use..
Answer: when you do
echo $CLASSPATH

it will look for system env variables, if its not set it will be blank and by default current DIR would be the classpath.
It will first look into Bootstrap classes then Extension Classes and then User Custom classes
Also See

How Classes are Found ?
Comment: Then, how is it able to find the standard java jars? because I am able to use System.out.println ..
Comment: Latest link : http://download.oracle.com/javase/7/docs/technotes/tools/findingclasses.html
Answer: You can check the classpath in Java:
import java.util.Properties;

public class PrintClasspath
{

    public static void main( String[] arguments )
    {
        System.out.println( System.getProperty( "java.class.path" ) );
    }

}

java classpath variable in RHEL 5.4