How can I make a field of "Content: Type" visible to users who do not have the "Administer content types" permission?

Question: I am trying to create a view which shows new posts of certain content types, including the name of the content type. So, e.g., "New How To: Displaying Content Type Fields in Views". Here are the fields:

Content: Title [hidden]
Content: Type [hidden]
Global: Custom Text
Content: Authored on

The "Global: Custom Text" field is a combination of the first two fields as "New {{ type }}: {{ title }}". The issue I have is this: The "Type" field appears blank for anonymous users unless I grant them the "Administer content types" permission. This is not an acceptable solution.
Is there a clean way to display this for anonymous users? Maybe a permission I'm missing? Relatedly, is there any danger in allowing users to see this?
I'm working with Drupal 8.0.0-beta14 (the latest at the time of this question). The code for the exported view is below if it helps.
uuid: 48ef9d3a-8278-4bc5-b13e-62eec03bad09
langcode: en
status: true
dependencies:
  config:
    - node.type.blog_post
    - node.type.how_to
  module:
    - node
    - user
id: news_items
label: 'News Items'
module: views
description: ''
tag: ''
base_table: node_field_data
base_field: nid
core: 8.x
display:
  default:
    display_plugin: default
    id: default
    display_title: Master
    position: 0
    display_options:
      access:
        type: perm
        options:
          perm: 'access content'
      cache:
        type: tag
        options: {  }
      query:
        type: views_query
        options:
          disable_sql_rewrite: false
          distinct: false
          replica: false
          query_comment: ''
          query_tags: {  }
      exposed_form:
        type: basic
        options:
          submit_button: Apply
          reset_button: false
          reset_button_label: Reset
          exposed_sorts_label: 'Sort by'
          expose_sort_order: true
          sort_asc_label: Asc
          sort_desc_label: Desc
      pager:
        type: full
        options:
          items_per_page: 4
          offset: 0
          id: 0
          total_pages: null
          tags:
            previous: '<<'
            next: '>>'
            first: '|<'
            last: '>|'
          expose:
            items_per_page: false
            items_per_page_label: 'Items per page'
            items_per_page_options: '5, 10, 25, 50'
            items_per_page_options_all: false
            items_per_page_options_all_label: '- All -'
            offset: false
            offset_label: Offset
          quantity: 3
      style:
        type: html_list
        options:
          grouping: {  }
          row_class: list-group-item
          default_row_class: true
          type: ul
          wrapper_class: ''
          class: list-group
      row:
        type: fields
      fields:
        title:
          id: title
          table: node_field_data
          field: title
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: true
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: false
            ellipsis: false
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: value
          type: string
          settings:
            link_to_entity: true
          group_column: value
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: node
          entity_field: title
          plugin_id: field
        type:
          id: type
          table: node_field_data
          field: type
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: true
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          click_sort_column: target_id
          type: entity_reference_label
          settings:
            link: false
          group_column: target_id
          group_columns: {  }
          group_rows: true
          delta_limit: 0
          delta_offset: 0
          delta_reversed: false
          delta_first_last: false
          multi_type: separator
          separator: ', '
          field_api_classes: false
          entity_type: node
          entity_field: type
          plugin_id: field
        nothing:
          id: nothing
          table: views
          field: nothing
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: true
            text: 'New {{ type }}: {{ title }}'
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: false
          plugin_id: custom
        created:
          id: created
          table: node_field_data
          field: created
          relationship: none
          group_type: group
          admin_label: ''
          label: ''
          exclude: false
          alter:
            alter_text: false
            text: ''
            make_link: false
            path: ''
            absolute: false
            external: false
            replace_spaces: false
            path_case: none
            trim_whitespace: false
            alt: ''
            rel: ''
            link_class: ''
            prefix: ''
            suffix: ''
            target: ''
            nl2br: false
            max_length: 0
            word_boundary: true
            ellipsis: true
            more_link: false
            more_link_text: ''
            more_link_path: ''
            strip_tags: false
            trim: false
            preserve_tags: ''
            html: false
          element_type: ''
          element_class: ''
          element_label_type: ''
          element_label_class: ''
          element_label_colon: false
          element_wrapper_type: ''
          element_wrapper_class: ''
          element_default_classes: true
          empty: ''
          hide_empty: false
          empty_zero: false
          hide_alter_empty: true
          date_format: custom
          custom_date_format: 'Y-M-d g:i:s A'
          timezone: America/Toronto
          entity_type: node
          entity_field: created
          plugin_id: date
      filters:
        status:
          value: true
          table: node_field_data
          field: status
          plugin_id: boolean
          entity_type: node
          entity_field: status
          id: status
          expose:
            operator: ''
          group: 1
        type:
          id: type
          table: node_field_data
          field: type
          relationship: none
          group_type: group
          admin_label: ''
          operator: in
          value:
            blog_post: blog_post
            how_to: how_to
          group: 1
          exposed: false
          expose:
            operator_id: ''
            label: ''
            description: ''
            use_operator: false
            operator: ''
            identifier: ''
            required: false
            remember: false
            multiple: false
            remember_roles:
              authenticated: authenticated
            reduce: false
          is_grouped: false
          group_info:
            label: ''
            description: ''
            identifier: ''
            optional: true
            widget: select
            multiple: false
            remember: false
            default_group: All
            default_group_multiple: {  }
            group_items: {  }
          entity_type: node
          entity_field: type
          plugin_id: bundle
      sorts:
        created:
          id: created
          table: node_field_data
          field: created
          order: DESC
          entity_type: node
          entity_field: created
          plugin_id: date
          relationship: none
          group_type: group
          admin_label: ''
          exposed: false
          expose:
            label: ''
          granularity: second
      title: 'News Items'
      header: {  }
      footer: {  }
      empty: {  }
      relationships: {  }
      arguments: {  }
      display_extenders: {  }
      css_class: ''
      use_ajax: true
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      cacheable: false
  block_1:
    display_plugin: block
    id: block_1
    display_title: Block
    position: 1
    display_options:
      display_extenders: {  }
    cache_metadata:
      contexts:
        - 'languages:language_content'
        - 'languages:language_interface'
        - url.query_args
        - 'user.node_grants:view'
        - user.permissions
      cacheable: false

Answer: Sounds like there is a field permission on the type field that prevents view access.
Not quite sure where that happens, actually, that would be in NodeAccessControlHandler::checkFieldAccess(), as you can see, that for example limits edit access on certain fields, but there's nothing about type, so that should be editable.
Ah.. maybe the field checks view access of the referenced entity, and node types aren't viewable by anonymous users, so it doesn't display it.
We have similar problems with e.g. referenced users, since Drupal doesn't have a generic concept of a "view label" access.
You could try to open a core issue and in NodeTypeAccessControlHandler::checkAccess(), allow view access if you have the access content permission or so, but it's tricky.. since that will e.g. also allow access to all values in it (like the settings for it), in case there is a generic check for it (e.g. REST).


systemd --user for normal graphical applications

Question: I'm trying to set up systemd to start some programs when I log in. I'm doing this by putting files in e.g. ~/.config/systemd/user/some.service. This has worked for my emacs server service, which looks like this:
[Unit]
Description=Emacs: the extensible, self-documenting text editor

[Service]
Type=forking
ExecStart=/usr/bin/emacs --daemon
ExecStop=/usr/bin/emacsclient --eval "(kill-emacs)"
Environment=SSH_AUTH_SOCK=%t/keyring/ssh
Restart=always

[Install]
WantedBy=default.target

This starts a background process and allows me to connect to the emacs service with emacsclient
What's not working is my terminator service:
[Unit]
Description=The only terminal emulator that seems to be somewhat decent

After=multi-user.target

[Service]
ExecStart=/usr/bin/terminator
Restart=always
Environment=DISPLAY=:0

[Install]
WantedBy=default.target

With this code in ~/.config/systemd/user/terminator.service I can start terminator on the command-line with systemctl --user start terminator, but I can't get terminator to start automatically on (graphical) login. I've tried messing around with the WantedBy and After lines, switching between to graphical.target, default.target and multi-user.target, but it's really just guess work and hasn't helped.
Any ideas?
Answer: your terminator service file looks okay to me.
check below things
1. just check "default.target" file, is this below line present in that file
After=multi-user.target
2. if you write "WantedBy=default.target" then you need to create a soft link of terminator.service file inside "default.target.wants/" directory.
if this above two are correct, it should get start.
If still doesn't work, please remove "After=multi-user.target" this line, and change Wantedby as "WantedBy=graphical.target".
let me know the status of service after login
systemctl status terminator.service
Answer: Systemd is not the right tool for this task because it doesn't know when you have finished logging in in a desktop environment and it's possible to launch terminator.  Instead, you could put a symlink to terminator's desktop file in your ~/.config/autostart :
ln -s /usr/share/applications/terminator.desktop ~/.config/autostart/

Most desktop interfaces (Gnome, KDE, Unity) will launch it when they start.
Comment: but if you do it this way you lose the automatic restart functionality. also if this is the problem systemd is doing a terrible job of communicating it to the user...


Generating a taxonomy

Question: I have a list of items that I need turned into a taxonomy. My list looks something like this:
<code>Apple
    Apple 1a
    Apple 1b
    Apple 2a
    Apple 2b
    ...
    Apple 192b
Banana
    Banana 1a
    Banana 1b
    Banana 2a
    Banana 2b
    ...
    Banana 96a
....
More Items
    More Items 1a
    ....
    More Items 300b
</code>
Anyway you get the idea. Creating new terms for each of these isn't going to work in this case , it'll take days. Is there any way to bulk create from a text file like this?
Answer: If you can get your terms into CSV format you can use the excellent Taxonomy CSV import/export module:

This module allows you to import or export taxonomy from or to a CSV (comma-separated values) file or with a copy-and-paste text.

It has support for importing hierarchical trees like yours, and even supports drush.
It also has good documentation to get you started.
EDIT
You could also try the Taxonomy import/export via XML module which does the same thing but for XML (if you find it easier to get your data into that format). It's only in dev release at the moment but its worth a try.
Answer: Alternatively you can use the Feeds module as it allow syou to both upload a file and create taxonomy terms based on the input. It is a little more configurable and as a result powerful but might be a little more difficult to setup.
If CSV gets the job done easily for you go with it otherwise i KNOW feeds can intelligently do what you need. Espercially if you combine it with feeds_tamper and a custom parser form contrib.

Generating a taxonomy


Proving that these two finite alternating series are equal.

Question: For all natural numbers $n$, prove that
$$ \sum_{r=0}^n \left( \frac{ (-1)^r {n \choose r} } {2r+1} \right)
= 4^n \sum_{r=0}^n \left( \frac{ (-1)^r {n \choose r} } {n+r+1} \right)$$
I have tried to do this by induction, but I'm not getting anywhere with that:
$$
\sum_{r=0}^{k+1} \left( \frac{ (-1)^r { k+1 \choose r} } {2r+1}\right)
\\ = 1 + \sum_{r=1}^{k} \left( \frac{ (-1)^r ( { k \choose r} + { k \choose r-1}) } {2r+1}\right)  + \frac{(-1)^r}{2k+3}
\\ = 4^k \sum_{r=0}^k \left( \frac{ (-1)^r {k \choose r} } {k+r+1} \right) + \sum_{r=1}^{k} \left( \frac{ (-1)^r { k \choose r-1} } {2r+1}\right)  + \frac{(-1)^r}{2k+3}
$$
... Which is nowhere close to the desired $4^{k+1} \sum_{r=0}^{k+1} \left( \frac{ (-1)^r {k+1 \choose r} } {k+1+r+1} \right)$
Here are a few verified values, I have tested them up to $n=30$ and they all work. When the numbers get too large, my program gets a little inconsistent with the calculations. But WolframAlpha still manages, when $n=10000$, LHS = RHS $\approx 0.0088619369$.
$$ \begin{array}{|c|c|c|}
\hline
\text{n}& \text{LHS} & \text{RHS}  \\ \hline
0& 1& 1\\ \hline
1& \frac{2}{3}& \frac{2}{3}\\ \hline
2& \frac{8}{15}& \frac{8}{15}\\ \hline
3& \frac{16}{35}& \frac{16}{35}\\ \hline
4& \frac{128}{315}& \frac{128}{315}\\ \hline
5& \frac{256}{693}& \frac{256}{693}\\ \hline
6& \frac{1024}{3003}& \frac{1024}{3003}\\ \hline
7& \frac{2048}{6435}& \frac{2048}{6435}\\ \hline
8& \frac{32768}{109395}& \frac{32768}{109395}\\ \hline
9& \frac{65536}{230945}& \frac{65536}{230945}\\ \hline
10& \frac{262144}{969969}& \frac{262144}{969969}\\ \hline
\end{array}$$
Comment: For large $n$ I'm sure any discrepancies are due to numerical phenomena such as rounding error, underflow etc.
Answer: The left hand side equals
$$\sum_{r=0}^n(-1)^r\binom{n}r\int_0^1 x^{2n}\,dx=\int_0^1(1-x^2)^n\,dx.\tag{1}$$
The left hand side equals
$$4^n\sum_{r=0}^n(-1)^r\binom{n}r\int_0^1 x^{n+r}\,dx=4^n\int_0^1x^n(1-x)^n\,dx.
\tag{2}$$
The integral (1) equals
$$\frac12\int_{-1}^1(1-x^2)^n\,dx$$
and if we substitute $y=(1+x)/2$ we get
$$\int_0^1(4y(1-y))^n\,dy$$
which is (2).
Answer: We may recall the partial fraction decomposition of the reciprocal Pochhammer symbol:
$$ \frac{1}{x(x+1)(x+2)\cdot\ldots\cdot(x+n)}=\frac{1}{(x)_{n+1}}=\frac{1}{n!}\sum_{k=0}^{n}\frac{(-1)^{k}\binom{n}{k}}{x+k} $$
and simply evaluate both sides at $x=1$ and $x=\frac{1}{2}$.


When can index funds buy shares of a new stock in the index?

Question: Apology again for When can index funds buy shares of a new stock in the index?. How can I make in on topic? What's wrong with it? Just edit my post in any way you see fit!
Are there too many quotations? I felt there was, but I kept them to show all the conflicting comments.
Answer: I do not think that the question is good fit for this site to begin with and in addition it is posed in an unclear manner.

The question is not about economics at all. When and if some index fund can buy some share depends on both external and internal regulations of that company.  For external regulations you will want to ask question at some law related site, for internal regulations you would have to mail the company directly or enquire at their site. Either way the question would not fit this site's scope. Hence in order to reopen it here you should first change it to be about economics.

The whole body of a question does not even contain a question, you just state bunch of opinions from reddit and comment on how you are "befuddled" by them. This:
a) makes it look like you are looking for opinions on those reddit posts - this is why I think people likely closed the question as opinion-based (although I cannot see into their heads and I did not casted my mod vote here).
b) posting just excerpts from reddit does not show any research effort since in this case it is just bunch of opinions of random strangers without any supporting evidence/research. Even if the question have been about economics I doubt that posting those comments would be received well.


Como incluir um valor na última linha de um data.frame no R

Question: Tenho um data.frame e um valor no R, precisava que este valor fosse incluído na última linha de determinada coluna deste data.frame. Já testei a função rbind mas não funcionou.
x <- c(1:15)
y <- c(1:15)
z <- 4
df <- data.frame(x,y)
df <- rbind(x, z)

Comment: A pergunta não está bem formulada. Qual é a resposta esperada para ela, já que `df` possui duas colunas e `z` possui apenas uma observação? A última linha deve ser formada por `c(4, 4)`? Ou `c(NA, 4)`? Ou ainda `c(4, NA)`? Por favor, verifique isso e seja mais claro a respeito de suas necessidades.
Comment: Perdão, o valor de Z deveria ser incluído na última linha de X, portanto, c(4, NA)
Comment: Mas `x` só tem uma dimensão. Por acaso `c(4, NA)` deveria ser a última linha de `df`?
Comment: Sim, o df deveria ficar com 16 linhas, e a última ser c(4, NA)
Answer: Crie o data frame z com as observações desejadas, atentando para que os nomes de suas colunas condigam com os nomes das colunas de df:
x <- c(1:15)
y <- c(1:15)
df <- data.frame(x,y)
names(df)
# [1] "x" "y"

z <- data.frame(x = 4, y = NA)
df <- rbind(df, z)
df
#     x  y
# 1   1  1
# 2   2  2
# 3   3  3
# 4   4  4
# 5   5  5
# 6   6  6
# 7   7  7
# 8   8  8
# 9   9  9
# 10 10 10
# 11 11 11
# 12 12 12
# 13 13 13
# 14 14 14
# 15 15 15
# 16  4 NA

Answer: Você pode adicionar valores em quaisquer posições diretamente, não é necessário criar um objeto só para isso:
df <- data.frame(x = 1:15,
                 y = 1:15)

df[nrow(df)+1, "x"] <- 4

> tail(df)
    x  y
11 11 11
12 12 12
13 13 13
14 14 14
15 15 15
16  4 NA

Se a posição já existir, o valor é substituído. Se não, o data.frame é redimensionado e NAs inseridos por omissão.


'Worksheet' object has no attribute 'cell'

Question: I need to open an xlsx document and color it. But I don't understand why it shows cell error it. My algorithm works like this:
Open xlsx,  writer = pd.ExcelWriter(path, engine='xlsxwriter')
worksheet = writer.sheets['Sheet1']

col_style = Font(name = "Reem Kufi", size = 12, color = "DB3B22", italic =True)

for i in range(2,40):
    worksheet.cell(row = i, column = 3).font = col_style

Error:- 'Worksheet' object has no attribute 'cell'
Comment: Looks like you're trying to use the methods for one library on another.
Answer: you will need to use Openpyxl's loadworkbook instead of ExcelWriter to achieve what you are looking for. Updated code here. Note that I have only changed the initial open file and sheet using the new code and required libraries and not changed rest of your code.
from openpyxl.styles import Font
from openpyxl import load_workbook
writer = load_workbook(filename='YourFile.xlsx')

worksheet = writer['Sheet1']

col_style = Font(name = "Reem Kufi", size = 12, color = "DB3B22", italic =True)

for i in range(2,40):
    worksheet.cell(row = i, column = 3).font = col_style

writer.save('YourFile.xlsx')


Backbone, Getting the id/name of the of changed element

Question: I am using Backbone.js with stickit for binding. I have something like below. How do I know which element the user has clicked? (Radio buttons)
<code>initialize: function() {
  this.listenTo(this.model, 'change', this.blockDiv);
}
blockDiv : function() {
  console.log('The changed element is '+); //How do i know which element the user has changed?
}
bindings : {
  '[name=element1]' : element1,
  '[name=element2]' : element2
}
</code>
Answer: You are listening changes from your model, not DOM events directly. You can check what attributes of model have changed with changedAttributes.


how to create a list a two columns list with variables in python

Question: I need to create a two column list with two variables.
the variables are two outputs that I get, and I need to make a list with them.
vara
varb
list=[vara,varb]
how do I create, print and initialize?
thanks
Answer: I'll start by warning you that this sort of question does not fly on Stack Overflow. I don't take personal issue with it, but I'd be cautious about asking similar questions - that is to say, questions that are vague and demonstrate a lack of independent research - in the future, as members here have a reputation of being fairly unkind to people that ask such questions.
That out of the way, I'll answer the question as best I can, with what little information I have. It sounds like you've got two variables, let's give them some random numerical values:
<code>a = 1
b = 2
</code>
and you want to know how to make a list with two elements made up of these two variables. In that case, you do it like this:
<code># two variables
a = 1
b = 2

# make a list
my_list = [a, b]
</code>
Easy as that.


When I POST an image file via rest, response is 201: Object Moved, status is temporary

Question: I'm attempting to POST images to Drupal 8 via the REST api.  The creation is successful (201) and the images appear in the files list.  However, there are problems. I'm not sure if they are independent of one another of is they are related.
1.The images are created with a temporary status.  Would prefer "permanent".
2.The MIME type is set to "application/octet-stream" and the images don't render.  I've discovered that by chaning the "uri" in the json object I'm posting to be an explicit uri like "public://photograph.jpg", the MIME type gets set to image/* and this work.
This is the code i'm using:

Comment: you could use hook_entity_insert to see if type file and then update the status
Comment: See my answer here: https://drupal.stackexchange.com/questions/298977/image-files-uploaded-via-rest-got-temporary-status-cannot-be-refereced-by-medi/299098#299098
Answer: Suggestions

I think filemime is autogenerated depending on the file you're uploading.
To make the file permanent, have you tried sending the property status: [value: 1]?

A status of 1 indicates that the file is permanent.


Is it okay to use drupal_goto() from within a node?

Question: I implemented a node that automatically adds a product to a cart using this function uc_cart_add_item(33);
but I want it to then redirect the visitor to the check out page.  I saw that drupal has a drupal_goto() function however this is essentially just a php Header(location: http://mysite.com/cart/checkout)  which usually shouldn't work if it is not done so before any content is spit out.
Now I got this to work and everything but I never liked the idea of just getting it to work, I'd like to get it right.  I thought of a script outside of the drupal environment but wasnt sure if I could use the ubercarts functions.  Does anyone have any ideas on a better way or is the using drupal_goto() within a node okay?
Just to say and I saw someone else who had a similar problem was that this did work, however the cron job time exceeded the time limit after I implemented this.  SO maybe not a good option like i thought.
Answer: It is a bad idea and I wouldn't recommend doing it.  The cron error you see is most likely due to the Search module. During cron while the Search module is trying to index content, if it reaches a node containing a drupal_goto() it will hang and cron will error which could lead to more problems
Answer: It's a bad idea to use it in the nodeapi. Drupal uses the decorator pattern in this API and interrupting that with a redirect won't give the other modules a chance to operate on the node.
Assuming you're submitting a form: The form API (which also uses the same pattern) will let you redirect with $form['#redirect']. But be sure to use the global $base_url in your path. It's a caveat in the form API.
Something like:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  global $base_url;
  $form['#redirect'] = $base_url .'/path';
}

You'd probably want to avoid hard coding the path but that should point you in the right direction...
Answer: This is what I used when we really needed drupal_goto() without creating modules to do it (D6)

//normally script name is index.php, but is cron.php if it's loaded via cron
//do not execute the drupal_goto if script name is cron.php,
// or if the node is loaded for anything other than being viewed

$script_name= str_replace(base_path(), '', $_SERVER['SCRIPT_NAME']);

$arg0 = arg(0);
$arg2 = arg(2);

if($script_name != 'cron.php'
   && $_SERVER['REQUEST_URI'] != '/admin/reports/status/run-cron'
   && $_SERVER['REMOTE_ADDR'] != $_SERVER['SERVER_ADDR']
   && !($arg0 == 'node' && !empty($arg2)))
{
  drupal_goto('node/123');
}

?>

Answer: Assuming that within a node means when viewing a node page, it is possible to safely call drupal_goto(). In a hook_nodeapi() when $op == 'view' (Drupal 6) or hook_node_view() (Drupal 7) implementation, you should take care to call drupal_goto() only if the node is actually viewed as a full page. This will prevent other modules' hooks to run, but as they should only add content to display to $node->content, this shouldn't be an issue.
In Drupal 6, something like
function MODULE_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($op == 'view' && $a3 === FALSE && $a4 == TRUE) {
    $page_node = menu_get_object();
    if (!empty($page_node) && $page_node->nid == $node->nid) {
      //It is safe to call drupal_goto() from here
    }
  }
}

In Drupal 7, something like
function MODULE_node_view($node, $view_mode, $langcode) {
  if ($view_mode == 'full' && node_is_page($node)) {
    //It is safe to call drupal_goto() from here
  }
}

It is unsafe to call drupal_goto() for all the other values of $op or from other hook_node_* implementations. drupal_goto() will end the request processing and prevent hooks from other module to run.


c++ sort custom function

Question: I need to be able to pass in a variable by which to sort. I noticed that it only takes in the types that it will be sorting so I was wondering if it is possible to do something like that.
For example I need it to sort arrays each containing 3 integers by their 3rd int. How would you make a function like that if you did not know in advance what value you would be sorting by?
Comment: `std::sort` takes a custom comparator.
Comment: Please, read about [`std::sort`](http://en.cppreference.com/w/cpp/algorithm/sort), about [`Compare`](http://en.cppreference.com/w/cpp/concept/Compare) requirements, then try writing some code.
Comment: I have an input I give my function which changes how everything is sorted. Is there a way to pass said input to the functioin somehow? Because I am a bit pressed for time and I am unfortunately unable to write a function for every possible sort that could be done.
Comment: You have two options: 1. Use global variable(s) to control your comparator function behavior at run-time (simple, but ugly); 2. Create [function object](https://en.wikipedia.org/wiki/Function_object#In_C_and_C.2B.2B) that would have adjustment options you want as part of its state, and use it instead of your function.
Comment: And please show the code you've written so far.
Comment: I need an idea if you have the time.
if args were 1,2,3 then my program would have to sort by 1st column values BUT if two values are equal then it has to try to sort those two by the values in column 2 and so on. How would you write something like that because I just finished rewriting my code 8 times over 7 hours.

 Edit you don't really want to see the code I think.
Comment: @n0rd here is some source code
http://pastebin.com/4RBP0Trn
Answer: You said "For example I need it to sort arrays each containing 3 integers by their 3rd int," and that you won't know which index (which column) is significant until run time.
If you are able to use C++11, it can be this simple:
void mysort(vector<vector<int>>& v, int col)
{
    sort(v.begin(), v.end(),
         [col](const vector<int>& a, const vector<int>& b) -> bool
               { return a[col] < b[col]; });
}

If you are restricted to C++98, you can do the same thing, but instead of a lambda, you must write a functor that takes the column as a constructor parameter:
class ColumnSort {
    int col_;
public:
    ColumnSort(int col): col_(col) { }
    bool operator()(const vector& a, const vector& b) const {
        return a[col_] < b[col_];
    }
};

void mysort(vector< vector<int> >& v, int col)
{
    sort(v.begin(), v.end(), ColumnSort(col));
}

Finally, if you want a multi-column sort, the functor would look like this, where cols is an ordered list of columns to sort on:
class ColumnSort {
    vector<int> cols_;
public:
    ColumnSort(const vector<int>& cols): cols_(cols) { }
    bool operator()(const vector<int>& a, const vector<int>& b) const {
      for (int i = 0; i < cols_.size(); ++i) {
        if (a[cols_[i]] == b[cols_[i]]) continue;
        return a[cols_[i]] < b[cols_[i]];
      }
      return false;
    }
};

Comment: Is `bool operator(...)` correct?  I am used to seeing something following *operator*.
Comment: @wallyk: You're quite right. The correct signature is `bool operator()(...)`, and I've edited my code to include that fix. (Also fixed my C++11 example which was missing `` from `vector`.)
Comment: That looks like exactly what I need. But how would you deal with col being a vector containing multiple commands? It could say sort by col 1 but if a[col] == b[col] then sort by the next thing in the vector.
Comment: @DerekJones Right now I am trying with this http://pastebin.com/MvGdEkye but it doesnt want to sort at all
Comment: @TheUnknown: Sorting by multiple columns is solved the same way, except that you would pass a series of columns to your comparator, and your comparator would need to make the cascaded checks you describe.
Comment: @TheUnknown: I took a quick look at your code in pastebin, and although the comparators look OK to me, the `sortit()` function looks fairly confused. As in my answer above, I'd suggest that you give your functors to `std::sort()` and let that algorithm do its job.
Comment: @DerekJones There are a whole bunch of cases given to us. The command to function can be. 1) A number; 2) A Number and a String; 3) A Negative number; 4) A negative number and string;
I test for all those because negative numbers cause their strings to be sorted backwards. And numbers with string "s" next to them are sorted without being converted back from string.
Comment: @DerekJones Actually is there a way to for (auto x : comm ) loop backwards? If I can do that my code will work now.
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/82345/discussion-between-derek-jones-and-theunknown).
Answer: You can use a custom comparator constructed with the information about your custom sort order. You do it sort of like this.
// Normal sort, except the specified value always comes first
class LessThanWithPreferedValue {
    int n;
public:
    LessThanWithPreferedValue(int v) : n(v) {}

    boolean operator()( int a, int b ) const {
       if( a==n ) { return true ; }
       if( b==n ) { return false ; }
       return a<b;
    }
};

int main() {
  std::vector<int> v = { 2, 3, 4 , 6 ,8 };

  // Normal sort, but with 4 first
  std::sort(v.begin(), v.end(), LessThanWithPreferedValue(4) );
  // v = { 4, 2, 3, 6, 8}

  // Normal sort, but with 8 first
  std::sort(v.begin(), v.end(), LessThanWithPreferedValue(8) );
  // v = { 8, 2, 3, 4, 6}
}

Comment: How would you handle the case if for example you have a vector inside of which you have the info by which to sort. I basically am sorting vectors of vectors based on the values inside of the said vectors.

By the way this was very helpful I will be trying this now.
Answer: Write a functor that takes arguments to determine how to sort. Here's a simple example that takes an argument to switch between ascending and descending order:
template<typename T>
class ReversibleComparator {
    bool asc;
public:
    ReversibleComparator(bool asc) : asc(asc) {}
    // This function performs the comparison,
    // returning true if a should come before b.
    bool operator()(const T& a, const T& b) {
        if(asc) return a < b;
        else return b < a;
    }
};

Of course, you could have as many parameters to the constructor as you want (or multiple constructors) and make the logic as complicated as you want, though it'll be called a lot, so making it really complicated would probably not be a good idea.
An example of calling it:
bool asc = true;
if(argc > 1 && argv[1] == string("-d"))
    asc = false;
std::sort(my_list.begin(), my_list.end(), ReversibleComparator(asc));

(Also, this example is a little contrived, since if what you want is to reverse the ordering, you can simply use rbegin() and rend() in place of begin() and end() respectively.)
Comment: Thanks. I have a lot of writing to do to make this work with what I am doing but I think I might be able to
Answer: Here I describe the C rtl qsort, but it is almost certainly almost the same as the c++ variant:
The sort function takes as a parameter a "comparison function".  Each time the comparison function is called it is passed two parameters which are pointers to the two elements to compare.
After coercing the type of the parameters, you can then compare anything you want.  For example, if the elements contain some struct with an integer array and you want to compare the nth items in them where the program's first parameter tells which column, something like this will work:
int which_index = (int) strtol (argv[1]);

int comparefunc (void *item1, void *item2)
{
     widget *w1, *w2;
     w1 = (widget *) item1;
     w2 = (widget *) item2;

     return w1->myarray[which_index] - w2->myarray[which_index];
}

widget table[1000];
qsort (table, n, sizeof table[0], comparefunc);

Comment: Why not? 1) `qsort()` is not type-safe - if you tell it your elements are 5 bytes large when they're actually 8 bytes large, it will happily go and sort bogus data. 2) `qsort()` is _slower_, partly because it's not guaranteed to actually use the quick-sort algorithm and partly because it's accessing the data through a double layer of indirection (rather than the single layer in `std::sort()`) 3) `qsort()` has no idea how large your array really is. It'll happily go and bogus data in uninitialized memory if you let it.
Comment: sadly std::sort works with ranges. It is rather similar to qsort in some ways like the way that the compare functions work. The main problem for me is that. I have a set of rules that are passed in through command line and I have to have my compare function follow those.
Comment: @TheUnknown:  Any reason you can't use the C `qsort()` function then?
Comment: How would you account for the different possible inputs for sorting?
The user is allowed to input unlimited amounts of arguments.
Comment: I really don't recommend `qsort()` when writing C++ code.
Comment: @TheUnknown:  What do the arguments mean?  If they are data to sort, that is easy:  put them in the array.  If they affect the sorting algorithm, you might have to construct an expression evaluator and run that inside the compare function.
Comment: @celticminstrel:  Why not?
Comment: @wallyk The arguments are numbers which stand for columns of data to be sorted. Imagine my data as a 2d matrix. Rows are vector and coluimns are string values inside vertically. So basically if my program gets an argument 1 I have to sort my vector> by the first value of each vector. What makes this tough is that when two values in a column are equal I sort by the next passed in value through arguments.
Comment: @TheUnknown:  I have updated my answer with what I think you are asking for by using a global variable.

c++ sort custom function


RTSP player performance

Question: I am struggling with rtsp playing performance i tried android mediaplayer to play the rtsp link but the delay is about 5 second. Then i came to know about Gstreamer and ffmpeg i have started exploring the gstreamer library to create a rtsp player there is a post on android which says that you can get the performance of <500ms delay.
So is there is any work done on android to acheive that performance or i have to create it by myself
Answer: Take a look at this ffmpeg to android solution. At the bottom of the page you will find link to the tutorials with simple implementation. After some minor edits you should be able to get playback with delay <500 ms.
Comment: are you sure you share the correct link i didn't see any sample project  there
Comment: Yes, I'm sure. [Here](https://github.com/roman10/android-ffmpeg-tutorial) is the tutorial project which you can find at the bottom of the compile guide.
Comment: BTW do you have personal experience with this, i mean playring rtsp using ffmpeg
Comment: Yes. Besides the above configuration, I am using ffserver to stream rtsp and I get quite a small delay with it.
Comment: okay i will give it a hit and get back to you, in case of any issue.
Comment: Right now i am working on gstream too. So may b i can get my thing done with this
Comment: Cool. If you manage to get decent delays pls let me know that it's possible
Comment: I am able to run rtsp link throught gstreamer but it has a delay of 2.2 sec.
Comment: Nothing special. I don't know much about gstreamer but try to find out if your app buffers some frames before displaying them

RTSP player performance


THREE.js OBJLoader - load to Geometry, manipulate, then save to BufferGeometry

Question: I'm trying establish why I can't smooth shade geometry loaded with OBJLoader.
var loader = new THREE.OBJLoader(manager);
loader.load('/manmodel/js/man.obj', function (object, materials) {
    console.log(object);
    console.log(materials);
    man = object;
    man.traverse(function (child) {
        if (child instanceof THREE.Mesh) {
            child.geometry.computeFaceNormals();
            child.geometry.computeVertexNormals( true );
            child.material = new THREE.MeshPhongMaterial({
                color: 'white',
                shading: THREE.SmoothShading // <-----------  THIS IS THE PROBLEM
            });
        }
    });
    man.position.y = -10;
    scene.add(man);
});

This is the result:

If I remove the line computeFaceNormals() the model renders the same.
If I remove computeVertexNormals( true ) the object renders with no lighting (black) - so I know this is doing something.
If I change the color attribute of the MeshPhongMaterial in this code, the color changes, so I also know that this is working.
I have tried to use the vertex and normal helpers to establish what the problem is, but they fail because with BufferGeometry the faces and verticices are not stored as arrays.
I have also tried modifying the man.obj file to change the 's' values from 'off' to 1. This did nothing.
As I will be loading several .obj files for different human figures, generated in Blender, and each is currently around 2MB, I prefer to do the shading on the browser than to 'bake' it into the file if this would increase file size.
THE QUESTION(s): Am I missing something here? OR,
Is there a way to load the .obj file as standard Geometry, compute the normals, apply the shading, and then save as BufferGeometry?
ps. I may also need the normals for ray tracing further down the line.
Answer: The most recent version of ObjLoader parses the .obj to a BufferGeometry for performance reasons.  If you look back through the history on GitHub you can find the previous version which parses to Geometry:
https://github.com/mrdoob/three.js/blob/a321ba05f02ae3a1586a4060a53f5ad63b90729b/examples/js/loaders/OBJLoader.js
Load your .obj using this and you can then manipulate the Geometry until you have it as you need it, then create a new BufferGeometry and load the Geometry into it using BufferGeometry.fromGeometry(geometry) in order to get the performance.  I have this working nicely.
Answer: If we want to use the most recent loader (r73), we can also convert the BufferGeometry to a Geometry, and then back!
The only caveat is that I had to merge the vertices before computing the vertex normals. I'm guessing that converting from the buffers messes with the triangles, so we gotta merge them before anything.
 var geometry = new THREE.Geometry().fromBufferGeometry( child.geometry );
 geometry.computeFaceNormals();
 geometry.mergeVertices();
 geometry.computeVertexNormals();
 child.geometry = new THREE.BufferGeometry().fromGeometry( geometry );


Variable number of fields in Django URL

Question: I'd like a URL of the form:
<code>... field1/eq/value1/field2/gt/value2/ ...
</code>
Where I want to filter the contents of the page in the view function based on an arbitrary number of fields (the names of which are not known in advance).
I've tried:
<code>(r'^((?P<field>\w+)/(?P<op>[a-z]+)/(?P<value>\w+)/)*$', my_view)
</code>
But the keyword arguments are filled with the last set of three field/op/value to occur in the URL.
Is there any way that I could populate a list or dictionary based on a variable number of URl fields like this?
Or should I be doing this some completely different way?
Answer: Don't do this.
Use the query string.  <code>?field,eq,value&field,gt,value</code> will work out much better.

Variable number of fields in Django URL


Mosh : client stay with "without contact" message

Question: I'm trying to use mosh in replacement of ssh but it doesn't work on my computer.
On my Mac (Macos X LION), the client stay with this message and never connect :
<code>mosh: Connecting... (10 s without contact.) [To quit: Ctrl-^ .]
</code>
I used homebrew to install mosh on my compute.
On my Server (ubuntu server), mosh-server seems to run without any problems. The UDP ports are open.
I try to figure out a solution but nothing seems to work.
Answer: Have you tried disabling your firewall for a moment to make sure that it's not being blocked?  We've all been bitten by rule ordering mistakes.
Also, how large of a range do you have defined?  Here's the iptables rule I'm using:
<code>-A INPUT -p udp -m multiport --dports 60000:60999 -m comment --comment "100 allow mosh" -j ACCEPT
</code>


How to force initial imported node to not have draft status using feeds?

Question: I'm using the Feeds (7.x-2.0-alpha9) and the Workflow modules. My imported nodes are automatically going to draft state and only go to done state when there is a second import of this node and the data is updated.
How can I automatically make the state on imported nodes be "saved" not "draft"?
I tried adding a rule upon feeds presave, but it never gets to the save since it is a draft.
Comment: Just a suspicion here, but does the node exist before the first import?  It sounds like you are having this situation: The node is being created by the feed; the rule is firing on pre-save, so before there is actually a nid on the node; the workflow module is firing on hook_node_insert so it runs after the rule and initiates the workflow; initial flow state is draft.  I suggest devising some flag or method for identifying an imported node after the feed has ran, and changing your rule trigger to an event that occurs after workflow initiation.  If all your imports have one author, perhaps?
Comment: yes these are new nodes.  which events occur after workflow initiation?
Answer: Even though this question is related to the Workflow module, the solution you're looking for should come from the Feeds and/or Rules module, as further explained in my answer below.
1st attempt: Feeds Rules module
The Feeds Rules module might be what you are looking for. Excerpt from its project page:

... provides some Rules integration for the Feeds module.
It provides:

Feeds processor: a processor for Feeds to create content via Rules. (Currently only simple data types like text and integer are supported).
Rules Event: Feeds After Import
Rules Data: Feeds Source (properties: ID, imported)

Recommendation: this might work, however there is only a dev version available for this module ... my advice = no go.
2nd attempt: Native Feeds module
The Feeds issue about Rules integration & enable modules to customize imports adds a hook hook_feeds_before_import(). Here are some quotes from that issue (bold markup added here):

... such that a rules integration could use it to customize the imported entities before saving + to skip saving.
Based on the hook we could add an event for it + an action for skipping the import. The entity could be manipulated with the usual rules actions else too.

Of course, in the question here the goal is to not skip saving. But instead "customize the imported entities before saving" and/or "manipulate the entity with the usual rules actions". More specifically: set the value of "state" to "Saved".
Recommendation: much better already, but it is not exactly right yet (and requires using a hook, i.e. writing some custom module) ... There has to be a Rules based solution ...
3rd (and Final) attempt: A rule that should do the job
Inspired (challenged) by the "I tried adding a rule upon feeds presave, but it never gets to the save since it is a draft" part of this question, I created a rule. Here is the export that rule, which I believe should be a perfect answer to the question (also because it doesn't require custom PHP code ...):
{ "rules_update_entity_after_import_via_feeds" : {
    "LABEL" : "Update field imported via feeds",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "workflow_rules", "feeds" ],
    "ON" : { "feeds_import_node" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_workflow_status" } }
    ],
    "DO" : [
      { "workflowfield_field_set_state" : {
          "node" : [ "node" ],
          "field" : [ "node:field-workflow-status" ],
          "workflow_state" : { "value" : { "3" : "3" } }
        }
      }
    ]
  }
}

To get this to work, I enabled the Workflow API module (of course ...), and also it's submodules  Workflow UI,  Workflow Field and Workflow Rules.
My Workflow itself has only status "Draft" and "Done" (identical to the question here).
The rule above only applies to "node", and only for those "nodes" that have a field defined with machine name "field_workflow_status" (if you want to use another field name, change the rule accordingly and it should work also ...). In my case I used "Article" as the content type, though the "entity_has_field" prevented that I had to hardcode the content type in my rule ...
Obviously, and to be complete, Feeds and Rules are also part of the solution.
Comment: Hi Pierre, that is exactly what I want to do , But I can't figure out how to do it.  The examples in that link don't tell me how to do it or how to make a rule to do ti.
Comment: @Dianacastillo : your own answer was too challenging to not try to change your mind again ... Hope you don't mind I further enhanced my answer anyway ...
Comment: Hi Pierre, I like the code answer better because i can easily modify it if necessary for any variations, basically I understand php much more than the rules language.   but I am sure your answer will be helpful to other people who want to use rules ( I haven't got time to test it so not sure if it will work or give bugs.)   But if you want the bounty, you can have it as long as you keep on helping me with these tricky questions!  Merci beaucoup!
Comment: Merci beaucoup aussi ... But don't worry ... No need for a bounty to keep answering such (sometimes challenging) questions ... I personally disagree with your preferred coding answer, but hey that is what Drupal is often about (pick what you prefer / feel most comfortable with), n'est pas (isn't it)? Autres questions (other questions?
Comment: not now ! i already gave you the bounty anyways
Comment: Fair enough ... But know that on Drupal.SE there is no such feature as 'follow user' ... Only a comment to ping a user seems available (should you ever want my comment/answer/advice to future questions) ... Or contacting me via my contact form on Drupal.org ...A bientôt ?
Comment: a bientot, merci! :-)
Answer: Here is the answer, thanks to another stackexchanger
function mymodule_feeds_after_save(FeedsSource $source, $entity, $item, $entity_id) {
    global $user;
    foreach ($entity->workflow_transitions as $key => $value) {
      $field_name = $key;
      $workflow = $value;
      break; // There should only be one workflow at this point
    }
   //$this_sid = $workflow->new_sid;
  $transition = new WorkflowTransition();
  $entity_type = 'node';

  $old_sid = 2; // sid of Draft status
  $new_sid = 3; // sid of Saved status
  $uid = $user->uid; // You can change with uid of author.
  $stamp = REQUEST_TIME;
  $comment = 'Created by upload';
  $transition->setValues($entity_type, $entity, $field_name, $old_sid, $new_sid, $uid, $stamp, $comment);
  workflow_execute_transition($entity_type, $entity, $field_name, $transition, $force = TRUE);
}


Merge masked selection of array with original array

Question: I'm facing a problem with an assignment at the moment.
So I have an array which contains 400 2d Points. So an array of shape 400 X 2.
Then I have a mask that selects m points (rows) that I wanna compute some changes on.
As per the assignment I'm supposed to store the points that I want to change in an array of shape m X 2.
Then I do my changes on this resulting array. But now after the changes I want to insert these new computed values in my original array at the original indices. And I just have no clue how to do that.
So I basically have:

orig (400 X 2)
mask (400 X 1) (boolean mask selecting the rows to edit)
change (m X 2) (just the changes I want to add)
changed (m X 2) (the original values + the change (with a factor applied) added together

How do I transform my change or changed arrays with the mask so that I can add/insert the changes into my original array?
Answer: Look at this example with 4 rows.
The principle is that the mask that "extract" from orig can also return the sub-array to the original place.
<code>import numpy as np
x = np.array([[1,2],[3,4],[5,6],[7,8]])
print(x)

mask_ix = np.array([True,False, True, False])
masked = x[mask_ix,:]
masked = masked * 10 # the change

print(masked)
x[mask_ix] = masked  # return to the original x in the mask_ix mask
print(x)

 x =[[1 2]
     [3 4]
     [5 6]
     [7 8]]

masked = [[10 20]
          [50 60]]

x = [[10 20]
     [ 3  4]
     [50 60]
     [ 7  8]]
</code>


How can I add a picture in address bar of the browser when my page is browsed?

Question: Duplicate:

Image icon beside the site URL
What is currently the best way to get a favicon to display in all browsers that support Favicons?
Preferred way to use favicons?

I want to add my logo in the address bar of the browser, whenever it is browsed.
How do I make a favicon?
Comment: Edited title now reads like the OP already knows what a favicon is before asking about it
Comment: I agree, doesn't help people searching. If he knew it was a favicon he might have found one of the other answers. Will edit...
Comment: Interesting. I agree with both sides on this edit.
Answer: You need a favicon - this is a 16x16 image in .ico format stored as favicon.ico in the root directory your site. Some browsers do support other formats too.
A newer, more standards based approach is to include something like this in your html head:
<link rel="icon" type="image/png" href="/path/image.png"/>

See also this document from W3C: How to Add a Favicon to your Site
You might also want to refer to these other answers to the question:

Image icon beside the site URL
What is currently the best way to get a favicon to display in all browsers that support Favicons?
Preferred way to use favicons?
Answer: That image is called a favicon and here are some links on how to add one or you can just google "how to add a favicon" for more information.
http://www.w3.org/2005/10/howto-favicon
http://www.clickfire.com/favicon-tutorial
http://essentialkeystrokes.com/tutorial-how-to-create-your-own-favicon
Answer: See http://en.wikipedia.org/wiki/Favicon
Answer: Are you talking about creating a Favicon?
If so, here's a site which will help you make one.
Answer: Just use this.
<link rel="icon" type="image/png" href="/path/image.png"/>

I hope it works for you.
Comment: This is a [duplicate](https://stackoverflow.com/a/626377/771431)


I'm blanking on a word regarding rhythmic interpretation (making 4/4 sound like 3/4 and vice versa)

Question: I know it's not polyrhythm or anything along poly-whatever lines (I could be wrong, but nothing's ringing a bell) and the only results I'm getting are either like that or not related to my question to at all. Can anyone help?
Comment: Are you thinking of *hemiola*?
Comment: If you're not happy with the existing answers, could you possibly be thinking of the words SWING, SHUFFLE and STRAIGHT? These are directions to do with the _division_ of the beat, rather than the _number_ of beats per bar? They can't make "4/4 sound like 3/4", but they can divide each beat into three - or roughly three - changing the feel of the piece completely.
Comment: Can you give any more details on exactly what kind of "making X sound like Y" you're thinking of, or even give examples? You're getting a lot of answers but depending on the context different ones might be best. I might even just go for "metric subversion," depending.
Comment: Maybe link some songs on youtube you know have this "effect", or possibly make a video on your own.
Answer: There are some specific rhythms like hemiola and sesquialtera.   But generally, I think you just need 'cross-rhythm'.
Answer: Hemiola springs to mind. However, that's less than half the story. A hemiola in pitch is the same as the interval of P5 (confusing?), whereas a hemiola in timing is  typically 2 groups of 3 beats, replaced by3 groups of 2 beats. Thus retaining the same value per bar (measure), but changing the 'feel' between triple and duple.
Sesquialtera is a far less common term, alternately used (rarely) as the name for a particular organ stop (confusing again?), but also can be, but rarely, referring to the same timing change. It more commonly gets used when music changes time signature - as in 3/4 to 4/4, where the 4 remains at the same tempo. Not exactly what the question is asking, I think, where the bar length remains the same for 3/4 and 4/4..
Answer: Three things come to mind.
Hemiola...

...where the eighth notes are first grouped by 3 and then switch to grouping by 2. The duration of an eighth note does not change, but the sense of beat pulses quickens.
Tuplets...

...where quarter notes play the beat, but at the tuplet 3 quarter notes get squeezed into the duration of 2, and so the pulse seems to quicken.
And duple meter 4/4 compared with 4/4 with triplets, or 12/8...

...where the 4 beats to each measure can be the same for all three examples, but the beat division can be by 2 (or 4) or by 3. In this case the 12/8 can have a very clear sense of 4 beats per measure, and so seem like common time. The similarity of 12/8 and triplets in 4/4 is a fairly common discussion topic.
Technically 12/8 is compound meter while triplets in 4/4 is simple duple meter. The difference is really a matter of written notation. With triplets in 4/4 the subdivision of beats by 3 might make someone feel, or actual count 1, 2, 3 for each beat, and that might make someone think of those meters as analogous to some kind of triple (3/4) or compound (12/8) meter, even though they are not.
Answer: Metric modulation maybe?
Check out this video: Everybody wants to rule the world
Also check out this video: Nautilus  This is so clever - you hear the swinging pattern at the beginning and make assumptions about where the barlines are. It's only when the drums come in at the end that you realise your initial assumption was miles off.


How to pass Discriminated Union as a parameter in a function? F#

Question: How to pass a parameter in a function if the defined type is a Discriminated Union? For example I want to pass in an object of type Color where the colorB is set to "blue". Inside the function I want to check if colorB is set to is blue.
type Color = ColorA of string | ColorB of string

let IsColorBlue (a:Color): bool =
    match a with
    | a -> if a.ColorB = "blue" then true // <- How to check if ColorB is blue ?

IsColorBlue (Color-Object)   // <- How do I call this?

Comment: First you need to match that you have a `ColorB` and not a `ColorA`, which you haven't done in your code
Comment: Also please provide a proper [mcve], you haven't defined `Color-Object` anywhere
Answer: To use pattern matching to check whether a Color is colorB with a specific value, you can use the following syntax:
let IsColorBlue (a:Color): bool =
    match a with
    | ColorB "blue" -> true
    | _ -> false

To create values of type Color, you can write ColorA "some" or ColorB "some". For example:
IsColorBlue (ColorB "blue") // true
IsColorBlue (ColorB "red")  // false - not blue
IsColorBlue (ColorA "blue")  // false - not ColorB

Comment: What if you need to check 2 parameters? Like if ColorA = blue & ColorB = blue at the same time. How do you call the function & how to write if else with pattern matching?


What are first-countable topological spaces?

Question: Right now I'm studying countability in topology. My notes provides me a definition of first-countable spaces:

In the following $(X,\tau)$ is a topological space.
Definition If $x \in X$ then $\mathcal{E}(x):=\{E \subset X \mid \exists U \in \tau: x \in U  \subset E \}$ is the neighbourhood system of $x$.
Definition: $\mathcal{B}_x \subset \mathcal{E}(x) $ is a local basis with respect to $x$ if for every $U \in  \tau$ such that  $x\in U$ exists $B\in\mathcal{B}_x$ such that $x\in B \subset U$
Definition: $(X,\tau)$ is first-countable or 1-countable if for each $x \in X$ there is  a countable local basis $\mathcal{B}_x$ (so $|\mathcal{B}_x|\leq\aleph_0$).

But I don't know what is a countable local basis. In my notes says "It's clear that $\mathcal{B}_x=\{B(x,r):r\in\mathbb{Q}\}$ is a countable local basis". For me is not so clear, someone can explain what is all stuff?
Thanks!
Comment: Buy a countable sets detector. They usually go for somewhere between $\aleph_0$ and $2^{\aleph_0}$ dollars. Sometimes you can find cheaper second hand detectors on eBay...
Comment: What is the adjective you don't understand? Countable? Local?
Comment: I have a definition of local basis. I just write above. My problem begins with "countable sets". Thank you!
Comment: @Melanctha I reworked the definitions because they seemed rather imprecise and incomplete to me. If you don't like this roll it back.
Comment: Thank you @miracle173 .I wrote word by word the definitions that my teacher give to us, and I prefer yours, they are clearer than my teacher's. Maybe his notes are incomplete and create dificulties where there isn't.
Answer: A set $X$ is countable if and only if there is an injection from $X$ to $\mathbb{N}$: that is, iff the elements of $X$ can be "counted." (Note that some texts use "countable" to mean "countable and infinite", so you should check exactly how your book uses the word.)
Now, a local base is a set of open sets such that [property]. Presumably you've already seen the definition of local base; that's why I'm ignoring it here.
A countable local base is . . . just a local base which is countable! So, for example, the set $\{B(x, r): r\in\mathbb{Q}\}$ you mention can clearly be injected into $\mathbb{Q}$ (just map $B(x, r)$ to $r$), and $\mathbb{Q}$ is countable (this is a theorem which your text should prove, or mention, somewhere). Note that a local base being countable or not has nothing to do with it being a local base or not; the two aspects of being a "countable local base" are completely unrelated.
Comment: @Melanctha Yes. If you have a set $X$, and you want to know if $X$ is countable, you need to do one of two things: (i) Find a bijection between $X$ and a set you already know is countable, or (ii) prove that no such bijection exists (see e.g. [the proof that the reals are uncountable](https://en.wikipedia.org/wiki/Cantor%27s_diagonal_argument)). *This isn't quite accurate - in principle, you could prove that a bijection between $X$ and some countable set exists, without actually exhibiting such a bijection (e.g. if $X=\{1\}$ if the Riemann hypothesis is true, and $\{1, 2\}$ otherwise)  .*
Comment: (cont'd) *However, that's extremely rare in practice.*
Comment: I prefer "countable" to mean "not uncountable". In other words "countable" for "finite or countably infinite". But some authors use "countable" to mean only "countably infinite."
Comment: First of all, thank you. My notes provides me a definition of local base, I'm goingo to put it in the question above here. But what about "detect" countable sets? I just have to invent  a bijection between a countable set and my set?
Comment: @user254665 Note that I cover that in the second sentence of my answer.


Why disable non-core modules when doing a core update?

Question: I have seem multiple update tutorials tell you to disable all non core modules before doing an update. What is the reason for this? I'm not real familiar with the update area of core but can't see any real good reason. Is there something major I am risking if I don't do this?
I can understand the reasoning if we are doing an update between major versions (6 -> 7). But when doing a minor update (7.10 -> 7.12) is where I have my question.
Answer: Contributed modules are not always robustly built and can fall victim to changes made in core. This is particularly an issue if the contributed module has not made proper use of Drupal's API or relies on a database structure in core that may change with the upgrade (even if it is just a minor update). It is therefore safest to disable all the contributed modules before updating in case one of the modules causes the site to fail on completion of the upgrade process. Admittedly this is rare, but it does happen. It happened to us once, but thankfully just on a dev version of a site.
Comment: As long as you have backups and you test it on a copy of the live site it should be fine to do this. If all goes well then you shouldn't have an issue on the live site, but make sure you put the site in Maintenance mode before upgrading. You don't want users messing things up. :)
Comment: Considering the rarity of something catastrophic happening, wouldn't it be good enough to depend on the backup you made just prior to doing the update? It seems to me like the chance of something going wrong is hardly worth the effort, time and risk of error that exists when you disable all your contrib modules.
Answer: When upgrading from 6 to 7, none of the modules should use sessions table (in *hook_boot* or *hook_init*), otherwise it generates the fatal error. If you have simple website, you can try to upgrade Drupal, but in case of any fatal errors, you should disable them.
Please see the common problem which happens when some people trying to upgrade with contrib modules:
Upgrade D6.20 to D7 fails with PDO Exception

Here is sample command to disable all non-core modules and themes:
echo 'UPDATE system SET status = 0 WHERE filename NOT LIKE "themes%" AND filename NOT LIKE "modules%";' | `drush sql-connect`

Also you may try to clear the caches:
echo "DELETE FROM cache`drush sql-connect`
echo "DELETE FROM cache_bootstrap" | `drush sql-connect`

And remove any included files from the settings.php file such as memcached, etc.
Answer: My suggestion is: don't. It's Drupal 6-era advice, and the world has changed since then.
In Drupal 7, many modules can't be disabled properly, or there is a danger of them not working properly when they are re-enabled.
Any module that provides field / entity types is a suspect, Commerce for instance.
This is why Drupal 8 has removed the concept of disabled modules completely.
(Of course, this only concerns point upgrades, not major version upgrades such as 6 -> 7)


How to add ToolBar in StaggeredGridView Activity

Question: Im using StaggeredGridView and I want to add ToolBar in StaggeredGridView, this is my Activity:
public class CategoryCarActivity extends AppCompatActivity implements AbsListView.OnScrollListener, AbsListView.OnItemClickListener {

   @Override
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_sgv);

    Toolbar toolbar = (Toolbar)findViewById(R.id.toolbar);

    setSupportActionBar(toolbar);
    // getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    ...
}

activity_sgv.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<com.etsy.android.grid.StaggeredGridView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/grid_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:item_margin="8dp"
app:column_count="@integer/grid_column_count" />

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:titleTextColor="@android:color/holo_blue_bright" />

<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/activity_horizontal_margin"
android:gravity="center" />
</LinearLayout>

It will not display Toolbar althrough I check Logcat and there are not any errors happened.
How to fix this the problem to Toobar display? Thank you !
Answer: You are unable to see the ToolBar as its wrapped beneath the StaggeredGridView .
How to FIX:
Try this:
    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
android:theme="@style/ThemeOverlay.AppCompat.Dark"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
app:titleTextColor="@android:color/holo_blue_bright" />

<com.etsy.android.grid.StaggeredGridView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/grid_view"
android:layout_below="@id/toolbar"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:item_margin="8dp"
app:column_count="@integer/grid_column_count" />

<TextView
android:id="@+id/text_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/activity_horizontal_margin"
android:gravity="center" />

Comment: Greate !! It's displayed but back button is not display
Comment: setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
Comment: If it did help, mark it as answer, Where is the back button defined in the XML file?


Why does this show that every solution exists for all $t\in (-\infty,+\infty)$?

Question:

Show that every solution of the system
    $$
\frac{dx}{dt}=y,\quad\frac{dy}{dt}=x-x^7,\qquad(x,y)\in\mathbb{R}^2,
$$
    is defined for all $t\in (-\infty,+\infty)$.

The given solution is the following:
The Hamiltonian $H(x,y)=\frac{y^2}{2}-\frac{x^2}{2}+\frac{x^8}{8}$ is conserved:
$$
\frac{dH}{dt}=(x^7-x)y+y(x-x^7)=0.
$$
Therefore $x(t)$ and $y(t)$ remain bounded for all $t$ (otherwise $H(x,y)$ would grow). Hence $(x(t),y(t))$ is globally defined.

I cannot fully understand this argumentation...
Of course, if $(x(t),y(t))$ is a solution, the Hamiltonian is constant along $(x(t),y(t))$.
But does this tell anything about boundedness of the solution?
In fact, if $H$ would grow, i.e. $\frac{dH}{dt}>0$, then $(x(t),y(t))$ would be no solution, since the Hamiltonian is constant along solutions.
Comment: Look at what $H$ is. If (at least) one of $x,y$ were unbounded, then $H(x(t),y(t))$ would be unbounded. Hence the solution must remain bounded for its entire lifetime.
Comment: @Evgeny And that $u(t) = H(x(t),y(t))$ is constant in particular implies that $u$ is bounded. But if one of $x,y$ were unbounded, then $u$ would be unbounded. That's a contradiction. Hence $x$ and $y$ are both bounded. The argument without using a contradiction is "The level sets of $H$ are compact, hence bounded, and the curve $t \mapsto (x(t),y(t))$ stays in one level set, therefore it is bounded".
Comment: @Evgeny We are looking at a specific situation. We have the Hamiltonian $H(x,y) = \frac{y^2}{2} - \frac{x^2}{2} + \frac{x^8}{8}$. For **this** Hamiltonian the level sets are bounded, and hence the trajectories are bounded. Of course that doesn't hold for all systems.
Comment: @Evgeny There's no "parallel reasoning", I just phrased it as an indirect proof (because of the "otherwise $H(x,y)$ would grow" in the solution). I hope you don't disagree with the reasoning that "if $\gamma$ is an unbounded curve and $F$ a function whose sublevel sets are bounded, then $F\circ\gamma$ is unbounded" [if we only require bounded level sets of $F$, we can only deduce that $F\circ \gamma$ is non-constant, it need not be unbounded, but for the $H$ under consideration here it's easy to see that $H(x,y)\to+\infty$ for $\lVert(x,y)\rVert\to+\infty$, so we have bounded sublevel sets].
Comment: Have you heard about solution continuation theorems? Take at look at them: using the fact that level sets are bounded might allow you to fulfill conditions of these theorems.
Comment: @DanielFischer I am not sure that I understood your reasoning correctly, but there are Hamiltonians with non-bounded level sets.
Comment: @Evgeny But for _this particular_ $H(x,y) = \frac{y^2}{2} - \frac{x^2}{2} + \frac{x^8}{8}$, all level sets are compact.
Comment: @DanielFischer I do not understand. It is $H(x,y)=\text{const}$ if $(x,y)$ is a solution. What is the level set?
Comment: @Rhjg A level set of $H$ is $H^{-1}(c) = \{ (x,y) \in \mathbb{R}^2 : H(x,y) = c\}$ for some $c\in \mathbb{R}$. Sometimes that's also called a fibre of $H$, but that terminology is used more often in other areas.
Comment: So if $H(x,y)=c$ for some constant $c$, we here have that $x(t)$ and $y(t)$ must be bounded? That is the level set has to be bounded? How to see this exactly? It is enough to show that each level sets are bounded?
Comment: @DanielFischer Sorry, I am just confused by part "If (at least) one of $x$, $y$ were unbounded, then $H(x(t), y(t))$ would be unbounded". It's Hamiltonian: it stays constant along trajectory, it neither grows nor decreases. Sorry again :)
Comment: @Evgeny I think it would be better to say that each level set is bounded and hence $x(t)$ and $y(t)$ must be bounded hence each solution $(x(t),y(t))$ exists for all $t$. Or?
Comment: @DanielFischer I think the argument using the contradiction is the better one here since if we use the other one one would have to prove that each level set is bounded which is not that easy as far as I see.
Comment: @DanielFischer Consider Hamiltonian $H(x, y) = \frac{y^2}{2} +\frac{x^2}{2}-x^3$. Consider [level set](http://www.wolframalpha.com/input/?i=y^2%2F2+%2B+x^2%2F2+-+x^3%2F3+%3D+0) $H(x, y) = 0$. You say that if $(x(t), y(t))$ were unbounded, then $u(t) = H(x(t), y(t))$ would be unbounded. Okay, trajectory is unbounded, but $u(t) \equiv 0$. Maybe I don't understand your reasoning, but for me it feels wrong (because I have this counterexample).
Comment: @DanielFischer I totally agree with reasoning using boundedness of level sets. I just don't agree with the parallel reasoning that starts with "if $x$ or $y$ were bounded ... ". I think I understand it better now, but it uses (at least implicitly) that level sets are bounded in this case. But why should we need this additional step when we can just use that trajectories lie on level sets?
Comment: @Rhjg In the answer there is already a proof of boundedness of level sets.
Comment: @DanielFischer Yeah, I've already understood that reasoning before I wrote my previous comment :) and this kind of indirect proof was a little bit confusing to me.
Answer: Take any particular solution, with initial conditions $x(a)=b,y(a)=c$.  Then $H(x,y)=\frac{c^2}2-\frac{b^2}2+\frac{b^8}8=d$ for all $t$.  If $x(t)^2$ ever got above $2d+3/4$, there would be no possible value for $y(t)$.
So $x(t)$ is bounded.  $y(t)$ is also bounded, for similar reasons.
Both $x(t)$ and $y(t)$ have bounded derivative, so they can be extended into the future.


VB6: Regular Expressions - Problem under Win7

Question: I have a little application which uses regular expressions under VB6.
It works perfectly under XP but under Win7 I'm experiencing massive problems.
Sometimes, when the text which is passed to the regex function is > 20KB, it freezes the application and also the whole Win7 system: it's getting really slow, almost completely freezes and only after ~30 seconds reacts for a few seconds and freezes again.
Strange thing - event if i terminate the VB6 task under task-manager the whole system remains slow, frozen and unstable. it's like if it's running on 100% cpu load although it's normal. Seems to be a system thing which eats up all resources and the only thing that helps is to reboot.
I've already googled but couldn't find anything. Anyone experienced the same thing / knows a solution? Is there at least some way to terminate the regex function in case it takes too long?
Comment: I experienced similar behavior on an old PC when upgraded to 4GB RAM. Turned out Intel board's BIOS has a new version.
Answer: Is the application multithreaded?  Did you also upgrade the hardware from a single-core CPU to multicore/multi-CPU?
Usually, when a regex goes rogue it either causes a stack overflow or goes into an (apparently) infinite loop, but it sounds like that's not happening to you.  The symptoms you describe sound more like a deadlock: multiple threads of execution contending for the same resource.
There have been some bugs reported against Java's regex package that turned out to be concurrency related, and nothing to do with regexes per se.  The root bug was there all along, but it couldn't manifest on a single-core machine, even in a nominally multithreaded app.  It didn't get reported until large numbers of users shifted to multicore hardware.
I'm not suggesting that there's a concurrency bug in VB6 like there was in Java; more likely it's in your application.  If the app is multithreaded, try eliminating that aspect and see what effect it has.  If it's not, or if this doesn't help, we'll need more information; there isn't much to go on in your original question.
Comment: hi,
i forgot to mention that i'm having an intel quadcore, but the vb6-app is singlethreaded (no external dll or multithreading, just normal app). is there maybe something to tweak in vb6/win7?
thx
Comment: I don't know about tweaks. I was mainly suggesting that you not focus exclusively on regexes as the cause of your problem just because of their reputation for causing lockups. Another thing you could try is eliminating the regexes while keeping the structure of the app as much the same as possible. Of course, a good profiler would help the most, but I don't know what's available for VB6.


Mysql query to find records that are common in multiple columns across multiple tables.

Question: Table1
- | a  | b  | C  | d  | e  |
- |----+----+----+----+----|
- | 1  | 2  | 3  | 2  | 9  |
- | 2  | 3  | 2  | 3  | 5  |
- | 3  | 8  | 4  | 4  | 2  |
- | 4  | 9  | 8  | 5  | 3  |
- | 5  | 1  | 9  | 7  | 1  |
- | 6  | 12 | 10 | 9  | 10 |

Table2
- | a2 | b2 | C2 | d2 | e2 |
- |----+----+----+----+----|
- | 1  | 2  | 3  | 2  | 9  |
- | 2  | 3  | 2  | 3  | 5  |
- | 3  | 8  | 4  | 4  | 2  |
- | 4  | 9  | 8  | 5  | 3  |
- | 5  | 1  | 9  | 7  | 1  |
- | 6  | 12 | 10 | 9  | 10 |

Results i want:
2,3
Because 2 and 3 are common in all the columns across these two tables.
I have tried :
SELECT DISTINCT c1.a FROM  `table1` c1
JOIN  `table1` c2 ON ( c1.a = c2.b )
JOIN  `table1` c3 ON ( c2.b = c3.c )
JOIN  `table1` c4 ON ( c3.c = c4.d )
JOIN  `table1` c5 ON ( c4.d = c5.e )
LIMIT 0 , 10

It works good for table1 but how to join more tables.
Comment: Waiting for reply ...
Comment: Can you explain a bit more on what you are trying to achieve?
Comment: This doesn't sound like a relational database problem at all. How are 2 and 3 the returned values when you have some rows which don't contain either value?  It is not really clear what you are asking here.
Comment: @MikeBrant : Please recheck, All the columns have 2 and 3.
Comment: one question, what are your specifications? May be more than a number repeated in each row, or only one of them will be repeated?
Comment: @Chococroc: Yes, a number could be repeated in same row and same column. But  i want all the numbers present in all the columns.
Comment: @TarunBhardwaj The number may be repeated in each column, but in mysqlm you are viewing data at a row level.  Again, I don't think this is a relational database problem, but more of a matrix problem.
Answer: It's exactly the same:
SELECT DISTINCT c1.a FROM  `t1` c1
JOIN  `t1` c2 ON ( c1.a = c2.b )
JOIN  `t1` c3 ON ( c2.b = c3.c )
JOIN  `t1` c4 ON ( c3.c = c4.d )

JOIN  `t2` c5 ON ( c4.d = c5.a )
JOIN  `t2` c6 ON ( c5.b = c6.c )
JOIN  `t2` c7 ON ( c6.c = c7.d )
LIMIT 0 , 10

Check this fiddle: http://sqlfiddle.com/#!2/46ade/6
Answer: Well you can start with this fiddle with 10 rows.
Where you will count it to equal how many rows you are comparing.
Your example has table1 6 rows, table2 6 rows.
12 rows for example is...
SELECT
    a.value,
    COUNT(a.value) as count
FROM
(
    SELECT a AS value
    FROM table1

    UNION ALL

    SELECT b AS value
    FROM table1

    UNION ALL

    SELECT C AS value
    FROM table1

    UNION ALL

    SELECT d AS value
    FROM table1

    UNION ALL

    SELECT e AS value
    FROM table1

    UNION ALL

    SELECT a2 AS value
    FROM table2

    UNION ALL

    SELECT b2 AS value
    FROM table2

    UNION ALL

    SELECT C2 AS value
    FROM table2

    UNION ALL

    SELECT d2 AS value
    FROM table2

    UNION ALL

    SELECT e2 AS value
    FROM table2

) a
GROUP BY value
HAVING count >= 12
ORDER BY count DESC

to be more dynamic on the row count you can also try:
HAVING count >= ((SELECT COUNT(*) as t1 FROM table1) + (SELECT COUNT(*) as t2 FROM table2))

update
Something similar to your approach is: http://sqlfiddle.com/#!2/56d52/4
SELECT t.value, COUNT(t.value) as count
FROM
(
SELECT DISTINCT c1.a AS value FROM  `table1` c1
JOIN  `table1` c2 ON ( c1.a = c2.b )
JOIN  `table1` c3 ON ( c2.b = c3.c )
JOIN  `table1` c4 ON ( c3.c = c4.d )
JOIN  `table1` c5 ON ( c4.d = c5.e )

UNION ALL

SELECT DISTINCT c1.a2 AS value FROM  `table2` c1
JOIN  `table2` c2 ON ( c1.a2 = c2.b2 )
JOIN  `table2` c3 ON ( c2.b2 = c3.C2 )
JOIN  `table2` c4 ON ( c3.C2 = c4.d2 )
JOIN  `table2` c5 ON ( c4.d2 = c5.e2 )
) t
GROUP BY t.value
HAVING count = 2

Comment: Its Working!!... But, Suppose i delete 2 from `table1` `a` and i add 2 to `table1` `b`. now there are total 12 2s so it will be on the top. I want data that is present in all the columns.


Service sharing

Question: I have a service which provides current location of the device. Several activities in my app can call this service at the same time. If I call stopService() in an activity, can it make the service running in different activity stop? I have read Android document but still confused about that. Please make it clear for me. Thanks.
Answer: There is only one instance of the service. You can call startService() from multiple activities, but it will have only one instance. As soon as any of the activities calls stopService() it will be stopped for all activities.

Service sharing


How to use external toolchain with yocto

Question: I wanted to use my platform toolchain before.
but changing toolchain isn't easy for me.
I don't know external toolchain is allowed by yocto
How can I do?
Thank you so much
step:

clone poky and meta-external-toolchain
clone https://github.com/BPI-SINOVOIP/BPI-W2-bsp.git to /tmp
modify/add conf/local.conf
3.1 modify MACHINE ??= "qemux86" to MACHINE ??= "qemuarm64"
3.2 add EXTERNAL_TOOLCHAIN = "/tmp/BPI-W2-bsp/toolchains/asdk64-4.9.4-a53-EL-3.10-g2.19-a64nt-160307"
add meta-external-toolchain path to conf/bblayers.conf
run bitbake xz -e | grep CC=

I got the messages
export CC="aarch64-poky-linux-gcc  -march=armv8-a+crc -fstack-protector-strong  -D_FORTIFY_SOURCE=2 -Wformat -Wformat-security -Werror=format-security --sysroot=/tmp/poky/build/tmp/work/aarch64-poky-linux/xz/5.2.4-r0/recipe-sysroot"

but I want to use this gcc to build packages
/tmp/BPI-W2-bsp/toolchains/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu/bin/aarch64-linux-gnu-gcc

How can I modify it??
Answer: External Toolchain is supported in yocto. you can do this by setting value to TCMODE & EXTERNAL_TOOLCHAIN variable (Ref Yocto ref-manual). Find more information for setting external toolchain from this meta-sourcery
Comment: Thank you for your answer. I found a meta (http://git.yoctoproject.org/cgit.cgi/meta-external-toolchain/) from poky.
I try to set EXTERNAL_TOOLCHAIN = "/tmp/BPI-W2-bsp/toolchains/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu" in the local.conf, but it's not successful.

toolchain source: https://github.com/BPI-SINOVOIP/BPI-W2-bsp/tree/master/toolchains/gcc-linaro-7.3.1-2018.05-x86_64_aarch64-linux-gnu


Check on which NextJs version is the project based

Question: I am working on a NextJs project and I would like to know which NextJs version is installed. Where can I check that?
Comment: Or you can simply run `npx next -v`
Comment: You can always check the package.json file.
Comment: Did  the answers solve your problem?
Answer: You can view package.json of your project. Or You can use Next.js CLI In your project root directory enter command  npx next --version.
Comment: Great thanks man!
Comment: @Denis2310  You're welcome! ;-) Glad  I could help You !
Answer: In the root directory of the project run
npx next -v

Hope this useful for you!
Comment: quick and easy!
Answer: Along with the above upvoted answers I just wanted to add another way I have checked the nextjs version using create-next-app. I just followed below different steps
1. One way can to find the version like mention above from the package.json file as referred from below

2. Running below command
npx next --version

3. By running below commands
sudo npm install -g create-next-app@lates
create-next-app --version


Search for a 'diff value than' from another sheet and return a cell from this row

Question: Sheet 1:(the one to copy to)
Redial     |    DND |  New call
value1     |    value2  |  value3  -> values that I want

Sheet 2: (the one with the info to copy from)
Redial     |    DND |  New call
HJSG       |    7654    |  eur

What I want is to search if the value of "new call" is NOT eur, and if so, copy the value of sheet2(redial,DND and New call) to the sheet1.
Im trying to do arrays with Index and vlookup and if's but I cant really figure it out.
Answer: In Cell A2 of Sheet1 enter the following formula
=IFERROR(INDEX(Sheet2!A$2:A$10,SMALL(IF(Sheet2!$C$2:$C$10<>"eur",ROW($A$2:$A$10)-ROW(INDEX( Sheet2!$C$2:$C$10,1 ))+1 ),ROWS($1:1))),  "")

Drag/Copy down and across (to right) as required. This is an array formula so commit it by pressing Ctrl+Shift+Enter.


Bulk update got slower after conversion of database tables to InnoDB

Question: After I converted the database tables to InnoDB engine from MyISAM, I noticed some operations became very slow, especially on updating multiple nodes in bulk for administrative work. Front end performance seems to be good.
I have tried configuration settings suggested in these articles without any luck: MySQL > YourSQL, and MySQL Performance Blog.
My test script would load 25 different nodes (node_load()) and save them right away (node_save()) in a loop. This script runs for 2 seconds on the server with MyISAM engine; after DB conversion to InnoDB, it now takes 13 seconds.
It also takes much longer to restore InnoDB database from a SQL dump of 500MB; 20 minutes (InnoDB) vs. 2 minutes (MyISAM).
Is this what I should expect from InnoDB engine?
New to InnoDB engine, I'd like to know what I might still be missing in configuring and optimizing InnoDB.
Comment: It is Drupal 6 site.
Answer: Thanks for the nice tips. I tried most of the suggested InnoDB tuning tips and it was not enough to remedy my problem.
Here is how I was able to fix my issue. This may be a special case that is isolated to my situation, but I hope that this could help other developers who are in a similar situation.
When I ran node_save() in a loop with 25 different nodes, it took 2 seconds with MyISAM and 13 seconds with InnoDB.
I captured 80 some database queries generated by node_save() in a single loop. Some of them came from running node_load(), which is needed before node_save(). I used devel module's feature of database query info collection. I put the queries side by side. The same queries from InnoDB were slightly faster than MyISAM especially for simple SELECT queries, which took majority portion of all queries.
I identified an INSERT query from InnoDB side that took more than a 0.5 second when total 80 queries took 0.6 second. The query was from notifications module, whose hook implementation was fired every time a node was saved.
I narrowed it down to the table notifications_fields in the query and decided to create an index on the table for the column value. And that made all the difference. After creating an index on value, saving 25 nodes now took only 0.2 seconds (down from 13 seconds), even ten times faster than MyISAM's! (BTW, creating index on MyISAM table also made it run ten times faster than before)
In this case, I have to admit that InnoDB's under performance gave clue to find out that an index was needed. I would not have found out about the index with MyISAM because it was relatively fast enough to hide the situation.
There have been several cases like this that adding indexes improved site performance quite a lot. However, actual application and result from it can differ in different sites. Back to my case with notifications_fields table, adding another index on field column -- hoping to strech performance boost -- ruined the effect and actually made it slow again. So one needs to be careful with adding indexes and understand that one fix on a site may not work the same way on another site.
Comment: I strongly suggest you give that back to the notifications project, preferable with a patch that updates the schema and adds a update function so that others can benefit from your findings too. This sounds like a default behavior that is the same on all sites.
Comment: Thanks for the suggestion. I posted an issue at http://drupal.org/node/1151930
Comment: Thanks for the tip about adding index on value. What engine have you finally choosen for notifications_fields?
Answer: Especially DDL (creation of tables etc.) statements are slower in InnoDB. That's just the way it is.
Another difference is that InnoDB uses transactions and MyISAM doesn't. So by default, if auto-commit is set to on, it will do an explicit commit after each update/insert/delete query.
The easiest way to speed that up is to explicitly start a transaction before your bulk updates and then commit it at the end.
Unfortunately, the D6 database API does not have a way to do that in a database agnostic way, so you will have to rely on the actual SQL comments which are for MySQL:
db_query('START TRANSACTION');

and
db_query('COMMIT');

See http://dev.mysql.com/doc/refman/5.0/en/commit.html for more details.
That should already greatly speed up these updates.
Comment: No, I am not. Disabling auto commit means that you would need to explicitly commit everything, what Drupal doesn't (obviously).
Comment: Are you suggesting we disable auto commit, and don't need to define transactions explicitly?


How to get all Connected Clients of Redis Cluster?

Question: How to get all connected clients of a redis cluster?
I am using AWS elasticCache redis with non cluster mode and redission as my redis client.
My Use Case:
I need to run specific code from only 1 connected redis client.
Thanks
Answer: redis has command about client information like CLIENT LIST, check out this page .
you could checkout this page for the command redisson has not supported yet.
Comment: I checked that command but there is no similar api in Redisson client.
**Redisson wiki page:** https://github.com/redisson/redisson/wiki/11.-Redis-commands-mapping.


Cannot accept SDK Licenses for android SDK in Flutter

Question: This is my first time running Flutter as I am looking to get started with it. When I try to configure it my apps cant be run because SDK Licenses have not been accepted. When I try to fix that in the suggested way I get the following error :
Exception Gets Thrown When I Try To Accept Licenses
How do I fix this exception?
Answer: I've fixed a similar issue by deleting the build tools from the Android SDK folder and reinstall it again.


Show webform textfield conditionally based on "radio other"

Question: I have a webform "radio other", with options like "1, 2, 3, more".
For "more", "radio other" is configured to add a textfield for custom values.
Now the problem is that I want to hide the custom text-field until "other" is selected, and if it's possible to do so with the existing conditional logic I can't work it out.
I've tried to work out a way to add conditional logic to the "radio other" element, but it appears I can only do so to the whole element, and not just the other part.
I've also tried adding another text-field, and have it's visibility be conditioned to the "more" choice, but I can't seem to chose that in the webform conditions dialog, as it only displays the 1,2,3 options.
Answer: You need to set the condition for the text field: Edit the webform text field and under "Condition" (I am not sure about the label in English) you choose for the status "visible" and under "Element" you choose your radio button element and as "Trigger/value" you choose "value is" (in the select box) and in the field you then choose your value "other".
With this set your text field appears when you choose "other" from the radio buttons.


What is the best way for creating a fullscreen app in Android NDK which renders in half resolution?

Question: When initializing my EGL\GLES context, I use fullscreen. My application is then rendered in half resolution and finally blitted to the screen using a simple draw.
However, for performance reasons, is it possible to initialize my context in an arbritary resolution (for example half the full resolution) and have the driver\hardware handle the blit to fullscreen?
Answer: You can use the android hardware scaler for this.
The way you use it depends if you initialize EGL from java or native C++ code:
<code>// java
surfaceView.getHolder().setFixedSize(1280, 720);

// native
int32_t ret = ANativeWindow_setBuffersGeometry(window, 1280, 720, 0);
</code>
Using the hardware scaler generally gives you better rescaling quality, better performance and less energy usage than using a render target.


Como setar o atributo autofocus automaticamente em input HTML por JavaScript?

Question: Preciso setar automaticamente o autofocus no input contido em um modal sempre que abri-lo.
Qual função JavaScript posso usar para isto?

<input type="email" class="form-control" placeholder="Informe o e-mail" value="{{cliente.getEmail()}}" name="email" id="emailCliente" required>
Comment: como está abrindo esse modal? vai depender dele!
Comment: Clicando em um botão ele abre com o input. Preciso que esse input receba autofocus automaticamente.
Comment: Coloque todo exemplo na sua pergunta não temos como saber o que fez ai!
Answer: Pela classe que está no input form-control me parece que vc usa Bootstrap. Nesse casso na documentação eles indicam que use o evento .on('shown.bs.modal', function () { } para interagir com o modal, então no seu caso ficaria assim. Veja a documentação oficial https://getbootstrap.com/docs/4.0/components/modal/
$('#myModal').on('shown.bs.modal', function () {
    $('#myInput').focus();
})

Veja o modelo funcionando.

<!DOCTYPE html>

 <meta charset="utf-8" />
 <title>Page Title</title>
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <link rel="stylesheet" type="text/css" media="screen" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" />
 <link rel="stylesheet" type="text/css" media="screen" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal">
  Abrir modal com input focado
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

        <input type="text" value="sem foco" id="">
        <input type="text" value="input com autofocus" id="myInput">

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

Comment: Deu certo. Obrigado!
Comment: @VictorMoraeslegal que deu certo ai!
Answer: Você pode fazer isso  adicionando  ao  evento  que abre o  modal
function abrirModal(){
    var element = document.getElementsByName("email")[0];
    element.focus();
}

Fiz  umas  correções no  codigo  e você  pode ver  ele funcionando aqui
https://jsfiddle.net/c25gvj9b/