text:
Q: Given a commutative diagram, show that $\delta$ is isomorphism
Let $R$ be a commutative ring with a unit and  let the following picture be a commutative diagram of $R$-modules with exact rows.
  Suppose that $\alpha$ and $\beta$ are isomorphisms. Show that the natural homomorphism $\bar{\delta}:\ker(\varphi)\to\ker(\psi)$ is an isomorphism.

Attempt:
According to the snake' lemma, there is a natural homomorphism $\bar{\delta}:\ker(\varphi)\to\ker(\psi)$.
$\bar{\delta}$ is surjective:
Let $n\in\ker{\psi}$. Then $\psi(n)=0\Rightarrow \beta(\eta(n))=\eta'(\psi(n))=0$. Because that $\beta$ is injective then $\eta(n)=0\Rightarrow n\in\ker\eta=\operatorname{Im}\delta\Rightarrow\exists m\in M,\delta(m)=n.$
We know that $\delta'(\varphi(m))=\psi(\delta(m))=0\Rightarrow \varphi(m)\in\ker\delta'=\operatorname{Im}\epsilon'\Rightarrow\exists k'\in K', \epsilon'(k')=\varphi(m).$
$\alpha$ is surjective. Hence,
$$
\exists k\in K, \alpha(k)=k'
$$Here I stuck. If I succeed to show that $\varphi(m)=0$, (or that $\epsilon'=0$) I'll finish the proof.
$\bar{\delta}$ is injective:
In this part I had no problem:
Let $m\in\ker\bar\delta$. Then $0=\bar\delta(m)=\delta(m)\Rightarrow m\in\ker\delta=\operatorname{Im}\epsilon\Rightarrow\exists k\in K,\epsilon(k)=m$.
We know that $\varphi(m)=0\Rightarrow0=\varphi(\epsilon(k))=\epsilon'(\alpha(k))$. Hence $\alpha(k)\in\ker\epsilon'=\operatorname{Im}(0\to K')\Rightarrow \alpha(k)=0$. But $\alpha$ is injective, then $k=0\Rightarrow m=\epsilon(k)=0$. Thus $\bar\delta$ is injective.

A: $\DeclareMathOperator{\im}{Im}$
Let's do some grunt diagram chasing.
First, we prove $\overline{\delta}$ is injective. Suppose $x\in\ker\overline{\delta}$. Then $x\in\ker(\delta)=\im(\varepsilon)$, so $x=\varepsilon(k)$ for some $k\in K$. But also, $x\in\ker\varphi$, so
$$0=\varphi(x)=\varphi(\varepsilon(k))=\varepsilon'(\alpha(k))$$
But $\epsilon'$ is injective, so $\alpha(k)=0$. Since $\alpha$ is an isomorphism $k=0$, so $x=\varepsilon(k)=\varepsilon(0)=0$.
Therefore, $\overline{\delta}$ is injective.

Now let us prove $\overline{\delta}$ is surjective. Let $y\in\ker\psi$. Then $\psi(y)=0$, so
$$0=\eta'(\psi(y))=\beta(\eta(y))$$
Since $\beta$ is an isomorphism, $\eta(y)=0$, so $y\in\ker(\eta)=\im(\delta)$. Write $y=\delta(x)$ for some $x\in M$.
We have $\delta'(\varphi(x))=\psi(\delta(x))=\psi(y)=0$, so $\varphi(x)\in\ker\delta'=\im(\varepsilon')$. Let $k'\in K'$ such that $\varphi(x)=\varepsilon'(k')$. Since $\alpha$ is an isomorphism, there is $k\in K$ such that $k'=\alpha(k)$. Then
$$\varphi(\varepsilon(k))=\varepsilon'(\alpha(k))=\varepsilon'(k')=\varphi(x)$$
So now we use the $R$-module structure: Let $z=x-\varepsilon(k)$. Then the above means that $z\in\ker\varphi$. We prove that $\overline{\delta}(z)=y$:
$$\overline{\delta}(z)=\delta(x)-\delta\varepsilon(k)=\delta(x)=y$$
because $\delta\varepsilon=0$, since the first row is exact.


text:
Q: How can i see dotnet implementation code (for eg.UseAuthentication() middleware) in vs code? when i press crl+right click in app.UseAuthentication() in vs code it only open the interface class but not actual implementation.
app.UseAuthentication();

//this will open the following class

#region Assembly Microsoft.AspNetCore.Authorization.Policy, Version=7.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60
// Microsoft.AspNetCore.Authorization.Policy.dll
#endregion

#nullable enable

namespace Microsoft.AspNetCore.Builder
{
    //
    // Summary:
    //     Extension methods to add authorization capabilities to an HTTP application pipeline.
    public static class AuthorizationAppBuilderExtensions
    {
        //
        // Summary:
        //     Adds the Microsoft.AspNetCore.Authorization.AuthorizationMiddleware to the specified
        //     Microsoft.AspNetCore.Builder.IApplicationBuilder, which enables authorization
        //     capabilities.
        //     When authorizing a resource that is routed using endpoint routing, this call
        //     must appear between the calls to app.UseRouting() and app.UseEndpoints(...) for
        //     the middleware to function correctly.
        //
        // Parameters:
        //   app:
        //     The Microsoft.AspNetCore.Builder.IApplicationBuilder to add the middleware to.
        //
        // Returns:
        //     A reference to app after the operation has completed.
        public static IApplicationBuilder UseAuthorization(this IApplicationBuilder app);
    }
}

i'm aspecting the actual implementation service class

A: For the ASP.NET Core source code you can find it on github here.
For your current AuthorizationAppBuilderExtensions, you can check its source code in the following reference:
https://github.com/dotnet/aspnetcore/blob/main/src/Security/Authorization/Policy/src/AuthorizationAppBuilderExtensions.cs

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to convert string to Title Case in Python? Example:
HILO -> Hilo
new york -> New York
SAN FRANCISCO -> San Francisco

Is there a library or standard way to perform this task?

A: Potential library: https://pypi.org/project/stringcase/
Example:
import stringcase
stringcase.camelcase('foo_bar_baz') # => "fooBarBaz"

Though it's questionable whether it will leave spaces in.  (Examples show it removing space, but there is a bug tracker issue noting that it leaves them in.)

A: Why not write one? Something like this may satisfy your requirements:
def FixCase(st):
    return ' '.join(''.join([w[0].upper(), w[1:].lower()]) for w in st.split())

A: Note: Why am I providing yet another answer? This answer is based on the title of the question and the notion that camelcase is defined as: a series of words that have been concatenated (no spaces!) such that each of the original words start with a capital letter (the rest being lowercase) excepting the first word of the series (which is completely lowercase). Also it is assumed that "all strings" refers to ASCII character set; unicode would not work with this solution).
simple
Given the above definition, this function
import re
word_regex_pattern = re.compile("[^A-Za-z]+")

def camel(chars):
  words = word_regex_pattern.split(chars)
  return "".join(w.lower() if i is 0 else w.title() for i, w in enumerate(words))

, when called, would result in this manner
camel("San Francisco")  # sanFrancisco
camel("SAN-FRANCISCO")  # sanFrancisco
camel("san_francisco")  # sanFrancisco

less simple
Note that it fails when presented with an already camel cased string!
camel("sanFrancisco")   # sanfrancisco  <-- noted limitation

even less simple
Note that it fails with many unicode strings
camel("México City")    # mXicoCity     <-- can't handle unicode

I don't have a solution for these cases(or other ones that could be introduced with some creativity). So, as in all things that have to do with strings, cover your own edge cases and good luck with unicode!

A: just use .title(), and it will convert first letter of every word in capital, rest in small:
>>> a='mohs shahid ss'
>>> a.title()
'Mohs Shahid Ss'
>>> a='TRUE'
>>> b=a.title()
>>> b
'True'
>>> eval(b)
True

A: This one would always start with lowercase, and also strip non alphanumeric characters:
def camelCase(st):
    output = ''.join(x for x in st.title() if x.isalnum())
    return output[0].lower() + output[1:]

A: Why not use title Right from the docs:
>>> "they're bill's friends from the UK".title()
"They'Re Bill'S Friends From The Uk"

If you really wanted PascalCase you can use this:
>>> ''.join(x for x in 'make IT pascal CaSe'.title() if not x.isspace())
'MakeItPascalCase'

A: def camelCase(st):
    s = st.title()
    d = "".join(s.split())
    d = d.replace(d[0],d[0].lower())
    return d

A: def capitalizeWords(s):
  return re.sub(r'\w+', lambda m:m.group(0).capitalize(), s)

re.sub can take a function for the "replacement" (rather than just a string, which is the usage most people seem to be familiar with). This repl function will be called with an re.Match object for each match of the pattern, and the result (which should be a string) will be used as a replacement for that match.
A longer version of the same thing:
WORD_RE = re.compile(r'\w+')

def capitalizeMatch(m):
  return m.group(0).capitalize()

def capitalizeWords(s):
  return WORD_RE.sub(capitalizeMatch, s)

This pre-compiles the pattern (generally considered good form) and uses a named function instead of a lambda.

A: I would like to add my little contribution to this post:
def to_camelcase(str):
  return ' '.join([t.title() for t in str.split()])

A: From code wars - Write simple .camelCase method in Python for strings. All words must have their first letter capitalized without spaces.
camelcase("hello case") => HelloCase
camelcase("camel case word") => CamelCaseWord
def camel_case(string):
    titled_string = string.title()
    space_joined_string = titled_string.replace(' ', '')
    return space_joined_string


text:
Q: Passing a object by reference in c++ This is a noobie question, but I'm not sure how to pass by reference in C++. I have the following class which sets up a Node and a few functions.
class Node
{
  public:
    Node *next;
    int data;
    Node(int dat)
    {
      next = NULL;
      data = dat;
    }
    Node* getNext()
    { return next; }
    void setNext(Node *n)
    { next = n;}

    void reverse(Node *root)
    {
      Node *previous = NULL;
      while(root != NULL)
      {
        Node *next = root->getNext();
        root->setNext(previous);
        previous = root;
        root = next;
      }
      root = previous;
    }
};

Now, the purpose of my little class is to create a singularly linked list and have the ability to reverse it. And it seems to work fine, if I return the node named 'previous' at the end of reverse.
But look at my main function:
int main()
{
  Node *root = new Node(1);
  Node *num2 = new Node(2);
  Node *num3 = new Node(3);
  Node *num4 = new Node(4);

  root->setNext(num2);
  num2->setNext(num3);
  num3->setNext(num4);
  root->printList();
  root->reverse(root);
  root->printList();

  return 0;
}

printList() was omitted for sake of space, but it just prints a list given a node. The problem is, when root->reverse(root) is called, root doesn't actually end up pointing to 'previous'.
The output would be this:
1
2
3
4
  // the value of previous from the reverse function is 4
1

I really don't understand the output. Anyone care to explain what's happening? (Why isn't the list reversed even though if I did something like this root = root->reverse(root) where reverse returns previous, it would) why is it that root now only points to itself? I'm new to c++ and appreciate your help!

A: C++ has support for reference semantics. Therefore, for a given function:
void foo(Bar& bar);

To pass by reference you do:
int main() {
  Bar whatsit;

  foo(whatsit);

  return 0;
}

That's it!
This is commonly confused with passing a pointer, where for a function such as:
void foo(Bar* bar);

You would do:
int main() {
  Bar whatisit;

  foo(&whatsit);

  return 0;
}

The difference is mostly a matter of semantics:
 - A reference is always valid. There is no reason to check for a NULL pointer.
 - A pointer could be NULL, and as such, should be checked.
It is, however, possible for a reference to refer to a NULL pointer, however, if the programmer decides to be evil and abuse reference semantics, but the principle remains.

A: You aren't passing by reference. You are passing a copy of the pointer. This copy still points to the same node, but it is still just a copy with local scope. Basically it is another pointer pointing to the node that the pointer in main is pointing to (ha!). At the end of your function, your assignment is assigning previous to this pointer copy, and then the function ends and the copy goes out of scope. Your pointer in main remains unchanged.
The reason returning/assigning the pointer worked is that this copy which has been set to what you want is returned and assigned to your pointer in main.
You can fix this in a multitude of ways. Pass a reference to your pointer (ugly imo), use references, or return root and do an assignment.

A: To pass a pointer by reference you can declare reverse as:
void reverse(Node*& root) {
  // ...
}


text:
Q: Place three edittext-widgets horizontally with same length How do I best put three edittext on the same row in a linearlayout and let them have the same size? Is the solution to get the screenwidth and divide it by the number of edittext-widtegs?
In the following xml-code - the last edittext does not fit within the screenwidth.
Set the layout width in absoulute px will not be a good idea since the screen-size differ from phone to phone.
 <LinearLayout
       android:orientation="horizontal"
       android:layout_width="match_parent"
       android:layout_height="match_parent">

    <EditText
        android:id="@+id/number1_input"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:imeOptions="actionSend" />

    <EditText
        android:id="@+id/number2_input2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:imeOptions="actionSend" />

    <EditText
        android:id="@+id/number3_input3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:inputType="number"
        android:imeOptions="actionSend" />

</LinearLayout>

A: Replace android:layout_width="wrap_content" with android:layout_width="0dp", and add android:layout_weight="1" to each of the <EditText> elements. See the documentation on LinearLayout for more about how to use android:layout_weight.


text:
Q: R2RML mapping with values from another table I want to use R2RML and Virtuoso to map some tables from a MySql source.
I have a table with "Things" and I want them to have predicates that are not URIs but coming from the name column from a table "Values" connected via the thingID.
I can map the table "Values" via the ID of a "Thing" to the thingId of "Values" - but with this mapping I only get the URI of the respective "Values" entry. What I want to have is the string stored in the column "Value".
The expected resulting triple should be for example:
<http://localhost:8890/ex/things/1> rdf:type <http://localhost:8890/ex/types/vmware> ;
ex:hasValue "Name from the table Values" .

Example of Things table:
ID  typeId
1   3

Example of the Types table:
ID   Name
3    vmware

Example of the Values table:
ID   thingId   Value
1    1         VMware Virtual Platform

That is my mapping so far:
<#TriplesMapThings> a rr:TriplesMap; rr:logicalTable [ rr:tableSchema "exdb" ; rr:tableOwner "ex" ; rr:tableName "Things" ];
rr:subjectMap [ rr:termType rr:IRI  ; rr:template "http://localhost:8890/ex/things/{id}"; rr:class ex:Things; rr:graph <http://localhost:8890/ex_test#> ];
rr:predicateObjectMap [ rr:predicateMap [ rr:constant ex:id ] ; rr:objectMap [ rr:column "id" ]; ] ;
rr:predicateObjectMap [ rr:predicateMap [ rr:constant ex:typeid ] ; rr:objectMap [ rr:column "typeId" ]; ] ;

rr:predicateObjectMap [ rr:predicateMap [ rr:constant rdf:type ] ; rr:objectMap [ rr:parentTriplesMap <#TriplesMapTypes>; rr:joinCondition [rr:child "typeId"; rr:parent "id";]; ];] ;

rr:predicateObjectMap [ rr:predicateMap [ rr:constant ex:hasValue ] ; rr:objectMap [ rr:parentTriplesMap <#TriplesMapValues>; rr:joinCondition [rr:child "id"; rr:parent "thingId";]; ];] .

<#TriplesMapTypes> a rr:TriplesMap; rr:logicalTable [ rr:tableSchema "exdb" ; rr:tableOwner "ex" ; rr:tableName "Types" ];
rr:subjectMap [ rr:termType rr:IRI  ; rr:template "http://localhost:8890/ex/types/{nameUri}"; rr:class owl:Class; rr:graph <http://localhost:8890/ex_test#> ];
rr:predicateObjectMap [ rr:predicateMap [ rr:constant ex:id ] ; rr:objectMap [ rr:column "id" ]; ] ;
rr:predicateObjectMap [ rr:predicateMap [ rr:constant ex:name ] ; rr:objectMap [ rr:column "name" ]; ] .

<#TriplesMapValues> a rr:TriplesMap; rr:logicalTable [ rr:tableSchema "exdb" ; rr:tableOwner "ex" ; rr:tableName "Values" ];
rr:subjectMap [ rr:termType rr:IRI  ; rr:template "http://localhost:8890/ex/values/{id}"; rr:class ex:Values; rr:graph <http://localhost:8890/ex_test#> ];

rr:predicateObjectMap [ rr:predicateMap [ rr:constant rdf:type ] ; rr:objectMap [ rr:parentTriplesMap <#TriplesMapAttributes>; rr:joinCondition [rr:child "attributeId"; rr:parent "id";]; ];]  ;

rr:predicateObjectMap [ rr:predicateMap [ rr:constant ex:hasThing ] ; rr:objectMap [ rr:parentTriplesMap <#TriplesMapThings>; rr:joinCondition [rr:child "thingId"; rr:parent "id";]; ];]  ;

rr:predicateObjectMap [ rr:predicateMap [ rr:constant ex:id ] ; rr:objectMap [ rr:column "id" ]; ] ;
rr:predicateObjectMap [ rr:predicateMap [ rr:constant ex:thingid ] ; rr:objectMap [ rr:column "thingId" ]; ] ;
rr:predicateObjectMap [ rr:predicateMap [ rr:constant ex:value ] ; rr:objectMap [ rr:column "value" ]; ] .

A: The simplest way is to use SQL queries:
<#TriplesMapThings> a rr:TriplesMap;
rr:logicalTable [rr:sqlQuery "SELECT Things.ID, Types.Name FROM Things, Types WHERE Things.typeId = Types.ID" ];
rr:subjectMap [ rr:template "http://localhost:8890/ex/things/{ID}"];
rr:predicateObjectMap [
    rr:predicate rdf:type;
    rr:objectMap [ rr:template "http://localhost:8890/ex/types/{Name}"]
].
<#TriplesMapValues> a rr:TriplesMap;
rr:logicalTable [rr:tableName "Values" ];
rr:subjectMap [ rr:template "http://localhost:8890/ex/things/{thingId}"];
rr:predicateObjectMap [
    rr:predicate ex:hasValue;
    rr:objectMap [ rr:column "Value"]
].

However, looks like this won't work with Virtuoso. Per their documentation, rr:sqlQuery is not supported.
If Types.Name is a unique key, I believe you could do the following:
<#TriplesMapThings> a rr:TriplesMap;
rr:logicalTable [rr:tableName "Things" ];
rr:subjectMap [ rr:template "http://localhost:8890/ex/things/{ID}"];
rr:predicateObjectMap [
    rr:predicate rdf:type;
    rr:objectMap [
        rr:parentTriplesMap <#TriplesMapTypes>;
        rr:joinCondition [ rr:child "typeId"; rr:parent "ID"];
    ]
].

<#TriplesMapTypes> a rr:TriplesMap;
rr:logicalTable [rr:tableName "Types" ];
rr:subjectMap [ rr:template "http://localhost:8890/ex/types/{Name}"].

<#TriplesMapValues> a rr:TriplesMap;
rr:logicalTable [rr:tableName "Values" ];
rr:subjectMap [ rr:template "http://localhost:8890/ex/things/{thingId}"];
rr:predicateObjectMap [
    rr:predicate ex:hasValue;
    rr:objectMap [ rr:column "Value"]
].

Note that you are defining the subject URIs for the table Types using the Name attribute. So even though you are joining between Things.typeId and Types.ID, the R2RML processor should use the subject definition of the <#TriplesMapTypes> TriplesMap.
If Types.Name is not a unique key, then you have to do it using SQL queries.
Note that R2RML was designed to use SQL queries in case you need complex mappings (like the one you are trying to do).


text:
Q: react native reselect state is undefined why I get this error:
undefined is not an object. state.shopping_cart
reselect
import { createSelector } from 'reselect';

const carts = state => state.shopping_cart.cart;

export const allCarts = createSelector(
  carts,
  (data) => data
);

cart:
import { createSlice } from "@reduxjs/toolkit";
import _ from 'lodash';

const shopping_cart = createSlice({
    name: 'shopping_cart',
    initialState: {
      cart: []
    },
....
});

export const { addCart, removeCart, removeCartByProductID, addAmountOnCartItem } = shopping_cart.actions;
export default shopping_cart.reducer;

I called like this:
allCarts();

A: You should pass the state to the selector allCarts(state);
You can access the state via:
import { useSelector } from 'react-redux'

const selectedData = useSelector(state => state);


text:
Q: How to display image keep ratio in editor I have a div container to display content which is inputed from editor.
In editor, I upload an image and I want to display this image in that div container also keep image ratio?
Can I do it? Can I get imaze size which I uploaded into editor?

A: if you give width: 100%; to image, height will adjust automatically due to height: auto; style.
if you need anvanced settings read down below:
if you have and img tag with source, you can get img.naturalWidth and img.naturalHeight, so you can make a div containing this image and give it proportional sizes.

.wrapper {
  width: 100%;
  height: 0;
  padding: 0 0 57%;
  position: absolute;
}

.img {
  position: relative;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

you can change this 'padding: 0 0 57%' part to whatever you want. for ex, you can set it with javascript:
wrapper.style.padding = '0 0 ' + img.naturalWidth / img.naturalHeight * 100 + '%;';

in this case if .wrapper width cahanges, height also changes automatically.


text:
Q: redirect after shib login coldfusion I need to do the following steps:
1 - authenticate through shibboleth on local coldfusion server
2 - create security token on local coldfusion server
3 - redirect to external site passing along the security token.
Can I perform the redirect through Coldfusion (and how is that done) or do I need to do the redirect through my shibboleth config on the local server?


text:
Q: Which command-line editor should be used in Windows 7 to modify settings Which command-line editor should be used in Windows 7 to modify settings such as the boot sequence, display order and time out values for multiple operating systems, or Emergency Management Services and boot debugging settings?

A: bcdedit I believe.
Scott Hanselman has a nice walkthrough in the context of booting to a VHD.


text:
Q: Loading specific translations with Globalize3 Is it possible to load a specific translation with Globalize 3?
For instance, I have a Post which is translatable and shows on the front end in the correct locale as it should.  However, I want to show a this same version in the admin which has a fixed locale of :en.
One way of doing this seems to be by telling what locale we're in:
Globalize.locale = :de
Post.where(id: params[:id])

works just fine, but that's going to be overriding the locale globally.
So, how can I request the specific locale for just this one instance?

A: You need to use Globalize.with_locale in the view:
- Globalize.with_locale(:de) do
  = debug @post


text:
Q: Share assets folder between two subdomain's document roots I have two web apps that share the same assets (js, css, img etc.) but use different subdomains/document roots.
I'm trying to figure out how i can share one assets folder between the two document roots, so i can avoid having to change the assets folder for each subdomain after i apply changes to the assets.
Thanks for your time.
Current Structure:
www/html
    ├─ subdomain1
    │   └─ assets
    │   └─ index.php
    └─ subdomain2
        └─ assets
        └─ index.php

Desired Structure:
www/html
    ├─ assets
    ├─ subdomain1
    │   └─ index.php
    └─ subdomain2
        └─ index.php

VHost Confs:
subdomain one:
<VirtualHost *:80>
  ServerName www.one.mydomain.com
  ServerAlias one.mydomain.com
  ServerAdmin admin@example.com
  DocumentRoot /var/www/html/subdomain1/

<Directory /var/www/html/subdomain1/>
   Options -Indexes +FollowSymLinks
   AllowOverride All
   DirectoryIndex index.php
</Directory>

  ErrorLog /var/www/html/logs/subdomain1-error.log
  CustomLog /var/www/html/logs/subdomain1-access.log combined
</VirtualHost>

subdomain two:
<VirtualHost *:80>
  ServerName www.two.mydomain.com
  ServerAlias two.mydomain.com
  ServerAdmin admin@example.com
  DocumentRoot /var/www/html/subdomain2/

<Directory /var/www/html/subdomain2/>
   Options -Indexes +FollowSymLinks
   AllowOverride All
   DirectoryIndex index.php
</Directory>

  ErrorLog /var/www/html/logs/subdomain2-error.log
  CustomLog /var/www/html/logs/subdomain2-access.log combined
</VirtualHost>

A: In the config for the second host, you could use Apache's mod_alias to define an alias to the "primary" asset directory:
<VirtualHost *:80>
    ServerName www.two.mydomain.com
    ...
    <Location "/assets">
        Alias "/var/www/html/subdomain1/assets"
    </Location>

Then just remove the duplicated directory /var/www/html/subdomain2/assets.
Alternately, you could leave the config as is, remove the second dir, and then symlink to the first:
mv /var/www/html/subdomain2/assets /var/www/html/subdomain1/assets.old
ln -s /var/www/html/subdomain1/assets /var/www/html/subdomain2

Note however that either method could make deployments/development tricky, as you're essentially locking them to always have the same versions of the same files. Ultimately, it's likely best to leave them as duplicates and instead address your deployment mechanism.


text:
Q: Displaying decimal in X/32 or X/16 in same cell In cell "H27" the decimal total is .95692. I want to take the decimal amount in "H27" and display it as a fraction in "H30".
The total in this example is over 61/64", so I want it to round to the next 64th or  as 15/16".


text:
Q: Info from one web app to another I apologise if this is a newbie question!!
I'm building a web app and I'd like to be able to send stored local data from an instance of the web app on my phone to another instance of the same web app on another phone and save it to local data there. The caveat is that it can't get sent through http to my server as it contains sensitive information. I also don't want to store it on a web server in any form as I don't want to manage the security of the web server in terms of storing this sensitive information.
At the moment then only solution I can come up with is for the web app to generate an email which is sent to the second device, and then copy and pasted into the web app. Very clunky. Any ideas?


text:
Q: move files with AppleScript I am trying to move a file with AppleScript. This Is the code I use:
on adding folder items to this_folder after receiving these_items
    repeat with i from 1 to number of items in these_items
        set this_item to item i of these_items
        set the item_info to info for this_item
        set the item_path to the quoted form of the POSIX path of this_item

...
...   //irrelevant code here
...

       tell application "Finder"
         move POSIX file item_path to POSIX file "/Users/mainuser/Desktop/Books"
       end tell

    end repeat
end adding folder items to

If I replace item_path with a regular path such as /Users/mainuser/Desktop/Test/test.png than it works great. What could be the reason for my problem?

A: these_items is an array of alias specifiers, any further coercion is not needed
tell application "Finder"
     move this_item to folder "Books" of desktop
end tell

the property desktop points always to the desktop of the current user.
By the way: The Finder doesn't accept POSIX paths (slash separated), only the native HFS paths (colon separated).
PS: The reason why item_path does not work is the quotation.
It's only needed in do shell script

A: Use:
on adding folder items to this_folder after receiving these_items
    tell application "Finder" to move these_items to folder "Books" of desktop
end adding folder items to

The after receiving parameter is a list of AppleScript alias values, which is something Finder's move command already understands and knows how to work with. While it's unusual for application commands like move to accept values that aren't references to application objects, it's not completely unknown; particularly with pre-OS X apps like Finder whose scripting support was completely hand-written, allowing developers to make it work in ways that would be helpful to users and not just in ways dictated by dumb, standardized frameworks like OS X's Cocoa Scripting.


text:
Q: Google Cloud Services Intermittent Content Security Policy Issues I have a static web site hosted in a google-storage bucket that I serve up via the Google Platform.
This site has been running with no problems for about 6 months but over the last month I have had intermittent problems with it not loading style sheets and scripts due to "Content Security" issues - this results in just the text of the main page appearing the browser with no style and no (Javascript based) functionality. By intermittent I mean it works OK for a couple of hours and then it fails for a couple of hours.
There is no "web server" for this service as such as I am just serving up static pages from a bucket - I understand that Google must have their own server that handles this though. The failures occur no matter what browser the user is using and clearing the browser cache does not help so this issue is at the Google server end.
Checking the developer console in the browser I can see the following issues for all stylesheets, scripts and fonts that the web page uses:

> Refused to load the stylesheet XXXXXXX because it violates the
> following Content Security Policy directive: "default-src 'none'".
> Note that 'style-src-elem' was not explicitly set, so 'default-src' is
> used as a fallback.

I think I have got my Content Security settings correct:
   <meta http-equiv="Content-Security-Policy" content="
         default-src 'self';
         img-src 'self'
            https://syndication.twitter.com;
         font-src 'self'
            https://use.fontawesome.com
            https://fonts.gstatic.com
            https://fonts.googleapis.com;
         script-src 'self' 'unsafe-inline'
            https://stackpath.bootstrapcdn.com
            https://connect.facebook.net
            https://platform.twitter.com
            https://code.jquery.com
            https://cdnjs.cloudflare.com;
         style-src 'self' 'unsafe-inline'
            https://stackpath.bootstrapcdn.com
            https://use.fontawesome.com
            https://fonts.googleapis.com;
         frame-src 'self'
            https://www.facebook.com
            https://connect.facebook.net
            https://platform.twitter.com
            https://www.youtube.com;
   ">

These are the links that fail, each 'external' one includes signing with the imports to ensure that the "real" thing is loaded.
<!-- Bootstrap core CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">

<!-- Font Awesome -->
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.2.0/css/all.css" integrity="sha384-hWVjflwFxL6sNzntih27bfxkr27PmbbK/iSvJ+a4+0owXq79v+lsFkW54bOGbiDQ" crossorigin="anonymous">

<!-- Custom fonts for this template -->
<link href='https://fonts.googleapis.com/css?family=Titillium+Web' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>

Can anyone see what I am doing wrong or offer any advice on how to get this working consistently?

A: Unfortunately at the moment setting up that CSP header that way is not possible on website buckets, as because the webserver used by Cloud storage for website buckets may be adding a default value for your website.
There's a Feature request for this, but it seems it's been a while since the last update.
You could give it a try to App engine standard if you need to serve your page without these issues (you could even apply for the Always Free Tier)


text:
Q: Construct an Injective and onto unbounded operator. i was study functional analysis and i found a interesting problem. Let $X$ an infinite dimensional normed space. Construct an operator $T: X \rightarrow X$ such that $T$ is injective and onto.
Also, we can define a new norm on $X$ given by $\| x \|_{T} = \| T(x) \| $. Prove that $(X,\|  \cdot\|)$, $(X,\| \cdot \|_{T})$ are isometric.
My attemp:
I was trying to define the operator $T$ in the usual form of the books, take a Hamel Basis $(x_{i})_{i \in I}$,and WLOG suppose $\|x_{i}\|=1$ for any $i \in I$ then take countable subsequence $J = \{j_{1},j_{2},\dots\}$ of $I$. And define then as follows: $T(x_{ji}) = ix_{ji}$, and $T(x_{i})=0$ if $i \in I-J$. Then we can extend the function and we see that is unbouded. The problem is that, in this way $T$ is neither injective nor onto.
At this point i do not how to redefine the function to be bijective.
Any help is welcome, thanks!

A: This answer assumes A:  The axiom of choice, so all vector spaces have a Hamel basis and B:  You are working in a field of Characteristic 0.
EDIT:  As per @SeverinSchraven 's comment,  if working working in a field of characteristic $p$,  make the labels of $J$ from $\mathbb{N}\setminus p \mathbb{N}$ instead of $\mathbb{N}$
I decided to delete and restart to answer the generic question.  Setting things to 0 loses surjectivity,  instead take your countable subset $J$ of your index set $I$,  label the $J's$ in the natural way,  and define $$T(x_j)=jx_j,j\in  J$$,  $$T(x_i)=x_i\in I \setminus J$$
and extend via linearity.  This defines a linear, unbounded operator,  no matter the norm.
1-1 and onto are both done by looking at your elements as a finite linear combination of bases elements.   If $T(x_1)=T(x_2)$,  then $T(x_1 -x_2)=0$.   But by definition of $T$,  any basis elements in $x_1-x_2$ that come from $J$ would output $j\cdot$ the field element in that spot,  so that element is 0 (assuming our field is characteristic 0, anyways!)  Not even sure this is true if you have another field characteristic,  I haven't worked with vector spaces over such fields.
If the basis element of $x_1-x_2$ comes from $I\setminus J$,  then the coefficient of $T(x_1-x_2)$ will just be the underlying field element, so once again it must be 0.    Ergo it is injective.
For surjective,  take an arbitrary $x\in X$, it can be written as a linear combination of $x_i$ and $x_j$,   it has the obvious preimage, take $\frac 1 j x_j$ times the field element for any of those terms and just the field element for any $x_i$ terms
For isometry,  we need a linear map that makes it so the action of $T$ doesn't change the norms,  that's easy, just use $T^{-1}$


text:
Q: Determine if a point lies within a polygon/shape in QGIS I am working with a dataset that records violence cases (CSV file). All violence cases are geocoded to a latitude/longitude address so that they can be coordinated to any given shapes/polygons.
What would be the best method to determine whether a point (violence cases) lies within a polygon? I have a raster layer that may contains hundreds of polygons, and would like to generate boolean result (0/1) or dummy variables for each polygon.

A: Yes, it is totally possible by using the Vector menu, then navigating to the Spatial Query tool. Select within from the dropbox menu that appears on the tool and you're ready to go. This topic might also help.
But!
You said that you have a raster of many polygons. You must polygonize them using the polygonize tool first.


text:
Q: Div not filling width of floated container (css expert needed I know there are many variations of this question posted, but none I've found quite provide an answer that works for this case.
I basically have two left floated divs. Inside those two divs are div headers and tabled content.
I want the Div headers (Hour/Minute) to stretch to the width of the tabled content, but they only do this in FF and Chrome, not IE7. IE7 is my works official browser so the one I need it to work with the most.
Here is the CSS:
#ui-timepicker-div { padding:0.2em; }
#ui-timepicker-hours { float:left; }
#ui-timepicker-minutes { margin:0 0 0 0.2em; float:left; }

.ui-timepicker .ui-timepicker-header { padding:0.2em 0; }
.ui-timepicker .ui-timepicker-title { line-height:1.8em; text-align:center; }

.ui-timepicker table { margin:0.15em 0 0 0; font-size:.9em; border-collapse:collapse; }
.ui-timepicker td { padding:1px; width:2.2em; }
.ui-timepicker th, .ui-timepicker td { border:0; }

.ui-timepicker td a {
    display:block;
    padding:0.2em 0.3em 0.2em 0.5em;
    text-align:right;
    text-decoration:none;
}

Here is the HTML (did not include tabled content):

Hour

Minutes

A: Sorry to answer my own question, but after literally hours on this I just found out that by removing the 'ui-helper-clearfix' class from the ui-timepicker-header, all now works well in IE7 and FF


text:
Q: How to solve [FlowExchangeError: redirect_uri_mismatch] / [FlowExchangeError: invalid_grant] on a google app engine app? I need to make an app via app engine, I am familiarizing with the [demos] (https://github.com/google/earthengine-api/tree/master/demos). I have successfully deployed all of them except for "export-to-drive". I am able to deploy it, but I get a 500 Internal Server Error. It is the same on the cloud shell, but when I run it locally it run well.
Since the web console shows no error, I checked in the cloud shell console and got those errors:

*

*redirect_uri_mismatch

*invalid_grant
I tried to authorize all the redirect domains I could think of, but nothing changes. I know it is not my API key because it is working when I run the code locally.

A: You need to set up both Service account and OAuth 2.0 Client ID credentials  to authorize requests to Earth Engine.
Make sure that client_id and redirect_uri are properly configured as instructed here
Note that the value redirect_uri must match an authorized URI you have set up in API console > Credentials >
 Client ID for Web application > Authorized redirect URIs
.


text:
Q: Grails 'java.lang.instrument ASSERTION FAILED' error When I am trying to start my Grails application (using grails run-app or through GGTS) I have suddenly started getting the following error:
| Running Grails application
*** java.lang.instrument ASSERTION FAILED ***: "!errorOutstanding" with message transform method call failed at ../../../src/share/instrument/JPLISAgent.c line: 844
Exception in thread "main"
| Error Forked Grails VM exited with error

I saw the answer to another StackOverflow post here that said to comment out grails.project.fork inside my BuildConfig.groovy file. While this seems to solve the problem I am still new to Grails so I'm not sure I fully understand what is going on. So, my questions are:

*

*Why would my application suddenly start breaking in this way. As far as I know I've not changed anything that would cause this kind of error. I have been developing and running on the same code on another machine all week with no issue. It wasn't until I updated on my desktop that I started seeing this error.

*What are the settings being commented out used for? It looks like it is setting some JVM parameters. Is this just used to configure memory, etc when using grails run-app? I assume these settings would have no effect when I build a WAR and deploy to a tomcat instance later on.

A: As I found here. Graeme Rocher said that:

There is an issue with 2.3.2 on Windows only, we plan to address it
  with a 2.3.3 this week
In the meantime please use 2.3.1 or wait for 2.3.3 this week or follow
  the instructions in this issue for a workaround:
http://jira.grails.org/browse/GRAILS-10756


text:
Q: Change Value based on Dynamical Object Goal:
The goal is to make the variable with value '2014-06-14 09:00:00.000'.
Problem:
The syntax code is created as a dynamical object how do you make it from '2014-06-14 16:20:10.000' into value '2014-06-14 09:00:00.000'?
DECLARE @a datetime = '2014-06-14 16:20:10.000'

Information:
*The variable @a's value will be change all the time and the. The important is that "09:00:00.000" is not changeable.
*The value " 16:20:10.000' " can be different from time to time.

A: select dateadd(hour, 9, cast(cast(@a as date) as datetime))

A: Write as:
-- to get desired result the base query should be like:
SELECT DATEADD(day, DATEDIFF(day,'19000101',@a), CAST('09:00:00.000' AS DATETIME2(7)))
-- and then you can convert it into any other desired format as:
SELECT CONVERT(VARCHAR(23),
               DATEADD(day, DATEDIFF(day,'19000101',@a),
               CAST('09:00:00.000' AS DATETIME2(7))),
               121);

A: Try something like this: if '09:00:00.000' is always constant and the date part alone differs
DECLARE @a datetime = '2014-06-14 16:20:10.000'
select @a
SELECT CONVERT(DATETIME,CONVERT(VARCHAR(10), @a, 112))+'09:00:00.000'

A: Try this:
DECLARE @a DATETIME = '2014-06-14 16:20:10.000'
SET @a = REPLACE(CONVERT(VARCHAR(10), @a, 102),'.','-') + ' 09:00:00.000'
SELECT @a


text:
Q: Problems running rails db:migrate with rolify Currently trying to install rolify to my rails application
Followed the steps on github and am getting the following error after running rails db:migrate
/home/alex/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/rolify-5.2.0/lib/rolify.rb:30: warning: Using the last argument as keyword parameters is deprecated; maybe ** should be added to the call
/home/alex/.rbenv/versions/2.7.1/lib/ruby/gems/2.7.0/gems/activerecord-6.0.3/lib/active_record/associations.rb:1826: warning: The called method `has_and_belongs_to_many' is defined here
rake aborted!
NoMethodError: undefined method `Migration' for ActiveRecord:Module
/mnt/d/linux-docs/projects/code/rails/kream/kream/src/db/migrate/20200511073629_rolify_create_roles.rb:1:in `<main>'

Caused by:
NoMethodError: undefined method `Migration' for ActiveRecord:Module
/mnt/d/linux-docs/projects/code/rails/kream/kream/src/db/migrate/20200511073629_rolify_create_roles.rb:1:in `<main>'
Tasks: TOP => db:migrate
(See full trace by running task with --trace)

A: Within the migration file ammend the version number like so
class RolifyCreateRoles < ActiveRecord::Migration[6.0]
  def change
    create_table(:roles) do |t|
      t.string :name
      t.references :resource, :polymorphic => true

      t.timestamps
    end

    create_table(:users_roles, :id => false) do |t|
      t.references :user
      t.references :role
    end

    add_index(:roles, [ :name, :resource_type, :resource_id ])
    add_index(:users_roles, [ :user_id, :role_id ])
  end
end


text:
Q: How to display value from array in Checkbox I have the following array in model project:
PAYMENT_TYPE = ['in bar', 'bargeldlose Zahlung', 'E-Geld']

I have view new.html.erb
<%= form_for @project, url: {action: 'create'} do |f| %>

  <%= f.label 'Titel' %>
  <%= f.text_field :title %>

  <%= f.label 'Budget' %>
  <%= f.text_field :price %>

  für

  <%= f.select :price_category, Project::PRICE_CATEGORIES %>

  <%= f.label 'Beschreibung' %>
  <%= f.text_area :description %>

  <%= f.label 'Kategorie' %>
  <%= f.collection_select :category_id, Category.all, :id, :name %>

  <%= f.label 'Professionelle Freelancer Kenntnisse' %>
  <%= f.text_field :skill %>

  <%= f.label 'Ort' %>
  <%= f.text_field :location %>

  <%= f.label 'Möglichkeit der Zahlung' %>
  <%= f.collection_check_boxes :payment, Project::PAYMENT_TYPE do |t| %>
    <%= t.check_box %>
    <%= t.label %>
  <% end %>

  <%= f.submit 'erstellen' %>

<% end %>

I use <%= f.collection_check_boxes :payment, Project::PAYMENT_TYPE do |t| %>
But this code does not work. Which attribute do I need add in this helper method?


text:
Q: Can I upgrade to iOS5 (beta) and still develop/debug against the current version of Monotouch? As monotouch updates have stopped (another story), can I upgrade my iPhone/iPad to iOS 5 beta and still continue to develop using the current version of Monotouch?
I understand I wont have access to the new API's, but as its not possible to downgrade from iOS5, I was wondering has anyone else done the upgrade and it worked successfully?
I am currently in the middle of developing for iPhone using monotouch, so i want to be sure I dont make my only test devices incompatible, and essentially kill all my ability to develop using monotouch anymore.

A: Yes it still works - I just tried it - but beware of unexcepted behaviour from the APIs since the UIKit was heavily changed (styling features)
Also don't update the SDK just work with the current version - for debugging I can't vouch for it, because I'm in a very restricted WiFi at the moment (the app hung when trying to connect)
Regarding the downgrade - it's still possible according to various source (I did not try it) - you just have to place the phone into DFU Mode and make a recovery (your baseband won't downgrade!) - to be save just save the shsh with tinyUmbrella


text:
Q: Key press (Windows+D) by Selenium WebDriver Actions Is there a way to perform a Windows+D key press by Selenium WebDriver Actions?
I can do almost all the other combinations of key pressings with Actions but couldn't find the way to simulate a Windows key press.
It should be something like this:
action.keyDown(Windows).sendKeys((String.valueOf('\u0036'))).keyUp(Windows).perform()

I also know how to do this with Robot but I'm looking for resolutions by Actions.
UPD:
None of so far suggested already existing questions with their answers DOES NOT provide answer to this problem!
So please do not flag my question as duplicate until you found an answer, tried is and found it answering my question!


text:
Q: Align four elements without empty space for content blocks with css I have a problem to container 4 blocks with different height in one place.
You can see my demo by link https://jsfiddle.net/inthedark122/ncvjaeqy/1/
HTML Code:

---- You can change only css styles!!!

---- height - height - what is affixed is for understanding the content, in the original height is unknown in all cases
We know only width = 48 for ga и fa, the content on the right (f and g) should occupy all the remaining space as done in the example

---- The content of 4 blocks at any time may change, because these 3 cases must be considered as one, but at a different time

There shouldn't be any empty space between f and g, there shouldn't be any space between fa / ga, you need to stretch g to f to fill this spaceо

fa

f

ga

g

  Empty space should not be between f and g, between fa / ga empty space should be, ga should be on the same level with g

fa

f

ga

g

  The height of the lower blocks should be aligned with the maximum height ga or g

fa

f

ga

g

CSS code:
body {
  padding: 0;
  margin: 0;
}

.root {
  display: flex;
  flex-wrap: wrap;
  color: white;
  position: relative;
}

.g-root {
  display: flex;
  width: 100%;
}

.fa {
  height: 128px;
  /* position: absolute; */
  z-index: -1;
  background-color: grey;
}

.f {
  height: 50px;
  background-color: red;
  /* flex: 1; */
  /* width: 100%; */
  width: calc(100% - 48px);
  /* margin-left: 48px; */
  /* margin-bottom: 128px; */
}

.g {
  height: 180px;
  background-color: blue;
  flex: 1;
}

.ga {
  border-top: 1px solid white;
  background-color: black;
  /* margin-top: -128px; */
}

.fa, .ga {
  width: 48px;
  color: white;
}

I try absolute position and float, but I got empty space between  f and g or block "ga" was not be on same line with g.
Please check all comments in my demo to better understand my problem
UPD1:
Main goal is remove empty space between f and g (right side). When I do this, I get two issue:

*

*blocks for fa and ga get on each other

*when panel f more then panel fa then panel ga not in the same line with g. For this case we need empty space between fa and ga
More details
The object is represented by 4 rectangles.
There are 3 possible object States at different time intervals. They are presented in the Example.
The rules must be followed:

*

*there should never be an empty space between f and g (in all three examples). You need to stretch g to f to fill this space.

*If the height f is greater than fa, there should be an empty space between fa and ga.

*If the heights of ga and g are different, then they should stretch to the maximum of them.

Note:
only CSS can be edited. html is forbidden to touch.

A: I have done the required changes, I think you need to play around with the flex property for other examples. Hope this helps -:
https://jsfiddle.net/e96cprb2/

body {
  padding: 0;
  margin: 0;
}

.root {
  display: flex;
  height: 150px;
}
.a-root{
  display: flex;
  flex-direction: column;
  flex: 1;
}
.g-root{
  display: flex;
  flex-direction: column;
  flex: 5;
}
.fa{
  display: flex;
  background: red;
  flex: 1;

}
.ga{
  display: flex;
  background: grey;
  flex: 1;
}
.f{
  display: flex;
  background: blue;
  flex: 1
}
.g{
  display: flex;
  background: black;
  flex: 5
}

---- You can change only css styles!!!

---- height - height - what is affixed is for understanding the content, in the original height is unknown in all cases
We know only width = 48 for ga и fa, the content on the right (f and g) should occupy all the remaining space as done in the example

---- The content of 4 blocks at any time may change, because these 3 cases must be considered as one, but at a different time

There shouldn't be any empty space between f and g, there shouldn't be any space between fa / ga, you need to stretch g to f to fill this spaceо

fa

ga

f

g

  Empty space should not be between f and g, between fa / ga empty space should be, ga should be on the same level with g

fa

ga

f

g

  The height of the lower blocks should be aligned with the maximum height ga or g

fa

ga

f

g

A: Can you just try removing fixed height height: 50px; for class .f. I think that should solve your problem.
If not, you can try grouping .f and .fa in one div and .g and .ga in another.
Like shown in this fiddle
https://jsfiddle.net/ah6f5ozx/4/


text:
Q: Running plugin in a different AppDomain C# I'm having difficulties trying to run a .dll in a new AppDomain. My object is always of type System.MarshalByRefObject, so I cannot get the methods from the plugin.
What I have right now, is a plugin, that implements an interface and extending a MarshalByRefObject, looking like this:
public interface IPlugin
{
    string Name { get; }
    string Description { get; }
    string Author { get; }
    void Execute();
}

Then I have my plugin implemented like this:
[Serializable]
public class IPPlugin : MarshalByRefObject, IPlugin
{
    public string Author
    {
        get
        {
            return "John John";
        }
    }

    public string Description
    {
        get
        {
            return "description";
        }
    }

    public string Name
    {
        get
        {
            return "name";
        }
    }

    public void Execute()
    {
    //do stuff here
    }
}

So I built the plugin, got the dll, placed it in a folder and now in my project I'm trying to load it like this:
AppDomain domain = AppDomain.CreateDomain("PluginDomain");
Object obj = domain.CreateInstanceFromAndUnwrap(path + "\\" + plugins[option].getAssemblyName(), plugins[option].getTypeName());

Console.WriteLine(obj.GetType());

if (RemotingServices.IsTransparentProxy(obj))
{
    Type type = obj.GetType();
    MethodInfo Execute = type.GetMethod("Execute");
    Execute.Invoke(obj, null); //crashes here
}

But it crashes on Execute.Invoke(...), because it doesn't know the method Execute, since the object is of wrong type.
Error message is:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object.


text:
Q: Why is it impossible to use a var in a type definition ? type myType = 'A';
const myVar = 'A';

let a: 'A'; // OK
let b: myType; // OK
let c: myVar; // ERROR : cannot find name 'myVar'

Why isn't it possible to use a var as a type ? Shouldn't it be possible ?

A: myVar is a constant, you cannot type a variable as a constant, you can specify that a variable has the same type as the constant:
let c: typeof myVar;

Note that since the constant is "A" the above declaration is the same as
let c: "A";

So the only value assignable tp c is the constant value "A"

A: There are 4 ways to delcare a variable in TypeScript
var, let, const & Type (Type will be custom datatype)
let & var are quite similar while const prevent re-assignment to a variable. You can find diff between var & let here.
const is something which is constant and it's behaviour in TypeScript is same as C#. In C#, we also can't use const as type.
And to mainly answer your question - myVar is a variable not a type so you can't use a variable as type.


text:
Q: Bootstrap AngularJS Hide ul if no li Is there a way to use ng-hide or ng-if (i.e. inside the element, not the controller) to hide the #navbar-nav ul if it has no li or visible li?
Perhaps this can be extended to hide the toggle button as well since there is nothing to show.
Currently if there are no list items, then you can still toggle (slide up and down) the navbar, and it does not look nice.
Most of the other questions I saw had to do with ng-repeat

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
        Toggle navigation

      </button>
      Brand

          Home

          Products

          Overview

JSFiddle

A: There are a few things we need to touch on here.  The first is that the entire reason you use angular is to do data binding to manipulate/populate the view.  With that being said you need to have something for ng-if/ng-show/ng-hide to check against.  And this is where the controller comes in.  The controller has to contain information so that the view can be manipulated.  So in this case we will want to create a controller that has a variable to contain the menu list items:
app.controller('navCtrl', function(){
  this.menuItems = [
    { name: 'Home', href: '' },
    { name: 'Products', href: '' },
    { name: 'Overview', href: '' }
  ];
});

Now that this is done we need to bind it to the nav:

 ....

Next the nav li items will need to have an ng-repeat on them so that you can populate the ul

    {{ navItem.name }}

Now you can start doing what you are asking.  Simply add a ng-if that check if there are nav items:

 0"> ...

You can also do this on the toggle menu:
<button ng-if="nav.menuItems.length > 0" type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse"> ... </button>

So now if the controllers menuItems is an empty array this.menuItems = [] the ul and the button will not be created.
Which leads me to point #2.  The only way that this makes sense is if you are populating the menu items through a service or and API call of some sort, or if you can dynamically create/delete nav items.  If you are hard coding the array in the controller and not manipulating it then you know that the values will be present and there is no reason for this.
My final point in this implementation is to remove the class="hidden-xs" from the li as per this implementation the nav items will not show up even if they are present when the viewport is xs.
Here is a fiddle to check out the full implementation:
http://jsfiddle.net/9shaakw9/2/
Hope this helps!


text:
Q: Ckeditor 4 is loading too slow in our product, How to preload ckeditor4? Can I preload ckeditor4? I did some research and tried some of the solutions available on google, but nothing helped. Is there any way to speedup ckeditor4 loading time? specifically when it loads for the first time.
Also, I tried to load ckeditor4 in a hidden div and textarea on window.onload. Replacing hidden div element or textarea didn't worked.
Thanks in advance :)
P.S - I already removed all unnecessary plug-ins and complied it from source.


text:
Q: How to update an XML document by stream reading a file and simultaneously stream writing output I have to update a node of an existing XML document, challenge is that node value can be too large (~1MB). Is there a way that node value (its stored in a separate file) can be stream read and simultaneously stream written to XML. So that at any point memory footprint is not high.
I just need to update value of one node in XML document. Original XML file is small.

A: Use SAX parser instead of DOM. You can also use the StAX APIs (part of JDK package javax.xml.stream ).
Further reading-

*

*http://docs.oracle.com/javase/tutorial/jaxp/sax/parsing.html

*http://download-llnw.oracle.com/javase/6/docs/api/index.html?javax/xml/stream/package-summary.html


text:
Q: on postback avoid iframe getting refreshed in asp.net I have used iframe in my page.
For each and every postback event content of the iframe is getting refreshed.
I dont want to refresh content of iframe on eace postbackevent, iframe has to call only at time time of page load(!ispostback).
I have a big calculation in my iframe, so if it loads each and every time when parent page's(main page) postback event the it is no use of using iframe.
So please help me on this issue.

A: use updatepanel
<asp:UpdatePanel ID="UpdatePanel3" runat="server" UpdateMode="Always">
    <ContentTemplate>
        content that only you want to postback
    </ContentTemplate>
</asp:UpdatePanel>

refrence http://msdn.microsoft.com/en-IN/library/system.web.ui.updatepanel%28v=vs.100%29.aspx


text:
Q: OBD2 PIDs 0101 vs. 0141 w/ regards to injection type PIDs 0101 (monitor status since DTCs cleared) and 0141 (monitor status this drive cycle) are both returning the monitor status, however as per the specification only 0101 differentiates between spark ignition and compression ignition, hence the bit-to-monitor-mapping is different.
As per the standard documents (and Wikipedia1), this distinction is missing in 0141, so how am I supposed to interpret the result of 0141 on a compression ignition vehicle then?

A: All the PID details are in ISO 15031-5. You have to either buy it (arouond 80$) or find it anyhow!! Infos about PIDs are not complete (even sometimes ambiguous!) on Wikipedia. Below is some information and differences between 0x01 and 0x41 (But not complete and you cannot parse the information with it!). Hopefully helps:
0x01 is Monitor status since DTCs cleared.
The bits in this PID shall report two pieces of information for each monitor:
1) monitor status since DTCs were last cleared, saved in NVRAM or Keep Alive RAM
2) monitors supported on the vehicle.
0x41: the bit in this PID shall report two pieces of information for each monitor:
1) Monitor enable status for the current driving cycle. This bit shall indicate when a monitor is disabled in a manner such that there is no easy way for the driver to operate the vehicle to allow the monitor to run.
Typical examples are
⎯ engine-off soak not long enough (e.g., cold start temperature conditions not satisfied)
⎯ monitor maximum time limit or number of attempts/aborts exceeded
The monitor shall not indicate "disabled" for operator-controlled conditions such as rpm, load, throttle
position. The monitor shall not indicate "disabled" from key-on because minimum time limit has not been exceeded or engine warm-up conditions have not been met, since these conditions will eventually be met as the vehicle continues to be driven.
If the operator drives the vehicle to a different altitude or ambient air temperature conditions, monitor status may change from enabled to disabled. The monitor shall not change from disable to enable if the conditions
change back. This could result in a monitor showing "disabled" but eventually showing "complete".
2) Monitor completion status for the current driving/monitoring cycle. Status shall be reset to "not complete" upon starting a new monitoring cycle. Note that some monitoring cycles can include various engineoperating conditions; other monitoring cycles begin after the ignition key is turned off. Some status bits on a given vehicle can utilize engine-running monitoring cycles while others can utilize engine-off monitoring cycles. Resetting the bits to "not complete" upon starting the engine will accommodate most engine-running
and engine-off monitoring cycles; however, manufacturers are free to define their own monitoring cycles.

A: In the latest version of the standard (SAE J1979DA-201406) – which I have since bought – they have clarified that bit by specifying B3 as injection bit for both 0101 and 0141. Thus this question has been solved.


text:
Q: User Verifier demo shows "waiting for kaa response..." I am trying to run the UserVerification demo on kaa-0.9.0 Sandbox with android APK as client.
I register an facebook application and successfully configured the facebook user verifier on server. and then I succeed to run APK on emulator and then also login facebook. but it keeps showing "Waiting for Kaa response..." and I can't send message.
I was wondering if there is other anything I have to do with the server side? or I have to connect with multiple clients with the same user then I can have interactions?
Thanks,

A: Probably you had some problems with internet connection, that's why your application was waiting for the response.

I was wondering if there is other anything I have to do with the server side?

No, you shouldn't configure anything on the server side for this demo.

I have to connect with multiple clients with the same user then I can have interactions?

Yes, if you want to see an interaction between two endpoints, you should install this app on different devices and log in with the same account. Otherwise, you will just send messages on one without seeing them on other.


text:
Q: Difference between declaration of variable with extern and without it 1.h
extern int a;

1.c
#include <stdio.h>
#include "1.h"

int main(){
 printf("%d\n", a);
 return 0;
}

2.c
#include "1.h"

int a = 6;

This compiles and runs just fine (gcc 1.c 2.c) if you remove extern from 1.h and prints 6.
I know that removing it might cause a to be defined in every translation unit (object file), but what is the problem? doesn't the linker just git rid of it when linking since it compiles with no errors?

A: This technique does not conform to the letter of the C standard and the
'one definition rule' — it is officially undefined behaviour:

J.2 Undefined behavior
An identifier with external linkage is used, but in the program there
does not exist exactly one external definition for the identifier, or
the identifier is not used and there exist multiple external
definitions for the identifier (6.9).
§6.9 External definitions ¶5
An external definition is an external declaration that is also a
definition of a function (other than an inline definition) or an
object.
If an identifier declared with external linkage is used in an
expression (other than as part of the operand of a sizeof or
_Alignof operator whose result is an integer constant), somewhere in
the entire program there shall be exactly one external definition for
the identifier; otherwise, there shall be no more than
one.161)
161) Thus, if an identifier declared with external linkage
is not used in an expression, there need be no external definition for
it.

more here:
How do I use extern to share variables between source files?


text:
Q: Declaring friend template class template in C++1z produces error: specialization of 'template class A' must appear at namespace I am using boost asio coroutines and I wanted to use the new filesystem TS (-stdc++fs), so I upgraded to GCC 6-20151025 snapshot. It worked fine. But then I turned on -std=c++1z and I got an error deep in boost's source code. I isolated the error and this is a minimal example:
// { dg-do compile }
// { dg-options "-std=c++1z" }

template< typename T >
class A
{
};

template<>
class A< void >
{
        template< typename X >
        friend class A;
};

It compiles fine with -std=c++14, but generates the following error for -std=c++1z:
error: specialization of 'template<class T> class A' must appear at namespace scope
  friend class A;
               ^

I traced the error in the sources and it appears the behavior diverges in the newly-introduced function `maybe_new_partial_specialization' in pt.c. In particular in a condition that only activates when Concepts TS is active.
I wanted to check first if this is the intended behavior in Concepts TS/C++1z before reporting it as a bug.
Thank you.
EDIT: Based on the answer(s) below, it turns out to be a bug, and I thus I have reported it here.

A: Backward compability issues were summarized in annex A of the concepts paper. It solely contains one entry:

The behavior you encountered is not intended and a regression, please report it.


text:
Q: destroy not working in java I have created a simple java program to open an excel file and write data to it, once the data is written I then proceed to open the file to view the spreadsheet:
String[] cmdarray=new String[]{"cmd.exe","/c","C:\\Users\\Jason\\Documents\\*******\\********\\******.xls"};
            Runtime runTime = Runtime.getRuntime();
            Process process = runTime.exec(cmdarray);

as part of the learning curve I then try to close the file 10 secs later with:
process.destroy();

but this isn't closing the window.
Can anyone point out where I am going wrong? Thank you.
private static void OpenExcel() throws IOException {

            //Find the File and open it
            String[] cmdarray=new String[]{"cmd.exe","/c","C:\\Users\\Jason\\Documents\\*********\\*********\\********.xls"};
            Runtime runTime = Runtime.getRuntime();
            Process process = runTime.exec(cmdarray);

            try{
            //Delay
             TimeUnit.SECONDS.sleep(10);

        }catch (InterruptedException e) {
                e.printStackTrace();
                //Handle exception
            }
            //Close Excel
            System.out.println("Closing Excel");
            process.destroy();

            }
 }

A: One of the reason could be well-known JDK bug:

The fundamental problem here is that, unlike Unix, Windows does that
  maintain parent-child relationships between processes. A process can
  kill its own immediate children, but unless you make other
  arrangements to obtain the information, can't kill any
  'grand-children' because it has no way of finding them.

You can try with direct execution of Excel, not via cmd:
Runtime.getRuntime().exec("C:\\full\\path\\to\\excel.exe C:\\file.xls");


text:
Q: Javascript module pattern : calling functions within nested function I have code like that :
var SEVERINU = SEVERINU || {};

SEVERINU.AutoGallery = {
    galleryImagesNames: new Array(),

    findImages: function () {
        var dirToResearch = this.galleryName;

        $.post(
            "_php/get-files.php", {
            dir: dirToResearch,
            ext: this.fileExtension
        }, function (data) {
            var pliki = $.parseJSON(data);
            console.log(data);
            for (var i in pliki) {
                this.galleryImagesNames.push(pliki[i]); // problem !
            }
        });

    },
}

This line: this.galleryImagesNames.push(pliki[i]); is giving me problems.
It says he cant find that var galleryImagesNames etc.
How to call functions, var if I am to 'deep' ?

A: Just save current this to some other variable so it won't get overwritten inside the function.
var SEVERINU = SEVERINU || {};

SEVERINU.AutoGallery = {
  galleryImagesNames : new Array(),

  findImages : function(){
        var self = this; // keep current value of this in variable named self
        var dirToResearch = this.galleryName;

        $.post(
            "_php/get-files.php",
            {
                dir: dirToResearch,
                ext: this.fileExtension
            },
            function(data){
                var pliki = $.parseJSON(data);
                console.log(data);
                for(var i in pliki){
                    // call the method using self variable instead of this that got overwritten
                    self.galleryImagesNames.push(pliki[i]);
                }
            }
        );

    },

}

A: Actually it's because your $.post has a different scope than the rest of the object. Try this:
findImages : function(){
    var dirToResearch = this.galleryName;
    var gImageNames = this.galleryImagesNames;
    $.post(
        "_php/get-files.php",
        {
            dir: dirToResearch,
            ext: this.fileExtension
        },
        function(data){
            var pliki = $.parseJSON(data);
            console.log(data);
            for(var i in pliki){
                gImageNames.push(pliki[i]); // we have access to this variable
            }
        }
    );

},

A: Since you are inside an anonymous function you will have to reference the this keyword again. Or use it directly like so:
SEVERINU.AutoGallery.galleryImagesNames.push(pliki[i]);

Usually when you need the reference SEVERINU.AutoGallery more than once you better store it in a variable like:
var that = SEVERINU.AutoGallery; // or "self" or something you prefer

for (var i in pliki) {
    that.galleryImagesNames.push(pliki[i]);
}

The reason for this is because javascript tends to be slow when accessing object namespaces. The deeper you go the slower it gets. The more references you make, the slower it will become since function scope has to be resolved first in order to access the next/previous scope.

A: You can also use $.proxy to pass in the context.
var SEVERINU = SEVERINU || {};

SEVERINU.AutoGallery = {
 galleryImagesNames : new Array(),

 findImages : function(){
    var dirToResearch = this.galleryName;

    $.post(
        "_php/get-files.php",
        {
            dir: dirToResearch,
            ext: this.fileExtension
        },
        $.proxy(function(data){ //Set up for the context to be passes for this function.
            var pliki = $.parseJSON(data);
            console.log(data);
            for(var i in pliki){
                this.galleryImagesNames.push(pliki[i]); // problem solved. now this doesn't refer to ajax context
            }
        },this) <-- Pass the context here
    );

},
}

$.proxy Takes a function and returns a new one that will always have a particular context.


text:
Q: Spring boot wait_timeout I have a problem with error of wait_timeout:
Mon Aug 08 06:16:31 CEST 2016
There was an unexpected error (type=Internal Server Error, status=500).
PreparedStatementCallback; SQL [SELECT main_cat FROM category_mapping WHERE cat=?]; The last packet successfully received from the server was 246,098,167 milliseconds ago. The last packet sent successfully to the server was 246,098,260 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: The last packet successfully received from the server was 246,098,167 milliseconds ago. The last packet sent successfully to the server was 246,098,260 milliseconds ago. is longer than the server configured value of 'wait_timeout'. You should consider either expiring and/or testing connection validity before use in your application, increasing the server configured values for client timeouts, or using the Connector/J connection property 'autoReconnect=true' to avoid this problem.

application.properties:
spring.datasource.url=jdbc:mysql://localhost/allek?autoReconnect=true
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.testWhileIdle = true
spring.datasource.timeBetweenEvictionRunsMillis = 3600000
spring.datasource.validationQuery = SELECT 1

CategoryRepository.java:
package pl.bpo.archiwumallegro.repositories;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public class CategoryRepository {

    private JdbcTemplate jdbcTemplate;

    @Autowired
    public CategoryRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Optional<Long> findMainCategory(Long category) {
        String sql = "SELECT main_cat FROM category_mapping WHERE cat=?";
        return Optional.ofNullable(
                jdbcTemplate.queryForObject(sql, Long.class, category));
    }
}

What I can still make the connection to be all the time or to be automatically switched on?


text:
Q: Back button android implementation Is it possible to implement an Action Bar back button in android and set similar function as the back button from android device? I can not set the parent activity in manifest, because i work on a parsing News app, I have category list, when I choose one of the categories, the NewsList appears, then when I click one News from the list, and click on the back button implemented in android manifest(parent-activity), it shows error because it doesn't know which category was chosen before.

A: You could simply do by adding onBackPressed() in
 @overrite
public onOptionSelected - method with
onOptionSelected(){switch(menuItem.getId()){case android.R.id.home:onBackPressed();break;}}

A: You have to start NewsActivity with startActivityForResult from Category list.
When you press backbutton from NewsActivity then send category id/name from it with setResult and handle onActivityResult in Category list screen
More details : http://www.javatpoint.com/android-startactivityforresult-example


text:
Q: Python import package from the wrong directory(outside of the virtualenv) I was working on my virtualenv on a Ubuntu server. When I tried to import scipy. The module was somehow imported from outside of the virtualenv, and I don't want this behavior to happen.(That's what virtualenv is for, right?)
I checked what python I am using, and it's the one from my virtualenv
$ which python
/mydir/.venv3.6/bin/python

Then I checked if scipy is installed in the virtualenv
$ which pip
/mydir/.venv3.6/bin/pip
$ pip list
...
scipy    1.3.1
...

However, when I import scipy, it's imported from outside of the virtualenv. Other modules work just fine.
$ python
Python 3.6.9 (default, Jul  3 2019, 15:36:16)
...
>>> import numpy
>>> import scipy
>>> print(numpy)
<module 'numpy' from '/mydir/.venv3.6/lib/python3.6/site-packages/numpy/__init__.py'>
>>> print(scipy)
<module 'scipy' from '/usr/lib/python3.6/scipy/__init__.py'>

I uninstall scipy and reinstall it, but nothing changes.
Why is this happening?

A: I still don't know what's causing this.
In the end, I created a Conda environment. And everything works just as expected from there.


text:
Q: Consecutive coupon collection This question has remained unanswered. In its edited form, it asks for a lower bound on the expected number of draws required to collect all coupons in a modified coupon collector's problem in which draws can yield more than one coupon and the coupon types within one draw are consecutive.
I was hoping to show that for small consecutive draws (low $q$ in the linked question) the expected number of coupons drawn is bounded below by the expected number of coupons drawn in the standard coupon collector's problem, but to my surprise simulations showed that this is actually an upper bound. This is clear enough for large consecutive draws – in the extreme case in which every draw contains all $n$ coupons, we need to draw only $n$ coupons instead of $O(n\log n)$, and if every draw contains $n/2$ consecutive coupons, this is still clearly favourable, but intuitively I would have expected draws of just two consecutive coupons to be unfavourable, since they "explore the sample space" more slowly. The simulations show, however, that even in this case there's a slight improvement.

Can we prove that tending to collect consecutive coupons reduces the expected number of coupons drawn?

I intentionally phrased the question somewhat vaguely so you can use whatever "tendency to collect consecutively" might allow a proof; if you want a concrete model, you can use either the one in the linked question, where the number of consecutive coupons drawn in each draw is geometrically distributed, or you could draw a fixed number $k$ of consecutive coupons in each draw. For both cases, simulations show that the expected number of coupons drawn is reduced compared to the standard coupon collector's problem.


text:
Q: Why does the compiler parse a floating point number in a source file differently than at runtime? I've been working on some Rust projects lately to learn the language and have some fun. I am writing something similar to libconfig in Rust, using the peg crate to generate my parser.
For the last hour, I've been fighting with a weird bug where some values that were parsed from a sample config file didn't compare equal to the expected values.
Ultimately, I narrowed down the bug to this:
fn main() {
    let my_flt = "10.4e-5".parse::<f32>().unwrap();
    let other_flt = 10.4e-5;
    println!("{} == {} -> {}", my_flt, other_flt, my_flt == other_flt);
}

Surprisingly, this prints:

0.000104 == 0.000104 -> false

See it in the playground
Now, I know this has to be something related to the old infamous floating point precision issues. I know that even though two floats might look the same when printed, they can compare differently for various reasons, but I would have guessed that getting a float from parse::<f32>("X") would be equivalent to explicitly declaring and initializing a float to X. Clearly, I'm mistaken, but why?
After all, if I declare and initialize a float to X, internally, the compiler will have to do the same job as parse() when generating the final executable.
Why does the compiler parse the float X in the source file in a different way from the runtime parse::<f32>() function? Shouldn't this be consistent? I'm having such a hard time getting this over with!

A: Note that the OP's specific example no longer fails (tested in Rust 1.31.0)

It's a known issue that the standard library and the rustc lexer parse floating point values differently.
The standard library ultimately calls down to from_str_radix, and you can see the implementation there. I'm not sure exactly where the compilers version of parsing floating-pint literals takes place, but this comment indicates it leverages LLVM:

The compiler uses LLVM to parse literals and we can't quite depend on LLVM for our standard library.


text:
Q: Fast color quantization in OpenCV How can I reduce the number of distinct colors in images using OpenCV (+ C++) the fastest way possible? I don't want the complete code. I'm already doing it using kmeans but it's not very fast. This is the part of my code that is slow:
kmeans(samples, clusterCount, labels,
    TermCriteria(TermCriteria::EPS + TermCriteria::COUNT, 10, 10.0),
    1, KMEANS_RANDOM_CENTERS, centers);

This code takes a few seconds to process which is very very slow for me. I was using Matlab for this (rgb2ind) which was fast. Almost 0.01 seconds.
I want to use my code for production where the users expect the program to be fast.
Is there any alternative to kmeans for color quantization? Is there any way to run kmeans faster (which I don't think so because I've tried many different parameters)?
Edit:
Turned out color quantization is a very complex topic and takes time to write a good optimized one. I've decided to use Magick++ (ImageMagick API) for this.
Because of that I haven't tried Cris Luengo's new (edited) answer. But I mark it as answer (check out the comments too) so that other people don't think this question isn't answered.

A: There are many ways to quantize colors. Here I describe four.
Uniform quantization
Here we are using a color map with uniformly distributed colors, whether they exist in the image or not. In MATLAB-speak you would write
qimg = round(img*(N/255))*(255/N);

to quantize each channel into N levels (assuming the input is in the range [0,255]. You can also use floor, which is more suitable in some cases. This leads to N^3 different colors. For example with N=8 you get 512 unique RGB colors.
K-means clustering
This is the "classical" method to generate an adaptive palette. Obviously it is going to be the most expensive. The OP is applying k-means on the collection of all pixels. Instead, k-means can be applied to the color histogram. The process is identical, but instead of 10 million data points (a typical image nowadays), you have only maybe 32^3 = 33 thousand. The quantization caused by the histogram with reduced number of bins has little effect here when dealing with natural photographs. If you are quantizing a graph, which has a limited set of colors, you don't need to do k-means clustering.
You do a single pass through all pixels to create the histogram. Next, you run the regular k-means clustering, but using the histogram bins. Each data point has a weight now also (the number of pixels within that bin), that you need to take into account. The step in the algorithm that determines the cluster centers is affected. You need to compute the weighted mean of the data points, instead of the regular mean.
The result is affected by the initialization.
Octree quantization
An octree is a data structure for spatial indexing, where the volume is recursively divided into 8 sub-volumes by cutting each axis in half. The tree thus is formed of nodes with 8 children each. For color quantization, the RGB cube is represented by an octree, and the number of pixels per node is counted (this is equivalent to building a color histogram, and constructing an octree on top of that). Next, leaf nodes are removed until the desired number of them is left. Removing leaf nodes happens 8 at a time, such that a node one level up becomes a leaf. There are different strategies to pick which nodes to prune, but they typically revolve around pruning nodes with low pixel counts.
This is the method that Gimp uses.
Because the octree always splits nodes down the middle, it is not as flexible as k-means clustering or the next method.
Minimum variance quantization
MATLAB's rgb2ind, which the OP mentions, does uniform quantization and something they call "minimum variance quantization":

Minimum variance quantization cuts the RGB color cube into smaller boxes (not necessarily cubes) of different sizes, depending on how the colors are distributed in the image.

I'm not sure what this means. This page doesn't give away anything more, but it has a figure that looks like a k-d tree partitioning of the RGB cube. K-d trees are spatial indexing structures that divide spatial data in half recursively. At each level, you pick the dimension where there is most separation, and split along that dimension, leading to one additional leaf node. In contrast to octrees, the splitting can happen at an optimal location, it is not down the middle of the node.
The advantage of using a spatial indexing structure (either k-d trees or octrees) is that the color lookup is really fast. You start at the root, and make a binary decision based on either R, G or B value, until you reach a leaf node. There is no need to compute distances to each prototype cluster, as is the case of k-means.
[Edit two weeks later] I have been thinking about a possible implementation, and came up with one. This is the algorithm:

*

*The full color histogram is considered a partition. This will be the root for a k-d tree, which right now is also the leaf node because there are yet no other nodes.

*A priority queue is created. It contains all the leaf nodes of the k-d tree. The priority is given by the variance of the partition along one axis, minus the variances of the two halves if we were to split the partition along that axis. The split location is picked such that the variances of the two halves are minimal (using Otsu's algorithm). That is, the larger the priority, the more total variance we reduce by making the split. For each leaf node, we compute this value for each axis, and use the largest result.

*We process partitions on the queue until we have the desired number of partitions:

*

*We split the partition with highest priority along the axis and at the location computed when determining the priority.

*We compute the priority for each of the two halves, and put them on the queue.

This is a relatively simple algorithm when described this way, the code is somewhat more complex, because I tried to make it efficient but generic.
Comparison
On a 256x256x256 RGB histogram I got these timings comparing k-means clustering and this new algorithm:

# clusters
kmeans (s)
minvar (s)

5
3.98
0.34

20
17.9
0.48

50
220.8
0.59

Note that k-means needs more iterations as the number of clusters increases, hence the exponential time increase. Normally one would not use such a big histogram, I wanted to have large data to make the timings more robust.
Here is an example of these three methods applied to a test image:
Input:

Uniform with N=4 leading to up to 64 different colors [with N=2 to get 8 different colors and comparable to the other methods, the result is very ugly]:

K-means with 8 colors:

New "minimum variance" with 8 colors:

I like this last result better than the K-means result, though they are fairly similar.

This program illustrates how to do color quantization using DIPlib and its implementation of the minimum variance partitioning:
#include "diplib.h"
#include "dipviewer.h"
#include "diplib/simple_file_io.h"
#include "diplib/histogram.h"
#include "diplib/segmentation.h"
#include "diplib/lookup_table.h"

int main() {
   dip::Image input = dip::ImageRead( "/Users/cris/dip/images/flamingo.tif" );
   input.SetColorSpace( "RGB" ); // This image is linear RGB, not sRGB as assumed when reading RGB TIFFs.

   // Compute the color histogram.
   dip::Histogram hist( input, {}, { dip::Histogram::Configuration( 0.0, 255.0, 64 ) } );

   // Cluster the histogram, the output histogram has a label assigned to each bin.
   // Each label corresponds to one of the clusters.
   dip::uint nClusters = 8;
   dip::Image histImage = hist.GetImage(); // Copy with shared data
   dip::Image tmp;
   dip::CoordinateArray centers = dip::MinimumVariancePartitioning( histImage, tmp, nClusters );
   histImage.Copy( tmp ); // Copy 32-bit label image into 64-bit histogram image.

   // Find the cluster label for each pixel in the input image.
   dip::Image labels = hist.ReverseLookup( input );

   // The `centers` array contains histogram coordinates for each of the centers.
   // We need to convert these coordinates to RGB values by multiplying by 4 (=256/64).
   // `centers[ii]` corresponds to label `ii+1`.
   dip::Image lutImage( { nClusters + 1 }, 3, dip::DT_UINT8 );
   lutImage.At( 0 ) = 0; // label 0 doesn't exist
   for( dip::uint ii = 0; ii < nClusters; ++ii ) {
      lutImage.At( ii + 1 ) = { centers[ ii ][ 0 ] * 4, centers[ ii ][ 1 ] * 4, centers[ ii ][ 2 ] * 4 };
   }

   // Finally, we apply our look-up table mapping, painting each label in the image with
   // its corresponding RGB color.
   dip::LookupTable lut( lutImage );
   dip::Image output = lut.Apply( labels );
   output.SetColorSpace( "RGB" );

   // Display
   dip::viewer::ShowSimple( input, "input image" );
   dip::viewer::ShowSimple( output, "output image" );
   dip::viewer::Spin();
}

A: Fast pairwise nearest neighbor based algorithm with 8 colors
High quality and fast

Efficient, Edge-Aware, Combined Color Quantization and Dithering with 8 colors
Higher quality for 32 or less colors but slower

Spatial color quantization with 8 colors
Higher quality for 32 or less colors but the slowest

Sample c++ code
For the speed, it might be depending on GPU parallel programming C/C++.


text:
Q: Could every symmetric matrix $M=LDU$ be re-written as $L^{'}D^{'}{L^{'}}^{*}$ I'm taking Strang's linear algebra OCW with the textbook and met this proposition.
First, notations. ${}^{*}$ is taking (the usual operation for complex matrices) transpose conjugate, and ${}^{T}$ is taking transpose without transpose, s.t. $M^{T}_{i, j} = M_{j,i}$ and $M^{*}_{i,j} = \bar{M_{j, i}}$. Lower-triangular matrices, be it invertible or not, are denoted by $L$, similarly upper-triangular $U$, and diagonal $D$. There's no invertibility restrictions; $\begin{bmatrix}0 & 0 \\ 0 & 7i\end{bmatrix}$ is complex lower-triangular, hence calling it $L$ is valid; it's upper-triangular so this matrix could also be $U$; it's diagonal so maybe under the name $D$ is this matrix. In particular the identity matrix is also at the same time $U$, $D$ and $L$. $\begin{bmatrix} 0 & 7 \\ 0 & 0\end{bmatrix}$ is a $U$; neither $D$ nor $L$. Notice $L^{*}$ is actually a $U$, similarly $U^T$ is actually $L$. P(S)D refers to positive-(semi-)definite, similaly N(S)D.
You may want to view such definition as saying that the set of all lower-triangular matrices i.e. those with entries above the main diagonal equal $0$ is $L$, and I abused the notations a bit such that $L$ appearing in a formula is a concrete lower-triangular matrix rather than a set.
Here's the question: Suppose complex-valued Hermitian $M$ has complex factorization $LDU$, i.e. a product of complex lower-triangular matrix, complex diagonal matrix, and complex upper-triangular matrix, is it guaranteed that there exists some complex lower-triangular $L^\prime$ and complex diagonal $D^\prime$ such that $M$ also equals $L^\prime D^\prime {L^\prime}^{*}$? What about the analogue in real-valued matrices? I.e. suppose real-valued symmetric $M$ has real factorization $M=LDU$, is existence of some real lower-triangular $L^\prime$ and some real diagonal $D^\prime$ such that $M=L^\prime D^\prime {L^\prime}^T$ guaranteed? Again, all matrices here have no invertibility/P(S)D restriction. It's just their "shape" i.e. being either upper triangular, lower triangular, or diagonal, matters.
For example, given
$\begin{bmatrix} 1 & \frac{4}{5} & \frac{-4}{5} \\ \frac{4}{5} & 1 & \frac{4}{5} \\ \frac{-4}{5} & \frac{4}{5} & \frac{1}{100} \end{bmatrix} = M =
\begin{bmatrix}1 & 0 & 0 \\ \frac{4}{5} & 1 & 0\\ \frac{-4}{5} & 4 & 1 \end{bmatrix} I
\begin{bmatrix}1 & \frac{4}{5} & \frac{-4}{5} \\ 0 & \frac{9}{25} & \frac{36}{25} \\ 0 & 0 & \frac{-639}{100} \end{bmatrix} = LDU$
viewing it as a complex problem, one may say let $L^\prime = \begin{bmatrix}1 & 0 & 0 \\ \frac{4}{5} & \frac{3}{5} & 0 \\ \frac{-4}{5} & \frac{12}{5} & \frac{3\sqrt{71}i}{10} \end{bmatrix}$ and $D^\prime = \begin{bmatrix}1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & -1 \end{bmatrix}$ such that
$L^\prime D^\prime {L^\prime}^{*} = \begin{bmatrix}1 & 0 & 0 \\ \frac{4}{5} & \frac{3}{5} & 0 \\ \frac{-4}{5} & \frac{12}{5} & \frac{3\sqrt{71}i}{10} \end{bmatrix}
\begin{bmatrix}1 & 0 & 0 \\ 0 & 1 & 0 \\ 0 & 0 & -1 \end{bmatrix}
\begin{bmatrix}1 & \frac{4}{5} & \frac{-4}{5} \\ 0 & \frac{3}{5} & \frac{12}{5} \\ 0 & 0 & \frac{-3\sqrt{71}i}{10} \end{bmatrix}
=\begin{bmatrix} 1 & \frac{4}{5} & \frac{-4}{5} \\ \frac{4}{5} & 1 & \frac{4}{5} \\ \frac{-4}{5} & \frac{4}{5} & \frac{1}{100} \end{bmatrix} = M$
Below are my attempts trying to figure this out. First, I noticed this toy example:
$LDU = \begin{bmatrix}0 & 0 \\ 0 & 1\end{bmatrix} I
\begin{bmatrix}1 & 1 \\ 0 & 1\end{bmatrix}
=\begin{bmatrix}0 & 0 \\ 0 & 1\end{bmatrix} = M$
where at first glance is a contradiction in the real case, but I quickly realized it's not really a counter example since I could well re-write it as
$L^\prime D^\prime {L^\prime}^{T} = \begin{bmatrix}0 & 0 \\ 0 & 1\end{bmatrix}
\begin{bmatrix}0 & 0 \\ 0 & 1\end{bmatrix}
\begin{bmatrix}0 & 0 \\ 0 & 1\end{bmatrix}
=\begin{bmatrix}0 & 0 \\ 0 & 1\end{bmatrix} = M$
since the proposition is about existential proof for $L^\prime$ and $D^\prime$; it's very likely $L^\prime \neq L$ and $D \neq D^\prime$ albeit they are both lower-triangular/diagonal.
I'm lacking in linear algebra; in an attempt to figure out (search for) the answer myself, I've checked Cholesky decomposition, but it cares only about the equivalence between that a Hermitian $M$ being PSD and that $M = LL^{*}$, which is a bit off here, since the proposition allowed an optional $D^{'}$ in-between, which could easily ruin the PSD argument in Cholesky decomposition. The first example shows this, where $M=\begin{bmatrix} 1 & \frac{4}{5} & \frac{-4}{5} \\ \frac{4}{5} & 1 & \frac{4}{5} \\ \frac{-4}{5} & \frac{4}{5} & \frac{1}{100} \end{bmatrix}$ is not PSD.
Wikipedia page on Cholesky has section dedicated to $LDL^{*}$, and notes that it's indeed possible for matrices that does not have Cholesky decomposition (i.e. not PSD) to be written as $LDL^{*}$, but didn't mention if that's a universal fact.
I also checked the common argument that $\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}$ could not be written as $LDU$ let alone $L^{'}D^{'}{L^{'}}^{*}$, but that's also not the point here, since one of the premise for $M$ is that it's $LDU$ to begin with. (In some sense we should consider adding some permutation matrix $P$ s.t. $P\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix} = LDU$ and consider $M=P\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}$)
I'm only on chapter 2.7 of the aforementioned book; the proposition stems from this quote from Dr. Strang: "If $S=S^T$ is factored into $LDU$ with no row exchanges, then $U$ is exactly $L^T$". Given that his main focus in chapter 1 and 2 are often real invertible matrices, I assume he's talking about real invertible matrices, which is immediate given that $LDU$ is unique for invertible matrices if such factorization exists (for complex just use ${}^{*}$ instead and similar argument follows), but I'm wondering if the proposition still holds sans the invertible criteria.


text:
Q: mongoose/mongodb subdocument deep query and update Schema
var chapterSchema = new Schema({_id: Number, completed: Boolean})
var bookSchema = new Schema({  date: { type: Date, default: Date.now }, author: String,  chapter: chapterSchema })
var personSchema = new Schema({ _id: Number, name: String, books: [bookSchema] })

Sample object (person object)
{
  _id: 1,
  name: Bond,
  books: [{
    date: ISODate("2017-10-24T19:01:18.362Z"),
    author: Martin,
    chapter: {}
  }]
}

Subdocument (chapter object)
var chapter = new chapterSchema({_id: 1, completed: true})

Requirement
I would want to add the chapter object into the sample object (person.books)
Expected
{
  _id: 1,
  name: Bond,
  books: [{
    date: ISODate("2017-10-24T19:01:18.362Z"),
    author: Martin,
    chapter: {
      _id: 1,
      completed: true
    }
  }]

Tried
let todayStart = new Date()
todayStart.setHours(0,0,0,0)

Patient.findOneAndUpdate({'_id': 1, 'books.date': { $not: { $gt: todayStart } } }, {$set: {'books.$.chapter': chapter}}, {new: true, upsert: true}, (err, consultation) => {
  if (err) {
    console.error('[UPDATE] Failed to add chapter')
  } else {
    console.log('[UPDATE] chapter is added)
  }
})

I got 'Failed to add chapter' error
So, I tried to findOne to get any of fields in books subdocument.
Patient.findOne({'_id': 1, 'books.date': { $gt: todayStart } }, {"books.$.author": 1}, (err, data) => {
  if (err) console.log('[find] data not found')
  console.log('[FIND]' + JSON.stringify(data)
})

It gave me the following result,
{_id: 1, books: [{ date: ISODate("2017-10-24T19:01:18.362Z"), author: Martin, chapter: {} }]}

But, I was expecting only author here.
Eventually, I would like to know how to insert an object into subdocument in Mongodb/Mongoose.
P.S: new Date() I got from express.js, which does not matter here though.

A: This can help you:
db.yourDb.update(
    {
        "_id": 1,
        "books": {
            "$elemMatch": {
                "date": {
                    "$lte": ISODate("2017-10-24T20:01:18.362+0000")
                }
            }
        }
    },
    {
        "$set": {
            "books.$.chapter": { "_id": 1, "completed": true }
        }
    }
)

Remember though that if more than one book matches the query, the first one is updated.


text:
Q: Echo alert in php using jquery I'm new to the programming world, so take it easy.. I'm running some tests and i realise that when I use jQuery libraries outside of php to create a form, the echo inside the php doesn't work. I actually want an alert message but I found out that this can be done with
echo "<script>alert ('message')</script>";

but anyway echo is responsible for not seeing anything..
Is the problem the jQuery libraies (which I don't really think so..) or I'm just not knowing what I'm doing..?
What code could I use..?
Thank you in advance..!!

A: Your code should be:
echo '<script type="text/javascript">alert("message")</script>';

A: You need to wrap it in HTML script tags:
echo '<script>alert("message");</script>';

A: Probably you execute this code directly by the response from AJAX, or something went wrong with other JS code in your page.

A: Got it..!! I realise that with jQuery libraries the page refresh too fast after i submit my form and my code runs.. the fast refreshing doesn't leave any time to the alert message to pop-up. So that's it.. When i use my page without jQuery libraries takes a longer time to refresh after i submit and the pop-up.. well pops-up


text:
Q: From where do the encodings supported by Terminal come? If one goes into the Preferences of Terminal.app, there is an "Encodings" tab.  From where does this list come?  How can one add further encodings?

A: At the bottom of the encodings menu you should see "Customize List".  Select that and it will give you the full list of 100 or so available.  Is what you need not on that?
A reference for Apple's Text Encoding Converter, which probably provides this function, is at
https://developer.apple.com/library/mac/documentation/Carbon/reference/Text_Encodin_sion_Manager/Text_Encodin_sion_Manager.pdf
iconv includes ucs-2 in case that is of any use:
https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/iconv_open.3.html