Convert Base Model To Sub View Model

Question: I have a model named DriverStaistic and a view model which inherits from it
the view model doesn't contain any extra properties it's just an empty inheritance of DriverStaistic, the reason I'm doing that is that I receive the model objects from an external library and I want to keep coupling to the minimum.
since the base and the sub class contains the same properties I was wondering if we there's a neat way to convert between them other than using the lambda expression which requires me to modify it every time I add or omit a property
I have come out with this solution using reflection but I believe it will present performance issues in the future.
can anyone come with a better suggestion?
public static void FromDriverStatistic(this DriverStatisticsVm viewModel, object model)
{
    bool isDriverStatistic = model is DriverStatistic;

    if(!isDriverStatistic)
        throw  new InvalidCastException();

    var modelProperties = model.GetType().GetProperties();
    foreach (var property in modelProperties)
    {
        property.SetValue(viewModel, property.GetValue(model));
    }
}

Comment: "I receive the model objects from an external library and I want to keep coupling to the minimum" which results in the need to do dirty hacks like this?
Answer:
I have come out with this solution using reflection but I believe it will present performance issues in the future. can anyone come with a better suggestion?

The option is to set all properties one by one, i.e.:
public static void FromDriverStatistic(this DriverStatisticsVm viewModel,  DriverStatistic model)
{
    viewModel.PropertyA = model.PropertyA;
    viewModel.PropertyB = model.PropertyB;
    //and so on...
}

The drawback with this approach is obviously that you must know all property names at compile-time and modify the mapper method whenever a property is added, removed or renamed from either of the classes.
The other option is to use reflection but the drawback with this is that you lose the compile-time safety and some performance.
You need to make a trade off decision. If there are only a few properties to be set, the price you will pay for using reflection won't be that high. You should also be able to re-use the same method or logic for several different view model/model type mappings. So if you want flexibility, stick with using reflection. If performance and compile-time safety is critical, don't.
Comment: certainly that's not better than using lambda expression on the contrary I could have made use of some of nice performance capabilities of the lambda expression

Convert Base Model To Sub View Model


How to make Views fill all LinearLayout size

Question: I'm trying to create some Views dynamically  in LinearLayout, the issue when the number of the created views is small the result looks like this :

And I want to make Views fill all LinearLayout like this :

LinearLayout  XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/palette_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:orientation="horizontal" />
</LinearLayout>

View XML:
<View xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="40dp"
    android:layout_weight="1" />

Java:
 public class ColorPaletteResultsFragment extends Fragment {
    public ColorPaletteResultsFragment() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_palette_results, container, false);
        configure(view);
        return view;
    }

    private void configure(View view) {
        LinearLayout palletContainer = (LinearLayout) view.findViewById(R.id.palette_container);
        fillPalletColors(mPalette, palletContainer);
    }

    private void fillPalletColors(List<Integer> colors, LinearLayout paletteContainer) {
        if (getActivity() != null && isAdded()) {
            LayoutInflater inflater = getActivity().getLayoutInflater();
             for (int color : colors) {
                    View palletColor = inflater.inflate(R.layout.suggested_color_item, paletteContainer, false);
                    palletColor.setBackgroundColor(color);
                    paletteContainer.addView(palletColor);
                }
        }

    }
}

Comment: I tested your code and it is working fine for me. Do you change the layout params anywhere? paletteContainer is a reference to palette_container? I think you may need to share more info/code
Comment: @W0rmH0le Massive thanks for ur help, I've updated my question with more code
Answer: For each of the Views you created, it looks like you'll need to assign a weight to the LinearLayout.LayoutParams params for that view.
The weight would be 1/n where n is the number of views.
int viewCount = 6;
View view = new View(getContext());
            float weight = 1/viewCount;
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,weight);
            view.setLayoutParams(params);


How to extend Ansible's setup module to gather more information?

Question: On Solaris Ansible's setup module does not gather information about installed zones. How to extend the setup module to gather the output of zoneadm list -iv?
Answer:
create a script named /etc/ansible/facts.d/zoneadm.fact and gather whatever information you need there. This can be whatever you want (bash/python/etc).
When you are done, echo it to stdout as json format.
Deploy that script via ansible, make it executable
Gather facts and notice that the new facts are present under ansible_local.zoneadm

More infos can be found here
Comment: They will be run on the machine on which they're located, which is why @user2599522 was suggesting that you first deploy the facts script to all your hosts.  More on that [here](https://docs.ansible.com/ansible/playbooks_variables.html#local-facts-facts-d).
Comment: What do you mean by `static` ? that script is run everytime you perform the setup step, i.e. `ansible all -m setup`.
Comment: Maybe I miss understood it. Will this script be executed on the target host or on the Ansible host?
Comment: @XiongChiamiov Thanks! I misunderstood that I have to deploy the fact scripts myself to the target system. I thought Ansible transfers everything necessary on its own and that it is not necessary to deploy anything (agentless). Now things start making sense. ;-)
Answer: I was dealing with the same dilemma ~2y ago. Previous reply is correct, but you have to deploy some stuff before and the rerun Ansible to get new facts too.
There's an option to write your own Ansible module, which returns JSON looking like:
{
  'changed': false,
  'ansible_facts': {
     'sunos': {
       'zonename': 'global',
       'zones': {},
  }
}

Facts returned by such module are then merged to ones coming from setup module. To be more portable, best to include such module into Ansible role and include just one task calling this module, plus add tag always, to get this fact collection run even when you choose subset of tasks by specifying tags on cmdline.
I've got my old role pushed here on GitHub. Probably will not work out-of-the-box... was used with Ansible 1.0, but get inspired.
Comment: Your solution is somehow different. Instead of collecting the data with a facts script you wrote a module bypassing the facts collection process. Any additional `setup-sunos` module has to be used explicitly whenever `setup` runs automatically. How did you achieve this?
Comment: You miss the point, it is not bypassing anything. The same way `setup` module works. Try `ansible -vvv your_host -m setup` and you'll see very similar `JSON`. Anytime some module returns `ansible_facts`, it is getting merged not overwritten.
Answer: The reason for my misunderstanding was, that I thought, I have to put something on the Ansible machine, which gets automatically deployed to the target system as it is done with the modules. But facts gathering works differently! One has to take cake, that the fatcs gathering scripts are already on the target system, before the setup starts working. I would say this is a design error in Ansible or at least a still not implemented feature.
To add this missing functionality, it is necessary to write a play, which works before all other things. I came up with the following solution:
---
- name: facts deployment
  gather_facts: false
  hosts: all
  become: true
  tasks:
    - set_fact: setup_necessary=false
    - file:
        path: "/etc/ansible/facts.d"
        state: directory
        recurse: yes
      register: facts_directory
    - set_fact: setup_necessary=true
      when: facts_directory.changed

- name: solaris facts
  gather_facts: false
  hosts: solaris
  become: true
  tasks:
    - include: deploy_fact.yml
      with_items:
        - { shell: bash, file: nonglobal_zones }
        - { shell: bash, file: solaris_eeprom }

- name: setup after facts update
  gather_facts: false
  hosts: all
  tasks:
    - setup:
      when: setup_necessary

The above playbook does all plays with gather_facts: false, to prevent any setup run before the facts have been deployed. All plays set the variable setup_necessary, when any change to the target system has been made. It is not possible to use a handler for this, because handlers run at the end of a play, but not at the end of a playbook or after some plays (Ansible limitation 1).
First the directory gets created and after that all facts files are deployed. It is necessary to put the body of the look into a separate task file, because it is not possible to group two tasks together in a playbook (Ansible limitation 2).
The contents of the deploy_fact.yml file uses the template module to transfer the facts scripts to the target system.
---
- name: "/etc/ansible/facts.d/{{item.file}}.fact"
  template:
    src: "{{inventory_dir}}/facts.d/{{item.shell}}.j2"
    dest: "/etc/ansible/facts.d/{{item.file}}.fact"
    mode: 0755
  register: facts_file
- set_fact: setup_necessary=true
  when: facts_file.changed

The reason why I use the template module is, that every facts script needs some kind of error handling which takes care that proper JSON gets created in case of an error.  This is my current error handling but it can be still improved. Some people also don't like set -eu, which is somehow a matter of taste.
#! /bin/bash
{% include item.file + '.bash' %}

set -eu

_stderr=$(mktemp)
trap 'rm -f "$_stderr"' EXIT
if _stdout=$(main 2>$_stderr); then
  if [ "$_stdout" ]; then
    echo "$_stdout"
  else
    echo null
  fi
else
  jq -Rsc "{\"ERROR\":{\"failed\":true,\"exit\":$?,\"msg\":.}}" $_stderr
fi

The template does nothing more than just including the file passed by the loop via the implicit item variable.  The wrapper expects from the included file, that a main functions gets defined. This is my main function for non-global zones:
main ()
{
  zoneadm list -i |
  grep -v global |
  jq -Rc . |
  jq -sc .
}

And this one collects the Solaris eeprom data:
main ()
{
  eeprom |
  sed 's/^\([^=]*\)=\(.*\)$/{"\1":"\2"}/' |
  sed 's/^\(.*\): data not available.$/{"\1":null}/' |
  sed 's/:"false"}$/:false}/g' |
  sed 's/:"true"}$/:true}/g' |
  sed 's/:"\([0-9][0-9]*\)"}$/:\1}/' |
  sed '/^{"boot-device"/{s/":"/":["/;s/ /","/g;s/"}$/"]}/;}' |
  jq -sc add
}

My bottom line is that it is somehow possible to extend Ansible's facts gathering but it is far from obvious and it is a bit painful, because it makes any ad hoc usage of the setup module impossible. Instead of requiring the user to implement the above stuff, Ansible should move all of the above into the setup module (Ansible limitation 3).


Do there exist dimensionless quantities in dimensional analysis?

Question: In physics and science in general researchers use dimensional analysis and they often state that some quantities are dimensionless like for example the number of some objects but I don't think this is true here's why.
Consider a typical problem, a coin has diameter $x\,\textrm m$ and we place a number of coins next to each other in a straight line which has length $y\,\textrm m$, find the number of coins.
The answer is fairly simple we just do $$\frac{y\,\textrm m}{x\,\textrm m}=\frac{y}{x}$$ which looks like it's a dimensionless quantity, but now let's consider the unit $[c]$ that measures the number of coins, so $1 [c]$ means one coin and so on, then $x$ is not measured in meters but in meters per coin, so $$\frac{y\,\textrm m}{x\,\textrm m/[c]}=\frac{y}{x} [c]$$ which is not dimensionless.
The same thing can be done to any problem, we can define a unit of measurement to measure anything.
Is my reasoning correct?
Comment: No, you don't need a unit conversion to state that $6$ apples and $6$ bananas are the same number of fruits. There's also no choice of which unit to choose here: while length, mass etc. don't come with a unit and one needs to be defined in order to specify a length or mass, the number of coins doesn't need a unit to be specified.
Answer: Dimensionality is always with respect to some unit system – and the typical one, SI, does not include "coin" as a unit. Thus if you add "coin" to SI, the number of coins is no longer a dimensionless quantity. However, the SI does include a unit which is very similar to your "coin" unit, in that it merely measures a count of objects, and which some scientists have argued should not be in SI – the mole.
Another example of the relativity of dimension lies in electromagnetism: the constant of proportionality in Coulomb's law has a dimension in SI but is simply $1$ in electrostatic cgs (centimetre/gram/second) and $\frac1{4\pi}$ in Gaussian cgs.
Regardless, there do exist physical quantities that are inherently dimensionless – it is simply not sensible to define a unit from them. The prime example is the fine-structure constant $\alpha\approx\frac1{137}$.


Criando novo array com objetos específicos de outro array - Javascript

Question: Em javascript eu tenho um array "cartasUsuario"  e preciso criar um novoArray  apenas com os valores do .texto que entrarão no cartasUsuario. Em algum momento preciso dar um .push e será acrescentado ao final do array cartasUsuario um objeto nesse modelo {texto: "A♠", valor: 11}.
let cartasUsuario = []
let novoArray = []

(3) [{…}, {…}, {…}]
0: {texto: "A♠", valor: 11}
1: {texto: "2♥", valor: 2}
2: {texto: "3♥", valor: 3}

O que preciso fazer para criar outro array com o conteúdo concatenado que receber do .texto?
console.log(`${cartasUsuario[0].texto + cartasUsuario[1].texto + cartasUsuario[2].texto} = pontuação ${usuarioValor}`)

Eu poderia utilizar cartasUsuario[0].texto, cartasUsuario[1].texto etc mas ficaria muito grande quando entrarem mais cartas. Queria algo que resolvesse isso de maneira mais prática.
Comment: Realmente não entendi muito bem o que você está tentando fazer... Você quer concatenar todas as propriedades `texto` dos objetos do array `cartasUsuario` ou somar os números da propriedade `valor`? Tente **[edit]** a sua pergunta para torná-la um pouco mais clara. :-)
Comment: Você quer criar um novo array só com o atrubuto texto?
Comment: Tentei editar, mas é isso mesmo. Eu preciso concatenar todas as propriedades texto dos objetos do array cartasUsuario.
Answer: Para criar um novo array com apenas a propriedade texto é necessário iterar pelo array cartas e retornar o texto, isso pode ser feito assim:

let cartasUsuario = [
{texto: "A♠", valor: 11},
{texto: "2♥", valor: 2},
{texto: "3♥", valor: 3}
]

let novoArray = cartasUsuario.map(c => c.texto)

console.log(novoArray)
Answer: Muito obrigado pela ajuda. Consegui destravar aqui. Eu utilizei algo semelhante ao que o Ewerton Belo propos:
novoArray = Array.from(cartasUsuario, ({ texto }) => texto);

já resolveu meu problema. Muito obrigado a todos!
Comment: Marque com o "✅" que aparece ao lado da resposta, a resposta mais adequada a sua pergunta. Além disso, caso queira concatenar e não saiba, pode usar o `join()`. Ficando `novoArray.join()`
Comment: Sou novo aqui, tô aprendendo ainda. Obrigado pela força, já marquei lá na sua resposta


Dependency gtools notavailable while installing MSA Package

Question: So I'm trying to install the Market Segmentation Analysis (MSA) package for a book I'm reading. The website that the book uses is here:
http://www.marketsegmentationanalysis.org/
On this website, I followed the instructions to install package MSA directly from the web page:
install.packages("https://homepage.boku.ac.at/leisch/MSA/packages/MSA_0.3.tar.gz", repos = NULL, type = "source")
However, once I enter the code, the console is showing the following error (image attached):
error
As a beginner to R, I'm not sure what I'm doing wrong or if the MSA package is not compatible with my version of R (1.2.5019)
Any help would be greatly appreciated!
Comment: Install gtools first (you can use the tools menu in R Studio) and then install MSA from the archive itself, not from the CRAN.
Comment: Fantastic! Just installed gtools. What do you mean from the archive itself vs. CRAN? Thanks again
Comment: Download the .tar.gz file for MSA to your machine and then use the install package menu to install the package from the file your downloaded.
Answer: You just need to install gtools package before to install the MSA package.
<code>install.packages("gtools")
install.packages("https://homepage.boku.ac.at/leisch/MSA/packages/MSA_0.3-1.tar.gz", repos = NULL, type = "source")
</code>


Grails: how do I set up a response wrapper in a Grails filter?

Question: I want to modify the response content of specific Grails requests.  How do I configure a ResponseWrapper in a request filter?
I had hoped it would be the following, but the response is a read-only property:
class MyFilters {
    def filters = {
        wrapFoo(controller:'foo', action:'bar') {
            before = {
                response = new MyResponseWrapper(response)
            }
        [...]

Thanks!
Answer: You can't - Grails filters are wrappers for Spring HandlerInterceptors and are invoked further up the processing chain than servlet filters. If you want to wrap the response you need to use a real servlet filter.
Create the class in src/java or src/groovy that implements javax.servlet.Filter and register it in web.xml like you would in a non-Grails application. To get access to web.xml run grails install-templates and edit the file in src/templates/war


Conditions for a function to be increasing close to 0

Question: Suppose $f:[0,1]\to[0,1)$ is a continuous function such that $f(0)=0$ and $f(x)>0$ for $x\neq 0$. Under what natural conditions there exists $\epsilon>0$ such that $f$ is strictly increasing over $[0,\epsilon]$?
For example, if $f$ is differentiable over [0,1] and $\partial_+ f(0)\neq 0$ (the right-derivative is non-zero), then such $\epsilon$ must exist, by here. Could we make the same conclusion if the differentiability assumption is removed (so, instead of differentiability, we have that  $\partial_+ f(0)$ is defined and is positive).
Comment: @afshi7n I don't think so. Imagine a function that essentially follows the line $y = x$, with small but sudden, violent oscillations, increasing in intensity as  $x$ moves towards zero. It will be possible to keep these oscillations above  the line $y = 0$. To answer your original question, continuity of $f_+'$ at $0$  is enough. Of course, the condition $f'(x) \geq 0$ is sufficient if it is also known that $f'(x)$ is not zero on any interval.
Comment: You seem to be saying that if the right derivative of $f$ is $0$ at $0$, then $f$ is increasing in some interval $[0,c]$. That is not true. See here: https://math.stackexchange.com/questions/807537/function-which-derivative-at-0-is-1-but-is-not-monotonic-increasing
Comment: So, from the linked question, do we need that $f'$ is continuous on some interval $[0,c]$? Or, is that a sufficient condition, anyway?
Comment: @user49640 the right derivative of $f$ is positive at 0. But even so, I think you're saying that in addition to that, the derivative needs to be positive at a whole interval $(0,\epsilon]$? Wouldn't the condition that $f(x)>0$ for $x>0$ buy us anything here?
Comment: @Tony From looking at the proof, I think continuity of $f'$ is needed only at the limit point.
Answer: If $f$ is not strictly increasing on $[0,\epsilon]$, there are $a,b$ with $0 \le a < b \le \epsilon$ and $f(a) \ge f(b)$.  The  maximum value of $f$ on $[a,b]$ is attained at some $c < b$, and then the upper right-hand Dini derivative $$f'_+(c) = \limsup_{x \to c+} \frac{f(x) - f(c)}{x-c} \le 0$$
Thus a sufficient condition for $f$ to be strictly increasing on $[0,\epsilon)$ is that $f'_+(x) > 0$ for all $x \in [0, \epsilon)$.  On the other hand, a necessary condition for $f$ to be increasing on $[0,\epsilon)$ is that $f'_-(x) \ge 0$ for all $x \in [0,\epsilon)$, where $f'_-$ is the lower right-hand Dini derivative $$f'_-(x) = \liminf_{t \to x+} \frac{f(t) - f(x)}{t - x}$$
Answer: Take $f(x) = \frac{1}{2}x  +x^2 \sin{\frac{1}{2x}} $ and $f(0)=0$
From the inequality $\sin{\frac{1}{2x}} \leq \frac{1}{2x} $  we can conclude that $f \ge 0$ one $[0,1]$.  Also  $f' (0+) = \frac{1}{2}$ and $f' (x) = \frac{1}{2} - \cos{\frac{1}{2x}} + 2x \sin{\frac{1}{2x}} $ for all $x >0$.
Observe that $f'$ oscillates with positive and negative values as $x \to 0^+.$ This shows $f$ can not be increasing on any interval $[0, \epsilon].$
This function satisfies all conditions in question but not the claim!
Comment: Thanks, this example is very helpful. It shows that some sort of continuity of $f'$ at 0 is needed. Now, if it's given that $f'$ is continuous over (0,1), and that the right limit $\lim_{x\to 0^+} f'(x)$ exists and is finite, does it also imply that $\lim_{x\to 0^+} f'(x)=\partial_+ f(0)$? This will solve my problem.. thanks!
Comment: I think the answer to the last question is positive. That seems to be just a consequence of L'hospital's rule.
Comment: Yes, If $\lim_{x\to 0^+} f'(x)$ exists , it has to be  equal to $\partial_+ f(0)$

@afshi7n


PHP as FastCGI: Custom php.ini not working

Question: I'm running PHP as FastCGI (I needed multiple versions of PHP).
.htaccess
<code>AddHandler php5-fastcgi .php
Action php5-fastcgi /cgi-bin/php-5.2.17.fcgi
</code>
cgi-bin/php-5.2.17.fcgi
<code>#!/bin/sh
PHP_CGI=/usr/local/php/5.2.17/bin/php-cgi
PHP_FCGI_CHILDREN=4
PHP_FCGI_MAX_REQUESTS=1000
export PHP_FCGI_CHILDREN
export PHP_FCGI_MAX_REQUESTS
exec $PHP_CGI -c /home/john/www/crm/php.ini
</code>
The main issue is that PHP is ignoring -c option. My php.ini files is NOT loaded.
Can anybody share any suggestions?
Answer: My first thought is permissions -- Apache typically runs as a limited user, often www-user or apache, depending on your flavor of Linux and how you installed Apache.
This means that with the default permissions on pretty much all Linuxes (Linii?), the Apache user (which will also be the same user running php-cgi) cannot read any file inside your home directory.
I would move the php.ini file to another location (e.g. /usr/local/php/crm/php.ini), which I suspect will solve your problem here. Another option is to simply spawn the php-cgi process using an entirely separate script, optionally running under its own user account, and have Apache talk to that.
Comment: I thought about this. Tried everything in this matter ;) I tried moving php.ini to cgi-bin directory, tried to delete -c option. Nothing works. I'm out of ideas.
Answer: i'm new to that Topic, so please dont kill me if i'm Wrong but shouldnt you use something like this:
<code>    <Directory "/path/to/doc/root">
      Options Indexes MultiViews FollowSymLinks +ExecCGI
      FCGIWrapper /path/to/cgi-bin/php-5.2.17.fcgi .php
      Order allow,deny
      allow from all
    </Directory>
</code>
Try using the -d Switch and check in phpinfo if you can change things this way.
If it works your probably on the right track (and i am wrong :) )


N-Queens problem. Returning array from functions c++

Question: While trying to solve the n-queens problem in c++. I came across this error where I would get the correct answer but when returning the array pointer, I end up getting garbage numbers instead of my answer. The weird part about this is that I use recursion to solve the problem and I only get garbage numbers when the recursion gets used (even though it correctly passes through the recursion). The array is completely correct before returning it.
int* Successor(int board[], int n) {
    bool currentlyLegal = isLegalPosition(board, n);
    int firstZero = -1;
    int templast;

    for(int i = 0; i < n; i++) {
        if(board[i] == 0) {
            firstZero = i;
            break;
        }
    }

    if(currentlyLegal) {
        if(firstZero != -1) {
            for(int i = 1; i < n; i++) {
                board[firstZero] = i;
                if(isLegalPosition(board, n) && i != lastNum) {
                    return board;
                }
            }
            lastNum = -1;
            board[firstZero - 1] = 0;
            Successor(board, n);
        } else {
            templast = board[n - 1];
            for(int i = board[n - 1]; i < n; i++) {
                board[n - 1] = i;
                if(isLegalPosition(board, n) && i != board[n-1] && i != lastNum) {
                    return board;
                }
            }
            lastNum = templast;
            board[n - 1] = 0;
            Successor(board, n);
        }
    } else {
        if(firstZero != -1) {
            if(firstZero != 0) {
                for(int i = board[firstZero - 1]; i < n; i++) {
                    board[firstZero - 1] = i;
                    if(isLegalPosition(board, n) && i != board[firstZero - 1]) {
                        return board;
                    }
                }
                lastNum = -1;
                board[firstZero - 1] = 0;
                Successor(board, n);
            } else {
                board[0] = 1;
                return board;
            }
        } else {
            templast = board[n - 1];
            for(int i = board[n - 1]; i < n; n++) {
                board[n - 1] = i;
                if(isLegalPosition(board, n) && i != board[n - 1] && i != templast) {
                    return board;
                }
            }
            lastNum = templast;
            board[n - 1] = 0;
            Successor(board, n);
        }
    }

}

Answer: Your recursive calls don't return anything. With all warnings on, you should be seeing something about "not all control paths return a value". Change your recursive calls to
return Successor( board, n );

Comment: then a question pops up in my mind. Why would he need a return value when the only thing the function can return is `board`
Comment: It doesn't, as far as I can tell. Possibly a stepping ground?


How to copy data from one node reference to another node reference in same content type

Question: I have already saved a lot of data in a content type 'Events' in the node reference field field_organization. However, I need the data to be moved to the field field_affiliation also within the same content type.
Is there a way to do this with VBO and PHP command or another simpler way without code?
Answer: As far as I know VBO is rather not for this kind of job, I also don't know any other module to help you with this except the migrate module but I also think that it won't be of any help for you. What you are describing is called "migration", transferring and storing data from one place to an other, even if it is just one field or an entire website. Most migration tasks require at some point, if not at all points, code writing, code to  manage the data during the migration. Fortunately, to your case is just a field, so you'll need to write a small script by taking advantage of the Drupal's node API, to transfer the data from one field to another, and that's it.
Rough idea on how to do it:
$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'events')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

$result = $query->execute();

if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);
}

foreach ($nodes as $node) {
  $value = $node->field_organization[LANGUAGE_NONE][0]['value'];
  $node->field_affiliation[LANGUAGE_NONE][0]['value'] = $value;
  field_attach_update('node' ,$node);
}

Use drush to run your script by using this command :
drush php-script site/all/scripts/script_name
I know, this is too much for someone who has not much experience with Drupal yet but if you are really serious in getting involved with it you should start learning and use those things as much as possible.
Lastly, if you still insist to do it without writing a single line of code, do it manually, but you will soon discover that that way has a major disadvantage if your nodes are more than one or two hundred.
Answer: If you have access to PHPMyAdmin or any other database viewing program, all you have to do is export the field_data_organization table and import it into field_data_affiliation.
Clear flush/cache in Drupal to see changes.
Comment: Don't forget to increase the `max_allowed_packet`  and `max_execution_time` otherwise the browser will hang in case of many items.


Remote access of Stratos Account Manager from IS

Question: I need to be able to update the tenant account information from Identity Server without having to login to the Apache Stratos Manager. I intend to do this via a custom jsp page.

How can this be done?
What jars need to be added to IS?
What method calls to perform the calls?

I have tried to copy the account-mgr.jsp code but fail to access the AccountMgrService.
Answer: You need to copy the following jars from Manager to IS,
|-- org.wso2.carbon.account.mgt-1.5.2.jar
|-- org.wso2.carbon.account.mgt.stub-3.2.2.jar
|-- org.wso2.carbon.account.mgt.ui-1.5.2.jar
|-- drools-5.0.1.wso2v1.jar
|-- jsr94-1.1.0.wso2v1.jar
|-- org.wso2.carbon.billing.core-1.5.2.jar
|-- org.wso2.carbon.billing.mgt-1.5.2.jar
|-- org.wso2.carbon.email.sender-1.5.2.jar
|-- org.wso2.carbon.email.verification-3.2.1.jar
|-- org.wso2.carbon.rulecep.adapters-3.2.0.jar
|-- org.wso2.carbon.rulecep.commons-3.2.0.jar
|-- org.wso2.carbon.rule.core-3.2.0.jar
|-- org.wso2.carbon.rule.engine.drools-3.2.0.jar
|-- org.wso2.carbon.rule.engine.jsr94-3.2.0.jar
|-- org.wso2.carbon.rule.server-3.2.0.jar
|-- org.wso2.carbon.usage-1.5.2.jar
`-- org.wso2.carbon.usage.meteringqueryds.stub-3.2.0.jar

Also copy billing-config.xml from $MANAGER_HOME/repository/conf to $IS_HOME/repository/conf directory.
Ideally it should only require account.mgt.*.jars, but since account management depends on billing and so on you will need all the above mention jars in you classpath. This is as of the latest WSO2 Stratos release version 1.5.2.
We are looking into making account management independent from billing.
Comment: This method does cause to appear in the menu the following link configure-account . However, log file shows the following                                                                   [WSO2 Stratos Identity] ERROR org.apache.axis2.rpc.receivers.RPCMessageReceiver} -  Exception occurred while trying to invoke service method getCustomerWithName {org.apache.axis2.rpc.receivers.RPCMessageReceiver}
....
Caused by: java.lang.NullPointerException
 at org.wso2.carbon.billing.mgt.services.BillingDataAccessService.getCustomerWithName(BillingDataAccessService.java:39)
Comment: Okay, this works. My problem was that my billing-config.xml had an incorrect parameter. I corrected it and now I am able to get this to work.
Comment: Just as a side note: I had to add org.wso2.carbon.register.ui-1.5.1.jar and org.wso2.carbon.tenant.register.stub-3.2.0.jar also before I could do an update on the form. I may only need one of those but to be safe I put both.


How to get track metadata from acoustID with Python

Question: I have a file.mp3 with unknown tags. I've used this to get the acoustID:
import acoustid
acoustID= acoustid.match(API_KEY, filepath)

acoustID contains several candidates, let's say I choose the best one: '0f6eb38a-d6c9-4f87-a9a7-6e7b0eeb4281'.
I've tried this but it doesn't give many info:
import musicbrainzngs
musicbrainzngs.get_recording_by_id(acoustID)

How to get the corresponding tags (album, tack number, genre, band, etc...) from this acoustID ?
Answer: Your acoustID is not an acoustid, but the MusicBrainz Identifier (MBID) of a Recording.
You're correct that musicbrainzngs.get_recording_by_id by default only returns a very small set of data. It's a wrapper around the MusicBrainz lookup API that returns data based on what was requested via the inc parameter. That is available in musicbrainzngs as the includes parameter to the get_*_by_id functions. If you use
musicbrainzngs.get_recording_by_id("0f6eb38a-d6c9-4f87-a9a7-6e7b0eeb4281", includes=["artists", "releases"])

more data - in this case about the artists of the recording and the releases it appears on - will be returned. You need to define yourself (or ask the user) to chose the correct release, because you can't tell from the MBID of the recording alone which release the should be considered "correct".
Answer: Finally found this: https://acousticbrainz.org/. From your browser you can use this url: https://acousticbrainz.org/<my acoustID>. From your code you can get a big json data file with all metadata on this track from this url: https://acousticbrainz.org/api/v1/<my acoustID>/low-level
For a python script you can use something like this:
import acoustid
import urllib.request, json

file = "path/to/myAudioFile"
API_KEY = 'cSpUJKpD'

candidates = acoustid.match(API_KEY, file)  # returns a generator of candidates

best_score, best_acoustId, best_title, best_artist = next(candidates)

metadata = {}
with urllib.request.urlopen("https://acousticbrainz.org/api/v1/" + best_acoustId + "/low-level") as url:
    data = json.loads(url.read().decode())
    metadata = data['metadata']

For more info about acoustid.match() you can check their github page, especially here: https://github.com/beetbox/pyacoustid/blob/master/aidmatch.py


Definition of $\hat{G_1}\times \hat{G_2}$ where $G_1,G_2$ are abelian groups and $\hat{G}$ is the dual of $G$

Question: The question is in the title. I want to know what happens to $(\chi_G,\chi_H)\in\hat{G}\times \hat{H}$. Are they just passively sitting there as a pair or they give something when applied on $(g,h)$?
My hunch is $(\chi_G,\chi_H)(g,h)=\chi_G(g)\chi_H(h)$ but is this the definition? I may be wrong.
Answer: What you have found out is that there is a canonical map
$$m : \hat{G}_1 \times \hat{G}_2 \to \widehat{G_1 \times G_2}$$
which maps $(\phi,\psi)$ to the mapping $m(\phi,\psi) : (g,h) \mapsto \phi(g) \psi(h)$. But by itself, $(\phi,\psi)$ cannot act on $(g,h)$, you have to apply this $m$ first. The map $m$ is a bijection, so it's reasonable to view $(\phi,\psi)$ as an element of the dual of $G_1 \times G_2$ anyway.
Comment: If $\chi \in \widehat{G_1 \times G_2}$ then $\phi(g)= \chi(g,0)$ and $\psi(h)=\chi(0,h)$ are in $\hat{G_1}$ respectively $\hat{G_2}$ and $$\chi=m(\phi, \psi)$$ The mapping is always surjective....
Comment: @N.S. You're right... That's what I get for trying to veer of my usual areas of math :) I was thinking about maps like $V^* \otimes W^* \to (V \otimes W)^*$ which are not always isomorphisms (when $V$, $W$ are finite dimensional), but of cours the situation is different here.


Unexpected value X imported by the module Z when using flag --aot

Question: My app is very slow until load finish when running on browser (I dare not speak about mobile uhhhh 10-15seconds) Yes, I do ng build --prod and it's still slow.
So with angular cli beta 16 I try the new flag --aot
And I get a lot of imports and declarations error:
 0% compilingUnexpected value 'FileDropDirective' declared by the module 'AppModule'
Error: Unexpected value 'FileDropDirective' declared by the module 'AppModule'
    at C:\Users\...\node_modules\@angular\compiler\bundles\compiler.umd.js:14174:33
    at Array.forEach (native)

Then just for fun I comment 3 libs which did me this error, just to see if it will continue to compile... NO ! I get another error:
10% building modules 6/12 modules 6 active ...ode_modules\style-loader\addStyles.jsSyntaxError: Unexpected token ILLEGAL
    at WebpackResourceLoader._evaluate (C:\Users\...\node_modules\@ngtools\webpack\src\resource_loader.js:75:24)

How achieve? thanks
Comment: Can you show us some source code please ? Your AppModule and FileDropDirective ;)
Comment: here you are: http://pastebin.com/fxAUmDBF
Answer: Version 2.0.0 of angular2-mdl hase been released today. AOT is now supported.
Comment: i know. will be fixed with 2.0.1. but the readme content is the same as on giihub.
Comment: BEAUCOUP DE PROBLEMES, I get lot errors after update to 2.0.0! In app.component.ts I use service MdlDialogOutletService and I get `angular2-mdl/components/index"' has no exported member 'MdlDialogOutletService'.` then In my dialog component dialog I have http://pastebin.com/UbJs3Y9U and I get `WARNING in ./src/app/edit-dialog/edit-dialog.component.ts
92:170 export 'MdlDialogReference' was not found in 'angular2-mdl'

WARNING in ./src/app/edit-dialog/edit-dialog.component.ts
92:208 export 'MdlDialogReference' was not found in 'angular2-mdl'
`
Comment: I also have these error: `WARNING in ./src/app/tabs-view/tabs-view.component.ts
305:98 export 'MdlDialogService' was not found in 'angular2-mdl'
`
Comment: So I tried remove this MdlDialogOutletService and put only  in index.html so I get always error `'MdlDialogService' was not found in 'angular2-mdl'` and
 `MdlDialogReference' was not found in 'angular2-mdl`
Je ne comprends pas!
Comment: please read the https://github.com/mseemann/angular2-mdl/blob/master/CHANGELOG.md. the version number increases because of the breaking changes. thats the way semver works.
Comment: I think it's not an problem to get it working but before I import all service from angular2-mdl  but now export not found with MdlDialogService and MdlDialogreference so I need import them from `import {MdlDialogService, MdlDialogReference} from 'angular2-mdl/components/dialog/mdl-dialog.service';`

Does this normal
Comment: you need to import from 'angular2-mdl': import {MdlDialogService, MdlDialogReference} from 'angular2-mdl'
Comment: YES that's what I did ! please check http://i.imgur.com/aNFnmbT.jpg export are failed
Comment: strange. i'm using beta.25 of wepback but this could not be the problem (here is my testproject: https://github.com/fit-4-angular-2/course-menu. can you post the content of the folder npde_modules/angualr2-mdl?
Comment: UDPATE: with cli17 I don't have error !  anyway forget this before !
Comment: @istiti never mind! i know the tooling is sometimes really  a big problem
Answer: I suppose that MdlModule and Angular2DataTableModule are some externals libs. If they don't include *.metadata.json for each of their Angular files, your AoT compilation cannot know what they do. You can't do much about it, just submit an issue so they update their libs to be compatible with AoT.
But for your FileDropDirective, I can't tell without the code.
Comment: How can I resolve it myself until fixed, there is way to achieve? some docs?
Comment: You can clone their project and build it yourself with the proper AoT configuration. Then call `npm pack` to generate a zip version of their lib for NPM. Then in your project, `npm install /path/to/this/zip.tar.gz` to override the public NPM version with your new AoT locale version.
Comment: by example: I tried `npm pack angular2-data-table` I get it then I need edit it no? before install. How and What I need to change to get it AoT-able :) thanks
Comment: You should `git clone` angular2-data-table, edit it, compile and build it with AoT, `npm pack` it, and `npm install` it in your project. For the AoT compilation part, you can start with https://angular.io/docs/ts/latest/cookbook/aot-compiler.html. You can also look at some other libs that already handle AoT compilation, like https://github.com/noemi-salaun/ng2-logger
Comment: not sure I'm able to get this lib able to be compiled using AoT but will contact team, hope will be enhanced, your logger seems nothing big change https://github.com/noemi-salaun/ng2-logger/commit/a6d5c3f03976b5abe1a48c2d607635de5245245e you only add ` "skipMetadataEmit": false` that's all ?


How to fix call to undefined function libraries_get_path() in multi-site install?

Question: I am setting up a multi-site Drupal 7 install. I have the base site set up correctly and running just fine. When I create the second site (a sub domain of the first site), the install.php script ran fine but when I try to view the site I get the following error:
<code>Fatal error: Call to undefined function libraries_get_path() in /var/www/drupalhome/d7/sites/all/themes/mytheme/template-preprocess.php on line 75
</code>
I assume that since the second site inherits everything from the first site (since it is the default install) that the second site should display just fine. However it looks like the second site doesn't know about the libraries module and is throwing the above error (at least that is my interpretation of it). My question is: how can I fix this?
Thanks.
Answer:
...since the second site inherits everything from the first site..."

To the best of my knowledge that's not how a multi-site setup works; in my experience there's no inheritance involved. Core code/modules/themes/libraries etc can be shared between any number of sites, but each has their own separate database (and files structure, potential for site-specific modules/themes etc.).
When you add a new site you get a fresh Drupal install, none of the settings from any of the other sites in the setup are copied over.
An inheritance-based workflow wouldn't make sense, as multi-sites can contain any number of completely different Drupal sites - the point is that they can share the resources mentioned above, and when it comes time to upgrade core/contrib modules you only have to do it once for all the sites in the setup.
You can solve the specific problem you're currently having by enabling the libraries module on the new site; but if your custom theme relies on other contrib modules to be installed as well, those will need to be enabled before the site will work properly. Similarly, if the custom theme relies on settings/variables that were available in the default site, those will need to be restored.
I think in your case it would make more sense to clone the default site and database into the new one (bypassing the installation procedure entirely), then make the necessary adjustments to distinguish it from the default site afterwards.
Either that, or wrap the default site's functionality up in Features/Config, perhaps creating an install profile along the way, and use that to instantiate the a clone when you need one.
Comment: Yes, I suppose using the term inherited might not be an accurate description. I just kind of view it that way as Drupal always looks for specific files before looking for more generalized files that apply for specific situation (whether that be templates, modules or themes). However I believe that your solution is the correct way to go to resolve this issue.


syntax error, unexpected 'if' (T_IF)

Question: Qual o erro?
$sql = "SELECT item1, item2, item3 FROM tab_exemplo WHERE"
if (isset($item3)) {echo 'quartos LIKE :A';}
if (isset($item2) || isset($item1) || isset($item4)){echo 'AND'}
if (isset($item4)){echo 'garagens LIKE :B';}
if (isset($item2) || isset($item1) || isset($item3)){echo 'AND'}
if (isset($item2)){echo 'tipoNegocio LIKE :C';}
if (isset($item3) || isset($item1) || isset($item4)){echo 'AND'}
if (isset($item1)){echo 'tipo LIKE :D';} echo '\"';

Answer: Procure organizar melhor seu código que evitará erros simples assim. Note abaixo como fica mais fácil ler e localizar problemas no código. Faltam ;  na finalização de várias linhas.
Acostume-se também interpretar as mensagens de erro e procurar na documentação sobre eles. Em programação erros acontecem aos montes. Se sempre que aparecer um tiver que perguntar pata alguém ficar lento e cansativo programar.
Muitas vezes o erro aparece em um lugar mas está em outro. O compilador/interpretador não consegue entender intenção. Se falta um ponto e vírgula que encerra o comando, então o erro só vai aparecer na linha seguinte quando encontrar algo estranho no que ele considera ainda o meio do comando (embora você programador tinha a intenção que fosse um comando novo).
Montar expressões SQL assim podem ser temerárias em termos de segurança dependendo de onde vem essas variáveis.
No comentário foi mencionado que seria para concatenar strings. Mesmo que o problema colocado na pergunta fosse esse, ainda teria que mudar muita coisa. Não só teria que concatenar a variável $sql no lugar de usar echo, mas também precisa rever a organização do texto já que desta forma não produziria uma consulta correta. Também acho estranho a forma de determinação do que deve concatenar.
Comment: O `;` nada tem a ver com concatenação, esse é outro problema. Se você quer concatenar, então concatene, mas não deixe de encerrar o comando. Parece um jeito confuso de concatenar. Principalmente usando `echo`. Se vai concatenar tem que usar a variável, não imprimir o texto.
Comment: tá certo porém gostaria de concatenar os echo´s junto com as strings do SELECT portanto não poderia colocar ; depois do where
Comment: exatamente isso, obrigado!

syntax error, unexpected 'if' (T_IF)


SQL Server Sub-query with min and Max values

Question: I'm having considerable difficulty understanding and using a nested subquery in T-SQL (SQL Server 2012):

Customer Name
Customer Number
Date of first sale
Date of last sale

I can create the table showing EITHER Min(sale_date) or Max(Sale_date using the below query but not both.
select
    cm_number, cm_name, dim_invoice_date
from
    fact_invoice_history
where
    fact_invoice_history.dim_invoice_date = (select MAX(fact_invoice_history.dim_invoice_date)
                                             from fact_invoice_history)

Please help. I know that this is a bit of a beginner question.
Comment: I suspect that you want this for each  cm_number?  (and not overall in fact_invoice_history).  Have you looked into Group By  ?
Comment: Yes, i'd absolutely need this to be by individual cm_number, not the max of the entire history. Thanks for the clarficiation.

How would a group by help? the Max date of sale would still be a distinct single value, not an aggregate. Same with Min date of sale

If i wanted to add the total value sold per cm_number I'd see the need, otherwise i'm not sure the value. Can you maybe elaborate a little?
Comment: or is it as simple as

select cm_number, cm_name, min(dim_invoice_date), max(dim_invoice_date)

from fact_invoice_history
Comment: What happens when you try that, along with Group By cm_number?  Then we also need max(cm_name).
Comment: So you want two records for each customer, one for first sale date and one for last sale date, or do you want a single record for each customer, containing both the first and the last sale dates?
Comment: hi all,
thanks for the assist. Solved.
Comment: Please share with what worked
Comment: @Boothy_79 If you've managed to solve your problem then please either post the solution as an answer and accept it once you can (there's is a time period to wait for accepting self answers) so that other people will know that the problem is solved, or delete the question entirely. Thanks.
Answer: the below solution worked fine.
    select
    cm_number,
    cm_name,
    min(dim_invoice_date) min_sale_date,
    max(dim_invoice_date) max_sale_date
from
    #fact_invoice_history
group by
    cm_number,
    cm_name

I probably asked the wrong question here though, but thanks for the help
Answer: select * into #fact_invoice_history from
    (select 1 as cm_number, 'one' as cm_name, '2018-09-01 10:15:00' as dim_invoice_date
    union all select 1, 'one', '2018-09-02 10:15:00'
    union all select 1, 'one', '2018-09-03 10:15:00'
    union all select 2, 'two', '2018-09-06 10:15:00'
    union all select 2, 'two', '2018-09-07 10:15:00'
    union all select 3, 'three', '2018-09-08 10:15:00') data

select * from #fact_invoice_history
-- ----------------------------------------
--  cm_number   cm_name dim_invoice_date
--  ----------- ------- -------------------
--  1           one     2018-09-01 10:15:00
--  1           one     2018-09-02 10:15:00
--  1           one     2018-09-03 10:15:00
--  2           two     2018-09-06 10:15:00
--  2           two     2018-09-07 10:15:00
--  3           three   2018-09-08 10:15:00
-- ----------------------------------------

select
    cm_number,
    cm_name,
    min(dim_invoice_date) min_sale_date,
    max(dim_invoice_date) max_sale_date
from
    #fact_invoice_history
group by
    cm_number,
    cm_name
-- ------------------------------------------------------------
--  cm_number   cm_name min_sale_date       max_sale_date
--  ----------- ------- ------------------- -------------------
--  1           one     2018-09-01 10:15:00 2018-09-03 10:15:00
--  3           three   2018-09-08 10:15:00 2018-09-08 10:15:00
--  2           two     2018-09-06 10:15:00 2018-09-07 10:15:00
-- ------------------------------------------------------------

drop table #fact_invoice_history


Question about directional derivative at a point

Question: A silly question. For example, let $f(x, y)=xy$, then it's a function from $\mathbb{R}^2$ to $\mathbb{R}$, and it is differentiable everywhere, so at a point $(a_1, a_2)$, the directional derivative at $a$ along directional $(v_1, v_2)$ is [$D_xf$ $  D_yf$]$(v_1, v_2)$ = $[a_2$ $ a_1](a_1, a_2)$.
Then let $v_1= (1, 2)$,  $v_2 = (2, 4)$, then is it right that $v_1, v_2$ point in the same direction? If it is, the two vectors point in the same direction, why, at any fixed point a, are the directional derivatives of $f$ along the two vectors different?
Answer: Since $v_2 = 2v_1$ which means they have the "same direction" and call it $u = \dfrac{v_1}{||v_1||}$. This means the directional derivatives are the same.
Answer: Good question.
You have to normalize your vectors to get unit vectors then find directional derivative by the dot product of the gradient vector and the unit vector.
If your vectors point at the same direction you have the same unit vectors so you have the same directional derivative.
Answer: To take the directional derivative along the direction of a given vector, we take the linear combination of the partials using the components of the unit vector in the direction in question as scaling factors.
Thus in a fixed direction, the derivative is always uniquely defined.


Search nodes and taxonomy terms

Question: I need to implement functionality for search nodes and taxonomy terms through one search form and display results in one listing.
I try to use these modules:
1. Apache Solr
2. Search API
3. Search API Solr Search
4. Search API multi-index searches
5. Search_api_views
I can't make apache solr module add taxonomy terms into index.
It's possible? What I do wrong?
Now my apache solr index only nodes.
I configure apachesolr module https://i.stack.imgur.com/dQa01.png
Also I configure Search API https://i.stack.imgur.com/BPCBK.png
Any help is appreciated
Answer: I do face similar situation and I am trying with http://drupal.org/project/apachesolr_term module.

This module provides basic indexing of the taxonomy terms for the
  multi entity branch of the Apache Solr Search Integration Module

I will post back my findings soon.
Comment: @Eugene It served my purpose. It indexed the terms in vocabularies chosen from config page. Hope it will help you as well.

Search nodes and taxonomy terms


Aplicação inicializar com Windows

Question: Tenho uma aplicação Java desktop, e preciso que ela seja sempre iniciada junto com o Windows (como um serviço do Windows por exemplo). Esta aplicação deve ficar rodando em segundo plano e sempre ficar aberta, pois vai executar tarefas periodicamente utilizando o Quartz.
Gostaria de saber como eu faço para que ela seja iniciada e mantenha-se sempre em execução?
Caso houver alguma falha e a aplicação não for iniciada, como executar um monitoramento para tentar executá-la novamente?
O processo deve ser automático, pois vou gerar o instalador desta aplicação utilizando o InnoSetup e os clientes vão fazer download da aplicação e instalar.
Ja avisando que fiz pesquisas, vi sobre o Java Service Wrapper, mas não sei como fazer ele manter a aplicação sempre rodando e monitorar tb. Gostaria de apenas uma orientação sobre.
Comment: você pode criar uma tarefa agendada no "Agendador de Tarefas", veja como ele funciona crie uma tarefa básica e entenda seus parâmetros, depois você terá criar um arquivo *.bath e/ou *.vbs para especificar os parâmetros para o mesmo ser inserido automaticamente no momento da instalação da sua aplicação em uma máquina de cliente.
Pesquisa na web como fazer backup automático utilizando arquivos *.bath e/ou *.vbs.
Comment: Conseguiu resolver sua dúvida? Alguma das respostas te ajudou?
Answer: Você pode criar uma chave no Regedit(Registro do Windows) através do próprio Java usando o seguinte código :
 String valor = "\"javaw -jar " + System.getProperty("usuário.dir") + "\\meuJar.jar\"";
WinRegistry.writeStringValue(WinRegistry.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", "meu Jar aplicativo exe", value);

E se quiser remover depois a sua chave criada para inicializar o aplicativo com o Windows :
WinRegistry.deleteValue(WinRegistry.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", "meu Jar aplicativo exe");

Ou você também pode criar um arquivo .bat e colocar este código dentro para criar uma chave e fazer o seu aplicativo iniciar junto com o Windows :
javaw -Xmx200m -jar C:\Caminho\para\jarfile\ArquivoJar.jar

E também se isto ainda não te ajudou,segue este link.
Answer: Você pode criar um serviço no Windows da seguinte forma, na linha de comando, rodando como administrador:
sc create meuServico binPath= "java -jar C:\to\my\service.jar" start= auto
                             ^^                                      ^
                       espaço||aspas                           espaço|

Preserve os espaços e as aspas adicionadas, conforme o exemplo acima.
O parâmetro start= auto indica a inicialização automática do serviço ao ligar a máquina.

Aplicação inicializar com Windows


Common drum rhythm index

Question: I'm looking for an index of common rhythms.  This video shows basically what I had in mind, only it is for the bass.
I'm pretty sure there has to be names and a list somewhere for the common rhythms of kick, snare, kick, snare, or kick, snare, kick kick snare etc.
Comment: I believe what you're looking for is an index of _notated drumset grooves_. As drumset is used in MANY different wide-ranging styles of music, please specify what genre you are interested in (Jazz and Rock would be two of the broader examples).
Comment: [See also](http://www.youtube.com/watch?v=dLLFFjqmRzI)
Comment: Oh, here's a pretty good site I had tucked away...
http://www.fivepinpress.com/drum_patterns.html also some free sample ones here... http://mididrumfiles.com/content/2011/02/even-more-free-files-to-download/
Answer: This site here has quite a few examples of rhythms, whether they be from well-known songs or just something to groove along to.
http://www.onlinedrummer.com/beats.php
I know I have something that was from Vic Firth which outlined about 40 or so basic rhythms from rock to jazz to latin:
Suggested by Rene Marcelo:
Try: Drumset Playalong Tracks
The one I was thinking of showed more basic grooves, but that link fits the bill nicely I think.
Comment: MIDI format would be nice, but it's also good to try and learn to read standard notation if you already can't.
Comment: I'll have to try a few of those out.  Honestly tho, I don't know why these sites don't use midi format...:/
Answer: As Zajn mentioned, Vic Firth does have an extensive education resource section. The 40 essential snare drum rudiments are probably less applicable here, but you can find 12 "Essential Grooves" plus six more in part 2. They are part of a video series with Vic Firth Artist Tommy Igoe, but the drumset notation for each basic groove is provided on the site for free.
Answer: For the sake of being comprehensive, I would like to introduce you to the 40 Snare Drum Rudiments (Wikipedia link) alluded to in previous answers by others on this page.
This link takes you to a really nice 40 Rudiments online tutorial provided by the Vic Firth drum stick company.
They are a set of exercises for snare drum alone, to learn basic patterns that are applicable in all types of Western music, and which are useful to develop rhythmic accuracy and dexterity.
The Rudiments started to be codified in the year 1612, for use by military snare drummers on the battlefield, according to the Wikipedia article referenced above. To this very day, all drummers of any and all styles of Western music who get formal training start by mastering all of these 40 rudiments on the snare drum before they go any further in learning to play drums. [I remember reading an interview with the famous hard rock drummer Tommy Aldridge who said that even though he is entirely self-taught, he started out playing drums by teaching himself the 40 rudiments on snare from a method book, and did not start adding additional drums to his kit until he had mastered playing these rudiments on solo snare.]

Common drum rhythm index


observablecollection how to add the collection to Sql Table WPF

Question: I have a ObservableCollection<Admissiontb> and i want to add this list to Sql Table.
The following code only add last record! Seeking any help and thanks in advance.
private void AddrecordToSql(object obj)
{
    AdmissiondbEntities db = new AdmissiondbEntities();

    foreach (var item in admissiontbsColl)
    {
        db.Admissiontbs.Add(item);

    }

    db.SaveChanges();

    MessageBox.Show("Done");

}

Trying to add records from the collection to the SQL table
Answer: You could try using addrange instead.
You need to call .ToList() on your observablecollection which is in the system.linq namespace ( using ).
Then you can do something like is explained here:
https://www.tektutorialshub.com/entity-framework-core/add-record-add-multiple-records-in-entity-framework/
AdmissiondbEntities db = new AdmissiondbEntities();

var addList = admissiontbsColl.ToList();
db.Admissiontbs.AddRange(addList);

db.SaveChanges();

MessageBox.Show("Done");


How to calculate the positive predictive value for a 2 x 2 table?

Question: In Why Most Published Reasearch Findings Are False the author claims that the positive predictive value (PPV) of a $2\times2$ table can be expressed as:
$PPV= (1-\beta)\cdot R / ((1-\beta)\cdot R + \alpha) \,,$
where

$\alpha$: significance level
$1-\beta$: statistical power
$R$: pre-study odds for a probed effect to reflect a true effect

However, here is an example that prooves in my opinion that this formula is wrong: Suppose, I run $1\,000$ studies with $1-\beta = 0.3$ (a), $\alpha = 0.05$ (b) and $R= 0.2$ (c). Now, (c) gives us 200 wrong null hypotheses of which by (a) 60 are correctly identified. Among the remaining 800 correct null hypotheses 40 are wrongly rejected by (b). Thus, in total 100 null hypotheses are rejected of which 60 are correctly rejected, giving a PPV of 0.6. Had I instead used the above formula, the result would have been a PPV of
$PPV= 0.3 \cdot 0.2 / (0.3 \cdot 0.2 + 0.05) = 0.06 / 0.11 = 0.55$
So, in my opinion the correct formula should read:
$PPV= (1-\beta)\cdot R / ((1-\beta)\cdot R + \textbf{(1-R)} \cdot \alpha)$
Who is wrong?
EDIT:
Kbiolsi's remark is right: Ioannidis (at least in the above paper) defines $R$ as "the ratio of the number of 'true relationships' to 'no relationsships' amonge those tested in the field." And he further explains that "[t]he pre-study probability of a relationsip being true is R/(R+1)."
However, in Power failure: why small sample size undermines the reliability of neuroscience by Ioannidis et al. the above equation for PPV (the one I claimed to be wrong) is immediately followed by: "[...] R is the pre-study odds (that is, the odds that a probed effect is indeed non-null among the effects
being probed)." Hence, Ioannidis clearly uses two differenct definitions of $R$ and (at least) in combination with this second definition the above equation is wrong.
Now, let me return to my above example. First, here is the requested contingency table:

What's the PVV in this situation? To my mind it is 0.6, which can be obtained by my above equation, assuming that $R$ is the pre-stuy odds for a probed effect to be true.
Comment: Can you write the table and explain the interpretation of the margins?
Answer: According to the original paper, R is the "ratio of the number of 'true relationships' to 'no relationships' among those tested in the field." Since it is "ratio" and not "proportion", if you have R=0.2 and have 200 true relationships, you will have 1000 (not 800) no relationships. So 50 correct null hypotheses are wrongly rejected for a total of 110 rejections, 60 of which are correct.
EDIT: I'll add to my answer to address your edit.
For the table you show, yes, PPV = 0.6. But, for this table, R=0.25 (200/800, the odds), not 0.2 (200/1000, the proportion of the total). Therefore, the computation using the Ioannidis formula is 0.3*0.25/(0.3*0.25+0.05) = 0.6, that is, the same value you get.


Loading an array with a for loop

Question: I'm trying to load a small 1D array using a for loop and for some reason I'm not getting the correct output.
int main()
{
  const int ROW = 3;
  int Table[ROW];
  for (int i = 0; i < ROW; i++)
  {
    Table[i];
  }
  for (int i = 0; i < ROW; i ++)
  {
    std::cout << Table[i] << std::endl;
  }
return 0;
}

The return I'm getting on my console is
0
0
1716919432

I would think that the output would be 0 1 2 (with the newline of course). Not sure what I'm doing wrong.
Comment: `Table[i];` - That line doesn't do anything at all.
Comment: That's what I was thinking, but I'm not sure what to do to it.
Comment: You never initialized the array, so the value of each element is garbage...
Answer: Table[i];

That line doesn't do anything at all.  I assume you meant:
Table[i] = i;

Comment: Thank you, that makes perfect sense.

Loading an array with a for loop


Deployed NextJS over Firebase but getting Error 403 Forbidden

Question: I just deployed my NextJS app over Firebase Hosting and Firebase Functions. After the deployment is successful, I went to the website but I was greeted with this page.

this is my firebase.json
{
  "hosting": {
    "public": "public",
    "ignore": ["firebase.json", "**/.*", "**/node_modules/**"],
    "rewrites": [
      {
        "source": "**",
        "function": "nextApp"
      }
    ]
  },
  "functions": {
    "source": ".",
    "predeploy": [
      "npm install",
      "npm run build"
    ],
    "runtime": "nodejs12",
    "ignore": [
      "**/tests/**",
      "**/node_modules/**",
      "jest.config.js"
    ]
  }
}

my cloud functions for nextJS
// This file is an entry point for Firebase Function to serve NextJS
const functions = require('firebase-functions');
const { default: next } = require('next');

const dev = process.env.NODE_ENV !== 'production';
const app = next({
  dev,
  conf: {
    distDir: '.next',
    future: {
      strictPostcssConfiguration: false,
      excludeDefaultMomentLocales: true,
      webpack5: false,
    },
  },
});
const handle = app.getRequestHandler();

exports.nextApp = functions.region('asia-southeast2').https.onRequest((req, res) => {
  console.log('File: ' + req.originalUrl);
  return app.prepare().then(() => handle(req, res));
});

I did check Google Cloud Console and made sure that I've added allUsers to the Cloud Function Invoker role, but it isn't helping.
Comment: Please don't post screenshots of your code, or other textual content. Instead post the actual text, and use the formatting tools of Stack Overflow to mark it up.
Answer: Sorry, silly me I've figured it out. The issue is because I'm deploying the Cloud Function to asia-southeast2 region but Firebase Hosting only able to access Cloud Functions hosted in us-central1.


Restcomm Media Player fail to paly file on S3 with error 312

Question: I have a file on AWS S3 that is public:
https://s3-eu-west-1.amazonaws.com/voxist-greetings/33631222504/33651291239_95113eed-386b-4264-a4cf-46182faae125COUCOU1.wav
Now when RVD try to play it I get:
INFO  [org.mobicents.servlet.restcomm.interpreter.VoiceInterpreter] (RestComm-akka.actor.default-dispatcher-8586) MediaGroupResponse, succeeded: false  jain.protocol.ip.mgcp.JainIPMgcpException: The IVR request failed with the following error code 312
I don't know why... The same file used to work with another name.
Thanks for any hint on how to debug this.
Comment: Hi, what version of Restcomm you run?
Comment: Version is: v7.7.0-SNAPSHOT with diversion header modification (github.com/RestComm/Restcomm-Connect/pull/1201). – karel 1 hour ago
Answer: The problem seems to happen on Media Server side. More specifically, it seems the file cannot be opened for some reason.
Relevant code line can be found here.
Can you please take a tcpdump and share it, so we can see the MGCP Play request?
Hope this helps.
UPDATE:
Here is an example:

The 200 OK simply indicates that the MGCP transaction completed successfully. Now we need to dissect the notification (NTFY) sent from Media Server to RestComm, mainly the ObservedEvents parameter.
If you look at the picture, you will see the event triggered is an OperationFailed (of) with ReturnCode (rc) equal to 312, which is an error.
Relevant link to specs can be found here.
To summarise, Media Server receives the request to play the file (in this case a cached version of it) but if fails to open the URL for some reason.
Is the URL reachable from Media Server side?
Comment: I looked at the tcpdump and I think the issue is with the cache...
I wonder if even if RVD said "Message played, path: https://s3-eu-west-1.amazonaws.com/voxist-greetings/33631222504/33651291239_76400402-1e17-4c9f-aaa5-29cbfd51b491.wav" in fact MGCP used a cache version that is corrupted (frame 131 I have: https://X.X.X.X:443/restcomm/cache/ACae6e420f425248d6a26948c17a9e2acf/4d278f0dc476656e4e3e4244957c3878d0b49b587c4706267bc71a8615dfe99b.wav it=1) ?
But still it is weird that it said success in the tcpdump but we get hangup...
Comment: which version of RestComm are you using karel?
Comment: Indeed I have a rc=312 error !
For the cache, I am not sure how it works and how Restcomm use it... In fact, I would prefer not having this cache! My RVD make a request and it should use the file provided in the request not a cached file. In case of error getting the remote file it should give an error that I can catch at =rvd level to triger another scenario.
Comment: Version is: v7.7.0-SNAPSHOT with diversion header modification (https://github.com/RestComm/Restcomm-Connect/pull/1201).
Comment: @karel I'm not sure but I believe RestComm always tries to cache files by default. If you wish to make this behaviour optional, then open a feature request on https://github.com/RestComm/Restcomm-Connect


cannot reset query row after executing while loop

Question: Hi whenever I try to reset row so that I can use same rows for a new column I get error: reset() expects parameter 1 to be array
I am new to PHP and was trying to build a table that outputs data stored in MySQL:
<?php

include ('config.php');

$user = mysqli_query($userDB, "SELECT username, email FROM user") or die(mysqli_error());

?>

      Username
      Email

    <?php while($row = mysqli_fetch_assoc($user)) echo $row["username"]."
"; reset($row); ?>

    <?php while($row = mysqli_fetch_assoc($user)) echo $row["email"]."
" ?>

Any better way I can do this?
Comment: You really want a list of usernames in a single `` and a list of emails in the other?
Comment: Why are you doing `reset()` on the username? If you want to display the list per row then you're doing it wrong.
Answer: You can rewrite in a better way:

      Username
      Email

    <?php while($row = mysqli_fetch_assoc($user)): ?>

           <?php echo $row["username"]; ?>

           <?php echo $row["email"]; ?>

    <?php endwhile; ?>

Unless you need to put all users in a single


Problem involving ideals contained in prime ideals

Question:
So far I have used the hint and have done the following:
Let $i=1,2$. Suppose that $I\subseteq P_1\cup P_2$, but that $I$ is not properly contained in $P_i$ for any $i$. Then there is an $a_i$ such that $a_i \in I\setminus P_i$. Then $a_1+a_2 \in I\setminus (P_1\cup P_2)= \emptyset$. This is not possible, so $I\subseteq P_1$ or $I\subseteq P_2$.
Now I want to extend this result for $i=n$, where $n$ is a positive integer greater than or equal to $2$. I want to try a similar approach where I let $a_j \in I\setminus \left( \displaystyle \bigcup_{i=1, i\neq j}^n P_i \right)$ so then $a_j\in P_j$, but I have absolutely no idea what to do from there. Please help me! Thank you!
Answer: Hint: One way to do this is to show that if $I\not\supset P_i$ for all $i$, then there are elements $x_1,\dots,x_n\in I$ such that for each $i$, $x_i\in P_j$ when $j\ne i$ but $x_i\not\in P_i$. Consider $\sum_i x_i$.


Lowering the drop-up menu by 10px

Question: I'm having a little positioning error and I'm sure it's a simple fix, but after trying lots of different combinations of margin and padding, I can't get it perfect. The problem is I can't seem to get my drop-up menu (footer-nav ul ul) to move down 10px when it appears by hovering over #info. If I remove the margin from the css under #info, it drops the footer-nav ul ul down 10px where I need it, but it removes the 10px margin between the black box (streaks-content) and the footer-nav. Anyone know how to fix this? I appreciate it so so much! I don't know what I would do without you geniuses!
Here is the JS Fiddle: https://jsfiddle.net/fe2zk4L8/19/
Here is the html:

PROJECTS

 ONE

 TWO

 THREE

 FOUR

INFO

    TWITTER

    INSTAGRAM

    EMAIL

Here is the css:
    a {
    text-decoration: none;
    color: inherit;
    display: block;
    }
    #header {
    width: 100%;
    position: fixed;
    background-color: #FFFFFF;
    margin: 0px;
    padding: 0px;
    top: 0;
    left: 0;
    text-align: center;
    z-index: 10;
    }
    #nav {
    width: 100%;
    background-color: #FFFFFF;
    }
    #projects {
    display: inline-block;
    padding-bottom: 10px;
    }
    #nav ul {
    font-family: Arial;
    font-size: 15px;
    font-weight: bold;
    color: #000000;
    list-style-type: none;
    text-align: center;
    margin: auto;
    padding-top: 10px;
    padding-right: 0px;
    padding-bottom: 0px;
    padding-left: 0px;
    }
    #nav ul ul {
    width: 300px;
    list-style-type: none;
    font-weight: normal;
    display: none;
    }
    #nav ul li:hover>ul {
    display: block;
    position: absolute;
    text-align: center;
    margin: 0 auto;
    left: 0;
    right: 0;
    }
    #one {
    padding-top: 10px;
    padding-bottom: 10px;
    border: 1px solid black;
    color: #000000;
    background-color: white;
    }
    #one:hover {
    background-color: black;
    color: white;
    }
    #two {
    padding-top: 10px;
    padding-bottom: 10px;
    border: 1px solid black;
    color: #000000;
    background-color: white;
    }
    #two:hover {
    background-color: black;
    color: white;
    }
    #three {
    padding-top: 10px;
    padding-bottom: 10px;
    border: 1px solid black;
    color: #000000;
    background-color: white;
    }
    #three:hover {
    background-color: black;
    color: white;
    }
    #four {
    padding-top: 10px;
    padding-bottom: 10px;
    border: 1px solid black;
    color: #000000;
    background-color: white;
    }
    #four:hover {
    background-color: black;
    color: white;
    }
    #footer {
    width: 100%;
    background-color: white;
    position: fixed;
    margin: 0px;
    bottom: 0;
    left: 0;
    text-align: center;
    z-index: 11;
    }
    #footer-nav {
    width: 100%;
    }
    #info {
    display: inline-block;
    padding-top: 10px;
    }
    #footer-nav ul {
    font-family: Arial;
    font-size: 15px;
    font-weight: bold;
    color: #000000;
    list-style-type: none;
    text-align: center;
    margin: auto;
    padding-top: 0px;
    padding-right: 0px;
    padding-bottom: 10px;
    padding-left: 0px;
    }
    #footer-nav ul ul {
    width: 300px;
    list-style-type: none;
    font-weight: normal;
    display: none;
    }
    #footer-nav ul li:hover>ul {
    display: block;
    position: absolute;
    bottom: 100%;
    text-align: center;
    margin: 0 auto;
    left: 0;
    right: 0;
    }
    #twitter {
    padding-top: 10px;
    padding-bottom: 10px;
    border: 1px solid black;
    color: #000000;
    background-color: white;
    }
    #twitter:hover {
    background-color: black;
    color: white;
    }
    #email {
    padding-top: 10px;
    padding-bottom: 10px;
    border: 1px solid black;
    color: #000000;
    background-color: white;
    }
    #email:hover {
    background-color: black;
    color: white;
    }
    #instagram {
    padding-top: 10px;
    padding-bottom: 10px;
    border: 1px solid black;
    color: #000000;
    background-color: white;
    }
    #instagram:hover {
    background-color: black;
    color: white;
    }
    #color {
    width: 100%;
    align-content: center;
    }
    #streaks-content {
    background-color: black;
    width: 300px;
    height: 1000px;
    display: block;
    margin: 0 auto;
    }

Comment: Why does it have to be 100% at #footer-nav ul li:hover>ul? Because 78% would do the work.
Comment: Why is bottom 100% at all? This is a strange way to do this.
Comment: The bottom had to be 100% to make it drop-up, rather than drop-down, is there a better way to do this?
Answer: Please add to the following CSS selector #footer-nav ul li:hover>ul that rule padding-bottom: 0;
so, in total you should have:
#footer-nav ul li:hover>ul {
    display: block;
    position: absolute;
    bottom: 100%;
    text-align: center;
    margin: 0 auto;
    left: 0;
    right: 0;
    padding-bottom: 0;
}

Comment: This worked perfectly! Such a simple fix, thank you so much!

Lowering the drop-up menu by 10px


Erro em query com WHERE E COUNT no Oracle. "SQL command not properly ended"

Question: Tenho a seguinte query:
INSERT INTO TB_CLASSIFICACAO_UG
    (COD_CLASSIFICACAO_UG, TXT_DESCRICAO, IND_ATIVO)
VALUES
    (SEQ_COD_TB_CLASSIFICACAO_UG.nextval, 'TESTANDO', 1)
WHERE
    (SELECT COUNT(TXT_DESCRICAO) FROM TB_CLASSIFICACAO_UG WHERE TXT_DESCRICAO = 'TESTANDO') = 0

Essa query gera o erro:
"SQL command not properly ended"

Porém se eu rodar somente a primeira parte ela funciona.
INSERT INTO TB_CLASSIFICACAO_UG
    (COD_CLASSIFICACAO_UG, TXT_DESCRICAO, IND_ATIVO)
VALUES
    (SEQ_COD_TB_CLASSIFICACAO_UG.nextval, 'TESTANDO', 1)

E se eu rodar a segunda parte também.
(SELECT COUNT(TXT_DESCRICAO) FROM TB_CLASSIFICACAO_UG WHERE TXT_DESCRICAO = 'TESTANDO') = 0

O que será que estou fazendo de errado?
O que eu quero no final das contas é tipo um INSERT IF NOT EXISTS. Alguma sugestão de query? Já tentei de outras formas além dessa e não funcionou.
Answer: O comando INSERT (SQL ANSI) não aceita a clausula WHERE, essa necessidade de inserir apenas caso não exista é relativamente comum mas sua implementação muda conforme o banco, uma abordagem que recomendo é verificar isso no código da sua aplicação de forma que a lógica fique mais clara.
Caso você opte por fazer tudo no SQL ainda é possível, da seguinte maneira(no oracle):
begin
  insert into TB_CLASSIFICACAO_UG
         (COD_CLASSIFICACAO_UG, TXT_DESCRICAO, IND_ATIVO)
  values (SEQ_COD_TB_CLASSIFICACAO_UG.nextval, 'TESTANDO', 1)
  ;
  commit;
exception
  when DUP_VAL_ON_INDEX
  then ROLLBACK;
end;

Comment: O que é esse DUP_VAL_ON_INDEX
Comment: É um tipo de exceção que o Oracle lança quando há duplicidade do índice (Duplication of value on index)
Comment: Mas como ele sabe que o índice é o TXT_DESCRICAO?
Comment: Imaginei que já que você pretende evitar a duplicação de um determinado campo você poderia ter adicionado um índice a ele, isso não é necessariamente verdade mas pode ser interessante especialmente se você pretende fazer essa verificação com frequência
Answer: Tente inverter a ordem de sua query para algo semelhante ao seguinte:
INSERT INTO TB_CLASSIFICACAO_UG
    (SELECT COD_CLASSIFICACAO_UG, TXT_DESCRICAO, IND_ATIVO FROM TB_CLASSIFICACAO_UG WHERE TXT_DESCRICAO <> 'TESTANDO')
VALUES
(SEQ_COD_TB_CLASSIFICACAO_UG.nextval, 'TESTANDO', 1)

Answer: Para a inserção condicional no Oracle você pode utilizar a cláusula MERGE
MERGE
   INTO  TB_CLASSIFICACAO_UG
   USING (SELECT COUNT(TXT_DESCRICAO) AS count FROM TB_CLASSIFICACAO_UG WHERE TXT_DESCRICAO = 'TESTANDO') s
     ON   (s.count > 0)
 WHEN NOT MATCHED THEN
     INSERT (COD_CLASSIFICACAO_UG, TXT_DESCRICAO, IND_ATIVO)
     VALUES (SEQ_COD_TB_CLASSIFICACAO_UG.nextval, 'TESTANDO', 1);

Teste no SQLFiddle: http://sqlfiddle.com/#!4/3944a4/2
Answer: Para que um registro seja inserido somente se ainda não existir, os bancos de dados possuem restrições de chave única.
No seu exemplo, basta transformar o campo TXT_DESCRICAO em uma chave única utilizando o comando:
ALTER TABLE TB_CLASSIFICACAO_UG
ADD CONSTRAINT TB_CLASSIF_TXT UNIQUE (TXT_DESCRICAO);

Desta forma, qualquer rotina ou query será impedida de inserir um valor para TXT_DESCRICAO que já exista na tabela.
Answer: Consegui chegar a uma solução para o meu problema:
INSERT INTO TB_CLASSIFICACAO_UG
    (COD_CLASSIFICACAO_UG, TXT_DESCRICAO, IND_ATIVO)
VALUES
    (SEQ_COD_TB_CLASSIFICACAO_UG.nextval, (SELECT '" + descricao + "' FROM dual WHERE NOT EXISTS (SELECT NULL FROM TB_CLASSIFICACAO_UG WHERE TXT_DESCRICAO = '" + descricao + "')) , 1);


EntityReference attribute is not always completely populated

Question: Here's a LINQ to CRM query:
Contact crmContact = xrm.ContactSet.Where(x => x.ContactId == contactId).SingleOrDefault();

I've got an attribute, an EntityReference, as such:
crmContact.assigned_clinic;

As you know, an EntityReference contains these attributes:
- Id (the Guid of the entity that it refers to)
- LogicalName (what type of entity does this reference references to)
- Name (the 'Name' attribute of the entity that's being refered to)

For some reasons I cannot put my finger on, in certain circumstances, the LogicalName and Name attributes are populated correctly, sometimes, they are empty strings.
Any ideas to force a complete retrieval of that data ?
Answer: Well, that was not long. I thought SingleOrDefault() retrieved everything, but apparently, you need to call ToList() for that to happen. I changed the query to:
Contact crmContact = xrm.ContactSet.Where(x => x.ContactId == contactId).ToList().SingleOrDefault();

And now all EntityReference attributes are being populated correctly. Sometimes I was doing so, sometimes not which explains the "not always completely populated" mystery.
Answer: The technical reason is written on MSDN:
EntityReference.Name Property

This property can contain a value or null. This property is not
  automatically populated unless the EntityReference object has been
  retrieved from the server.


How can I run Openstack devstack in my ASUS chromebook?

Question: I use crouton to host a Ubuntu 14.04 LTS os on my chromebook and I am trying to use the devstack of the openstack. However, when I run ./stack.sh, I got error message saying:
<code>df: '/mnt/stateful_partition': No such file or directory
df: '/usr/share/oem': No such file or directory
df: '/home/chronos': No such file or directory
df: '/home/.shadow/8ffdc7dfab0156490faeb957f20259a78406cdfa/mount': No such file or directory
df: '/home/chronos/user': No such file or directory
df: '/home/user/8ffdc7dfab0156490faeb957f20259a78406cdfa': No such file or directory
df: '/home/chronos/u-8ffdc7dfab0156490faeb957f20259a78406cdfa': No such file or directory
df: '/home/root/8ffdc7dfab0156490faeb957f20259a78406cdfa': No such file or directory
df: '/run/crw': No such file or directory
+ exit 1
</code>
Any help would be really appreciated!

I tried run the script as a root and it doesn't work either
Comment: OpenStack is designed to be run as a non-root user; Horizon will fail to run
# as **root** since Apache will not serve content from **root** user).
# ``stack.sh`` must not be run as **root**. It aborts and suggests one course of
# action to create a suitable user account.
Answer: I feel this to be as SD card issue. Did you install ubuntu directly on your Chromebook SSD/SD??
The chances of this being openstack issue seems low.
Comment: I don't think I did. I am using crouton to host ubuntu and I don't think it writes that in my SSD/SD. So it would be an issue of crouton right?


Domain redirect in .htaccess causing SSL "Your connection is not private," but works OK on non-https://

Question: I've been banging my head trying to resolve this. Here is the problem and what I've done so far:
(1) I have domain: domain-one.com
(2) domain-one.com forwards to domain-two.com by .htaccess code below
############################
Redirect To Other Domain
############################
Options +SymLinksIfOwnerMatch
RewriteEngine on
RewriteRule (.*) http://www.domain-two.com/$1 [R=301,L]
(3) When attempting to access http://domain-one.com all is OK, forwards properly to domain-two.com, but
(4) When attempting to access https://domain-one.com, I receive SSL error "Your connection is not private" (this is Chrome's message)
The main problem I am facing is how can the https:// also forward from domain-one.com to domain-two.com without causing the "Your connection is not private." invalid SSL issue.
(5) Here is a breakdown of what is working and what is not with the .htaccess forwarder:
5.a FAIL: https://www.domain-one.com/ -> domain-two.com, "Your connection is not private."
5.b FAIL: https://domain-one.com/ -> domain-two.com, "Your connection is not private."
5.c PASS: http://www.domain-one.com/ -> domain-two.com
5.c PASS: http://domain-one.com/ -> domain-two.com
Excuse me for my ignorance and confusion on this. Thank you in advance for any tips on this problem. I am happy to provide any further clarifications needed, but I was trying to keep the post short.
Comment: You need to get SSL certificates with those hostnames. Then you have to configure Apache to use them.
Comment: Also, don't use `domain-one.com` because you don't own it. Use `one.example.com` instead, it is explicitly reserved for this purpose by [IANA](https://www.iana.org/domains/reserved)
Answer: I solved the problem, and wanted to clarify a few points:
(1) digijay, I own both domain names, and have access to them on the domain host. The domain host is separate from the hosting/email server, that is why we are needing to use this redirect to stall the production of an email migration.
(2) Michael Hampton, thank you for the tip. I was able to enable Let's Encrypt on the domain-one.com account, and the redirect now works when accessing https://domain-one.com, no security errors.
Let's Encrypt was the solution.


Spring Data JPA and Projection getting ConverterNotFoundException for TupleConverter

Question: Is there a way to write and register a TupleConverter converter in Spring Data? I'm getting this exception when I have an @Query annotation in the Repository interface and asking for Projection.
The Interface:
public interface ProjectRepository extends JpaRepository<Project, Integer> {
    @Query("select p.projectId, p.projectName, p.techstack from Project p")
    public List<ProjectItem> findAllForTest();
}

The DTO:
public class ProjectItem {
    private final Integer projectId;
    private final String projectName;
    private final String techstack;
    @JsonCreator
    public ProjectItem(
        @JsonProperty("projectId") Integer projectId,
        @JsonProperty("projectName") String projectName,
        @JsonProperty("techstack") String techstack
    ) {
        this.projectId = projectId;
        this.projectName = projectName;
        this.techstack = techstack;
    }
    public Integer getProjectId() {
        return projectId;
    }
    public String getProjectName() {
        return projectName;
    }
    public String getTechstack() {
        return techstack;
    }
}

The exception

No converter found capable of converting from type [org.springframework.data.jpa.repository.query.AbstractJpaQuery$TupleConverter$TupleBackedMap] to type [project.item.ProjectItem]] with root cause
Answer: Use a JPQL Constructor Expression:
@Query("select new com.company.path.to.ProjectItem(p.projectId, p.projectName, p.techstack) from Project p")

Comment: This works even with the `Feign Client` though I have to specify the attributes which is not pretty.
Answer: You're close. If you just want a DTO with a few of the items from the original item, just use the interface projection technique with methods having the same signatures as the Project class method items you want:
public interface ProjectTestSummary {
    public Integer getProjectId();
    public String getProjectName();
    public String getTechstack();
}

And in your DAO:
public interface ProjectRepository extends JpaRepository<Project, Integer> {
    public List<ProjectTestSummary> findAllProjectedBy();
}

Comment: This works until I try to use the `FeignClient` and then there is no way for Feign to decode the interface version. "feign.codec.DecodeException: Type definition error: [simple type, class project.item.ProjectSummary]; nested exception is com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `project.item.ProjectSummary` (no Creators, like default construct, exist): abstract types either need to be mapped to concrete types, have custom deserializer, or contain additional type information" PS> Thanks for double answer!
Comment: Oh! Interesting use case. I would make clear what your trying to accomplish with Feign in your question, otherwise SO solutions will just  be tackling the projection issue in their answers.
Comment: But writing test case for this is difficult


how I can get The last time the file is opened in php

Question: How can I get the last time the file was opened in PHP?
Can anyone help me?
I just found the stat() function but this just returns time of last modification but I need last time the file was opened.
Comment: surely you can Google that
Comment: Last time its opened is impossible, as this is not recorded. Possibly you could process the Apache access log to find the last time it was requested by someone, but that wont help you with any non web server access
Comment: Provide some more sample code, add some more details to your question so that we would be more willing to help you.
Answer: You can use the function fileatime().
The following example:
<?php
    $filename = "/Users/rafaelalmeida/projects/UFP-API/README.md";

    if (file_exists($filename)) {
        echo "$filename was last accessed: " . date("F d Y H:i:s.", fileatime($filename));
    }

The result from the code above is: /Users/rafaelalmeida/projects/UFP-API/README.md was last accessed: February 17 2017 00:29:20..
You can read more about fileatime() function here.
Comment: Well... this might not really do what the OP wants, since it checks the file, then lists the access, which will be when it was checked - ie, always return the current time. If you want to be able to see when the file was LAST accessed, you will need to always log this to a database or file, then pull the last entry in the file/database.
Comment: @junkfoodjunkie actually no. I've changed to another file and the output I get is `/Users/rafaelalmeida/projects/UFP-API/phpunit.xml was last accessed: February 09 2017 20:06:18.`
Comment: @rafaelcpalmeida Are you responsible for every access? If so, you might want to look into the [touch](http://php.net/touch) function. **Edit:** Woops, I thought you were OP for a minute. Regardless, touch updates the access time.
Comment: @thordarson it happens :) I guess that the `touch` function doesn't solve the OP problem because, from what I read, he wants to get the last time that a given file was access


Script for renaming files - removing dash chars from Android resource files

Question: The following scripts finds all files in the current directory (recursively) and replaces dash - characters to underscore chars in file names
find . -type f -name '*.png' | while read FILE ; do
    newfile="$(echo ${FILE} |sed -e 's/-/_/g')";
    mv "${FILE}" "${newfile}" ;
done

given a file in the path that contains dashes, for example, drawable-hdpi/file-name.png, the script will try to rename it to drawable_hdpi/file_name.png - replacing the dash in the directory name as well as in the file name.
I would like to avoid modifying the directory path, and only rewrite the file name.
Any suggestions on how to modify the sed usage to skip the directory path?
Comment: it is a good practice to use lower case variable names to avoid potential conflict with environment variables... and see https://unix.stackexchange.com/questions/321697/why-is-looping-over-finds-output-bad-practice
Comment: depending on your `find` version and availability of perl based `rename` command, you could do `find . -type f -name '*.png' -exec rename -n 's|[^/]+$|$&=~s/-/_/gr|e' {} +` and remove the dry run `-n` option once you see that command works as intended
Comment: @Sundeep running on osx, which does not come with rename so I'm dependent on mv
Comment: then I would suggest `find . -type f -name '*.png' -exec bash -c 'd=$(dirname "$0"); f=$(basename "$0"); echo mv "$0" "$d/${f//-/_}"' {} \;` instead of using find+while
Comment: @Sundeep looks good :)
Answer: The shell has some nifty string operators to chop parts of variables. Your shell manual page has all the details. Here's how I would use them:
find . -type f -name '*.png' |
while read FILE; do
    dir=${FILE%/*}
    newfile=$(echo "${FILE##*/}" |sed -e 's/-/_/g')
    mv "${FILE}" "${dir}/${newfile}"
done

Explanation:
dir=${FILE%/*} chops the shortest part from the right that matches the /* glob, removing the slash and file name, giving the directory.
${FILE##*/} removes the longest part from the left matching */, i.e. leaves just the file name.


Views e variáveis de sessão disponível em sub domínios

Question: Estou a criar um sistema web em laravel onde serão criados vários sub-domínios para localizar alguns serviços para os usuários. Ex. painel.dominio.com , loja.dominio.com, etc.
Minha dúvida são:

Minhas variáveis criadas na sessão do domínio principal estarão
acessíveis a todos os sub domínios ?
Existe a possibilidade de gerenciar toda a aplicação no domínio
principal fornecendo as views através de rotas para os sub domínios ?
Answer: Não é possível compartilhar a sessão nativa do PHP pois são domínios diferentes. Neste caso você terá que utilizar um controle de sessão via Banco de Dados ou outra fonte de dados que seja acessível de modo comum entre todos domínios (principal + subdomínios) e levar a autenticação de um domínio para outro através de variáveis atreladas a requisição HTTP, seja via GET, POST ou HEADER.
Um sistema de Token também irá te ajudar nisto. Onde cada sessão criada por um usuário você gera um token, que ficará armazenado nesta fonte de dado comum, e quando você levar o usuário para outro domínio, você anexa esse token a requisição, conforme informado acima, e faz a validação do token na requisição recebida no novo domínio.


During an interactive rebase, how do you restart the current merge conflict without aborting the entire rebase?

Question: I'm working on an interactive rebase. I've --continued 3 times, but confused myself on this current merge conflict and want to start over. How do I restart this merge conflict without losing all my previous work?
I've annotated what git status says:
interactive rebase in progress; onto 44444
Last commands done (2 commands done):
   pick 3333333 My edits
   pick 2222222 Removed some gibberish
Next commands to do (8 remaining commands):
   pick 1111111 Personal changes
   # not sure what this is, but what little research I've done makes it seem irrelevant
  (use "git rebase --edit-todo" to view and edit)
You are currently rebasing branch 'branch' on '44444'.
  (fix conflicts and then run "git rebase --continue")
  # I don't want to skip, I want to restart
  (use "git rebase --skip" to skip this patch)
  # I don't want to go all the way back to the beginning, I only want to restart the 44444 merge conflict.
  (use "git rebase --abort" to check out the original branch)

Unmerged paths:
  # this didn't revert my merge conflict changes
  (use "git restore --staged <file>..." to unstage)
  (use "git add <file>..." to mark resolution)
        both modified:   file.py

After git restore --staged, I tried again without the --stage. Now it says nothing to commit, working tree clean.
How do I reset only this merge conflict?
Comment: @mkrieger1 tbh, I'm not sure. This potential dupe is about `merge`. Does it apply to `rebase`?
Comment: @mkrieger1 okay I tried `git checkout -m -- file.txt` from one of those answers and it did what I want. Thanks
Answer: I'm not sure if this is a straight up duplicate or a different question with the same answer, but doing this to the file put the commit back into its original merge conflicted state:
git checkout -m -- file.txt

Here's the official documentation on checkout -m:

  -m, --merge

When switching branches, if you have local modifications to one or more files that are different between the current branch and the branch to which you are switching, the command refuses to switch branches in order to preserve your modifications in context. However, with this option, a three-way merge between the current branch, your working tree contents, and the new branch is done, and you will be on the new branch.
When a merge conflict happens, the index entries for conflicting paths are left unmerged, and you need to resolve the conflicts and mark the resolved paths with git add (or git rm if the merge should result in deletion of the path).
When checking out paths from the index, this option lets you recreate the conflicted merge in the specified paths.
When switching branches with --merge, staged changes may be lost.

You can do this to revert all files at once:
git checkout -m -- .


Unix shell script with query is not generating data for query with where clause but without where clause it is generating data for postgres metadata

Question: I have used Postgres query in shell script to execute and get some result and load to file.
The query is using where clause in which date column is used for postgres database.
Without where clause it is generaing data but with where clause in query it is not generating data.Below is the sample query for reference.
psql -h host -p port -U username -w -d databasename -Atc
"with A as(  select max(col1) as max_inst_id,col2,col3,col4 from
sch_task_Inst where col5 > timestamp '2018-05-05 02:00:00 - interval
'1 hours'  group by col1,col2,col3,col4  )
select b.col1 as task_nm,A.col1 as run_status,A.col2 as run_log from
A join sch_task b on A.col1 = b.col1  where A.col2 = 'FAI' ;" >>
/app/ditechstyle/diserver/app/source/Sch_test.dat

Can some one tell me what is the problem with the query where clause?
Comment: Looks OK. Maybe there just are no data that satisfy the condition? If you add some sample data to the question, that might help to clarify the problem.
Comment: What has it got to do with shell script? If the query with `where` clause is wrong or there's no data, obviously it won't work. Check first if the query runs fine from psql prompt.
Answer: Your problem is that you are missing a single apostrophe after your timestamp. You should have timestamp '2018-05-05 02:00:00' - interval '1 hours', but what you actually have is timestamp '2018-05-05 02:00:00 - interval '1 hours'. Note the apostrophe after the 02:00:00. See examples at this page on PostgreSQL dates and timestamps.
Comment: My bad i sent incorrect format but actually gave it properly as timestamp '2018-05-05 02:00:00' - interval '1 hours' in the query,still i see the same issue.
Comment: Data is coming into filename as Sch_max_failurejob.dat? but not coming to actual file Sch_max_failurejob.dat.
Comment: Try setting the interval to `'1 hour'` instead of `'1 hours'`. Does that work?