Possible display options in Drupal views

Question: I am a newbie into Drupal 7.
I am learning D7 views. I exported a view and found :
<code>$handler->display->display_options['access']['type'] = 'perm';
</code>
with no permission array to specify the user group who can access this view.
Which user group does it take by default?
Also, in my custom view in code I have replaced it with following:
<code>$handler->display->display_options ['access']['type'] = 'role';
$handler->display->display_options['access']['role'] = array(
    3 => '3',
);
</code>
It is working fine. I want to know all possible values of $handler->display->display_options this array. Where can I find all these options? Is there any documentation available for this?
Answer: Restrictions to access view can be set through Views UI to "role", "permission" or "none". See this page in Views documentation.
As for "role", those are IDs of different roles on your website. You can find those IDs in adiministration admin/people/permissions/roles - just hower over role edit link, number is in its URL.
Comment: It just gives options for $handler->display->display_options['access']['type'], I want to have a look at all of them. Is there any doc available for this?


Does high variance and high bias mean that it is both underfitted and overfitted?

Question: I know that high bias and low variance implies underfitting, while high variance and low bias implies overfitting.
But what if both bias and variance are high?
Does this mean that the model is underfit and overfit at the same time? Or is it neither overfit nor underfit?
Answer: It's not typical to have high degrees of both, but if it happens it's neither overfitting nor underfitting because these are defined with contrasting amounts of bias and variance. An overfitting model performs very well on the dataset it learns. So, it has low bias by definition. An underfitting model doesn't properly fit the data, which means it isn't very sensitive to the changes in the features, so having low variance.
Artificially, you can take an overfitted model, add an effective constant amount to its output and create a high bias and variance case, but I haven't encountered this case naturally before.


Eulerian paths in non-traversable graphs

Question: Suppose I have a weighted connected graph which is traversable (each vertex has even degree) and I wish to walk over all edges. Clearly any Eulerian path minimizes the total weight. What can be said about the case of non-traversable (weighted connected) graphs? Can a minimum-weight path still be found in polynomial time?
Comment: This is the Route inspection problem a.k.a. Chinese Postman Problem. This has a polynomial time algorithm for undirected graphs and polynomial for directed graphs, but it is NP-complete for mixed graphs.
Comment: You want a path that traverses every edge _at least_ once, I suppose?
Comment: @HenningMakholm: Yes. Sorry, I had typed that but it must have been deleted as I edited the post before submitting.
Comment: I would be surprised if it had an efficient solution. It is a variant of the travelling purchaser problem (on the line graph) but with some simplifications (like travel cost zero) and only one product.
Answer: Yes, this can be done in polynomial time.
What we need to is find a minimum-weight set of edges to traverse twice, such that the graph with some edges doubled is traversable. Once we have that, finding an actual Eulerian path is of course easy.
The edges we need to double will form a set of paths each connecting two odd-degree nodes, such that each odd-degree node is the endpoint of exactly one of the path.
To find out which odd-degree nodes to connect, temporarily disregard the even-degree nodes and instead consider a graph with one edge between each pair of odd-degree nodes, its weight being the length of the shortest path between those nodes in the original graph.
What we need to find is then a minimal perfect matching in the reduced graph, which is known to have a polynomial-time algorithm.


Laravel Blade Comment causes CONNECTION_RESET

Question: In a Laravel 4.2 app, I have this view file:
{{--

--}}

making this view causes a crash in the browser.
I don't know which part causes this, sometimes removing a single space resolves the problem.
There are similar questions but there was some blade commands within blade comments that caused it, here I have the same problem with pure HTML
EDIT:
Copy/pasting above code resolves the problem! please copy from this gist https://gist.githubusercontent.com/anonymous/ad0da06d727e9973ca9e/raw/8d38ad3b416e920a0f1b9b8a42385ae56f25dc20/gistfile1.txt
Answer: This happened with laravel 5 as well. I fixed this by converting to php comment, ie replace
`{{--` with  `<?php /*`

and
`--}}` with  `*/ ?>`


Continuous linear functionals

Question: Let L be a continuous  linear functional on a metric linear space X. Prove:  L(S) is a bounded set for any bounded subset S of X. The metric is translation invariant.
Comment: How do you mean *linear* on a *metric space*?
Comment: Is the metric compatible with the linear structure, that is do you assume that the addition and scalar multiplication are continuous functions?
Comment: @Berci: no, it's not the same. In your example $(\mathbb{R},d')$ the entire line is bounded with respect to the metric, but it is *not* absorbed by *every* neighborhood of zero. There is no scalar $\lambda$ such that $\mathbb{R} \subseteq \lambda B$, where $B$ is the ball of radius $1/2$.
Comment: Presumably you mean on a vector space with a metric?
Comment: I corrected the question. It now reads "...metric linear space" instead of "metric space"
Comment: Yes. I think that is the definition of a metric linear space.
Comment: I suppose *bounded* means *bounded in the [topological vector space sense](http://en.wikipedia.org/wiki/Bounded_set_(topological_vector_space))*, right?
Comment: Isn't it the same? Neighborhoods are built up by balls.
Answer: Note that this is true in general for $L:X\rightarrow Y$ linear continuous between two metric linear spaces.
Hints:

fix an open ball centered at $0$ (the one of radius $1$ for instance)
use continuity at $0$.
prove that $L$ is bounded on some open ball $B$ centered at $0$.
use that for every bounded set $S$, there is $\rho>0$ such that $S\subset \rho B$.
Comment: @mas In the view of Martin and Berci comments, I think you should clarify what you mean by *bounded*.
Comment: Taking the last bullet as given the proof is very easy. So, how do you show the last bullet?
Answer: Consider the inverse image of any bounded open neighborhood $W$ of $0$ in the target space (let it be $\Bbb R$ or $\Bbb C$ or anything). Its preimage, $L^{-1}(W)$ is an open neighborhood of $0\in X$, so it contains a ball $B(\varepsilon)$ around $0$ with radius some $\ \varepsilon >0$. Let us fix this $\varepsilon$.
Now, if we have any bounded set $S\subseteq X$, then there exists a ball that contains it, say with radius $r_0>0$ and midpoint $Q$, then  $\ S\subseteq B(r)\ $ where $\ r=r_0+d(0,Q)$.
Now imagine the continuous mappings $f_\lambda:X\to X,\ \ v\mapsto \lambda\cdot v$. If $\lambda\neq 0$,  it is a homeomorphism, mapping any ball $B(\rho)$ (around $0$) to an open set, which also contains a ball around $0$, say with radius $f(\lambda,\rho)>0$. So that $B(\lambda\cdot\rho)=f_\lambda(B(\rho))\supseteq B(f(\lambda,\rho))$...
Then,  $L(S)\subseteq L(B(r))= L(f_{\frac r\varepsilon}( B(\varepsilon))) \subseteq f(\displaystyle\frac r\varepsilon)\cdot  W $, bounded.

Update: Hmm, in this generality it is not true. Let $X=\Bbb R$ with a bounded metric, for example $d'(x,y):=\displaystyle\frac{d(x,y)}{1+d(x,y)} <1$, and let $L$ be the identity $X\to\Bbb R$. Then the whole $X$ is bounded, but its image is not bounded.
Comment: I think there is a confusion between two largely unrelated notions of "bounded": bounded with respect to the metric and [bounded in the topological vector space sense](http://en.wikipedia.org/wiki/Bounded_set_(topological_vector_space)). For bounded sets in the second sense the assertion is true, but, as you observe, not for bounded sets in the first sense. // Your metric $d'$ is translation invariant, but it isn't homogeneous.
Comment: Why is $B(r)=\frac{r}{\epsilon}B(\epsilon)$? You have to have some extra assumptions about the metric, I think.
Comment: Exactly. You cannot assume that. You only know that you are in a metric linear space, and you cannot assume d(ax,0)=ad(x,0).
Comment: Aha.. a bit unusual to me, I am going to think it over..
Comment: I started to prove, then got to the point to see that it is not true. Also added counterexample.
Comment: Ok, then it's a hint, probably this new condition  of translation invariance implies surjectivity of $f(\lambda,\rho)$, and then one can prove that scalar multiplications preserve *bounded* sets, that is the missing point.
Comment: Just to let you know, I do not have a proof for it. The metric in the counter example is not invariant.
Comment: Hey wait, if it is translation invariant, it also means that $d(0,n\cdot x)\le n\cdot d(0,x)$ for all $x$, no? But then you can use the earlier reasonging with the upper integer part of $\frac r\varepsilon$ or something like that.

Continuous linear functionals


how to make linux cdrom mounting/unmounting show up in syslog

Question: I'd like a record of every time the cdrom drive is mounted.  Ideally this would be in syslog. The system is CentOS 5.5 linux.
Answer: While mounting a device, the mount command will issue an open system call. Thus, one approach is to use linux's audit subysystem to log reads on the cdrom device. First, you need to get it enabled.
yum install audit
chkconfig auditd on
service auditd start
auditctl -e 1

Now you need to figure out your cdrom device and add the rule to log reads.
readlink -f /dev/cdrom
auditctl -w /dev/sr0 -p r

Now if I have a shell with my working directory of /var/log and I run
mount /dev/sr0

Afterwards there will be three related lines in /var/log/audit/audit.log

type=SYSCALL
  msg=audit(1301280283.689:15549):
  arch=c000003e syscall=2 success=yes
  exit=3 a0=7f0d3af92820 a1=0 a2=0 a3=1
  items=1 ppid=14660 pid=14661 auid=500
  uid=0 gid=0 euid=0 suid=0 fsuid=0
  egid=0 sgid=0 fsgid=0 tty=pts4 ses=231
  comm="mount" exe="/bin/mount"
  key=(null)
type=CWD
  msg=audit(1301280283.689:15549):
  cwd="/var/log"
type=PATH
  msg=audit(1301280283.689:15549):
  item=0 name="/dev/sr0" inode=5821
  dev=00:05 mode=060660 ouid=0 ogid=11
  rdev=0b:00

This approach isn't a good idea if there are other processes the regularly read the cdrom device. On a Fedora 14 system, the udisks-daemon seems to poll it every second. However, on a CentOS 5.5 system, there doesn't seem to be anything accessing it.
Comment: This works pretty well at getting the event logged to a file, but I was really hoping to be able to send it to syslog.


spring reactive: check if user exists or not

Question: I am using spring reactive and need to check weather user with particular
data exists or not and currently I am not able to solve that problem.
Considering the scenerio
In my document I need to check if username or email already exists or not
In RDBS I can do it as
select count(id)>0 where username='abc' or email@example.com'
while using spring reactive which returns either mono or flux the simple most query becomes
{$or:[{"username":"abc"},{"email":"email@example.com"}]} which will return flux but I need boolean to verify from db
On solution is that I can get Flux<User> and the iterate it using form loop but then using ' result.block()' whick will block some other threads and therefore not a clean solution.
Is there any clean solution or any Idea how to solve this.
Thanks
Edit One possible solution can be creating unique indexing in monogdb, that I am using right now. But if there is any other solution please let me know
Answer: Using Spring Data MongoDB, you can use something like below:
public interface ReactiveUserRepository extends ReactiveSortingRepository<User, Long> {
     Mono<User> findByUsernameAndEmail(String username, String email);
}

Find a single entity for the given criteria. It completes with IncorrectResultSizeDataAccessException on non-unique results.

You can refer to the complete syntax here:
https://docs.spring.io/spring-data/mongodb/docs/current/reference/html/


Can't create Hello World in Eclipse (Mac), Building error (NullPointerException)

Question: I installed Java & Eclipse and wanted to run the tutorial of the Hello World project.
As soon as I start with the first real step, creating a Java Project, I do everything alike the Tutorial, write the name "HelloWorld", finish.
Then a Window pops up, that wants me to create a new module-info.java. That is pretty strange, I have not seen anything like this in a Tutorial anywhere, but either way, if I create it or not, I get an error:
Errors occurred during the build.
Errors running builder 'Java Builder' on project 'HiWorld'.
java.lang.NullPointerException
Does anyone know something about this issue?
I have already tried to look in the Properties - Building Path, but when I add, remove, change something I do not get anywhere.
I had the idea that it could be a problem with my eclipse, but I reinstalled it twice already (Java as well) and I have not made any progress.
My code is just:
module helloworld {
}

I want to eliminate the error, so that later on my HelloWorld program is running.
Thank you for taking some time!
Comment: Thank you very much, I will try this!
Comment: I am sorry for asking, but you do not mean the compliance level? Because I have the opportunity between 11,10,9 and then 1.8
Comment: If I do go to 1.8 for example, I get the error, that no JRE is installed in this workspace. Do I have to install this JRE?
Answer: You don't mention the tutorial, but I imagine it's for below Java 9, of which module-info is part.
Go into Eclipse project settings and set language level to 8 (there's plenty of guides online) and you should be good.
Edit: If, however, the tutorial is for Java 9, I'd really recommend finding another tutorial as the module stuff is a whole set of extra complication which you don't need right away (I've yet to see Java 9 used in the real world)
Comment: do you have a link for such a tutorial? I can online find those that modify the compliance level.
Comment: @cruiser0223 there are so many. thenewboston on youtube is good


Connecting Web App to new VPN in Azure

Question: Is it possible to connect a Web App to a 'Virtual network' (not a 'Virtual network (classic)') in Azure - and if so how.
I virtual network, with a virtual network gateway connected but there does not seem to be any way to configure a point-to-site connection, and my network does not show up under the web app network configuration.
Note: this is through the new portal.azure.com as opposed to manage.azure.com
Thanks
Answer: Point-to-site connections are not currently available in the Azure Resource Manager. You'll need to use classic networking until it's available.
You can connect a classic virtual network and virtual network with a site-to-site VPN

Connecting Web App to new VPN in Azure


Primitive root, if and only if condition.

Question: What is the easiest way to see that $a \not\equiv 0, 1 \text{ (mod }p\text{)}$ is a primitive root mod odd $p$ if and only if for all $q$ such that $q|(p-1)$, we have$$a^{{p-1}\over{q}} \not\equiv 1 \text{ (mod }p\text{)}?$$
Answer: Recall that the order of $a$ modulo $p$ is defined as the least $k$ such that $a^k \equiv 1 \pmod{p}$.
Recall also that $a$ is a primitive root modulo $p$ precisely when the order of $a$ modulo $p$ is $p-1$.
We know from Fermat's Little Theorem that $a^{p-1} \equiv 1 \pmod{p}$.
Thus, the order of $a$ modulo $p$ divides $p-1$. Let's call this order $k$.
So we know that $k \mid p-1$. Can you show that, given this, we have $k < p-1$ if, and only if, $k \mid \frac{p-1}{q}$ for some prime divisor $q$ of $p-1$?

 $k \mid p-1$ means that there exists $m$ with $mk = p-1$.

 $k < p-1$ precisely when $m > 1$.

 But then $m$ must have some prime factor $q$.

 This means that $\frac{m}{q} k = \frac{p-1}{q}$, in other words that $k \mid \frac{p-1}{q}$


UseEffect not firing (NextJS) - CKEditor

Question: I am trying to integrate CKEditor in my NextJS App and have the following code for the editor component (this solution was found in another SO post but is not working for me). The likely reason seems to be that UseEffect is not firing. When I do a console log inside UseEffect I cannot see anything in the console.
import React, { useState, useEffect, useRef } from 'react';
import styles from '../../styles/components/WriteBlog.module.scss';

const WriteBlog = () => {
  const [content, setContent] = useState('');
  const [editorLoaded, setEditorLoaded] = useState(false);
  const editorRef = useRef();
  const { CKEditor, ClassicEditor } = editorRef.current || {};

  useEffect(() => {
    editorRef.current = {
      CKEditor: require('@ckeditor/ckeditor5-react').CKEditor,
      ClassicEditor: require('@ckeditor/ckeditor5-build-classic'),
    };
    setEditorLoaded(true);
    console.log('useEffect ran!');
  }, []);

  return editorLoaded ? (

Create New Post

        <CKEditor
          editor={ClassicEditor}
          data={content}
          onChange={(event, editor) => {
            const data = editor.getData();
            setContent(data);
          }}
        />

  ) : (

Loading Editor...

  );
};

export default WriteBlog;

I just get a "Loading Editor..." screen that I have defined in the return statement.
I am importing the modules correctly as per the latest CKE documentation.
Why is the editor not loading / UseEffect not firing?
Answer: This worked when I moved the code to the 'pages' folder of the application from the 'components' folder. Originally I was trying to import the editor as a component from components/blog/WriteBlog.jsx into the pages/blog/new/index.js file.
I have no clue why this solution works though. It seems to defeat the purpose of separating components and pages. Clearly I am missing something fundamental in NextJS. Any insights would be very handy for the rest of the project.


In Microsoft Azure, How to retrieve operationid (of applicationInsights) in api policy

Question: In Azure API Inbound policy, how to retrieve application insights operationId field.
Tried with following in inbound xml but it did not work. also tried by context.Variables["InvocationId"].
@{
 return (context.Operation.Id);

}

Answer: Azure APIM provides access to context via "context" variable. Documented here: https://learn.microsoft.com/en-us/azure/api-management/api-management-policy-expressions#ContextVariables. In general it gives you access to full HTTP request/response that, and in addition to whatever scope information APIM maintains itself, like API, operation, product e.t.c. You should be able to get value used for operationId as context.RequestId.


Converter script SQL em Linq

Question: preciso fazer a conversão do script SQL abaixo para Linq.
SELECT
    [ID_Pessoa],
    [ID_ArquivoPagamento],
    SUM([Peculio_Valor]) AS 'Peculio_Valor'

FROM [VW_PESSOA]
WHERE   [ID_Pessoa] = @ID_Pessoa AND
        [ID_ArquivoPagamento] = @ID_ArquivoPagamento
GROUP BY [ID_Pessoa], [ID_ArquivoPagamento]

Abaixo o código em Linq, porém incompleto, pois não está realizando a somatória do Pecúlio:
 var reg = (from p in db.VW_PESSOA
            where
            p.ID_Pessoa == item.ID_Pessoa &&
            p.ID_ArquivoPagamento == ID_ArquivoPagamento
            select new
            {
                ID_Pessoa = p.ID_Pessoa,
                ID_ArquivoPagamento = p.ID_ArquivoPagamento,
                Peculio_Valor = p.Peculio_Valor
            }).GroupBy(p => new { p.ID_Pessoa, p.ID_ArquivoPagamento});

Comment: Já conhece o [Linqer](http://sqltolinq.com/)?
Comment: Não conheço @jbueno
Comment: Vou dar uma olhada
Comment: Você quer somar pelo agrupamento, certo?
Answer: Ficaria assim:
var reg = (from p in list
                       where
                       p.ID_Pessoa == item.ID_Pessoa &&
                       p.ID_ArquivoPagamento == ID_ArquivoPagamento
                       group p by new { p.ID_Pessoa, p.ID_ArquivoPagamento } into g
                       select new
                       {
                           ID_Pessoa = g.Key.ID_Pessoa,
                           ID_ArquivoPagamento = g.Key.ID_ArquivoPagamento,
                           Peculio_Valor = g.Sum(x=>x.Peculio_Valor)
                       });

Muda um pouco o que você fez só.
Fiz um Fiddle para vc ver como ficaria, repara em como o List é montado, o Where está com valor fixo na variável de comparação para ficar mais fácil de entender.
Código completo do Fiddle aqui:
using System;
using System.Linq;
using System.Collections.Generic;

public class Program
{
    class VW_PESSOA
        {
            public string ID_Pessoa;
            public string ID_ArquivoPagamento;
            public int Peculio_Valor;
        }

    public static void Main()
    {
        List<VW_PESSOA> list = new List<VW_PESSOA>();

            list.Add(new VW_PESSOA() { ID_Pessoa = "1", ID_ArquivoPagamento = "2", Peculio_Valor= 10 });
            list.Add(new VW_PESSOA() { ID_Pessoa = "1", ID_ArquivoPagamento = "2", Peculio_Valor = 10 });
            list.Add(new VW_PESSOA() { ID_Pessoa = "4", ID_ArquivoPagamento = "3", Peculio_Valor = 10 });

            var reg = (from p in list
                       where
                       p.ID_Pessoa == "1" &&
                       p.ID_ArquivoPagamento == "2"
                       group p by new { p.ID_Pessoa, p.ID_ArquivoPagamento } into g
                       select new
                       {
                           ID_Pessoa = g.Key.ID_Pessoa,
                           ID_ArquivoPagamento = g.Key.ID_ArquivoPagamento,
                           Peculio_Valor = g.Sum(x=>x.Peculio_Valor)
                       })
                       .ToList()
                       ;

        Console.WriteLine("Reparar em como o List foi montado para entender porque o resultado é 20.");
        Console.WriteLine("A soma de Peculio_Valor onde todos os IDs = 1 e ID_arquivoPagamento = 2 é: " + reg.First().Peculio_Valor);
    }
}

Comment: Bah, olha [isso](https://dotnetfiddle.net/dkyeDg) hahaha
Comment: Estamos de mais hoje kkkkkk. Coloca como resposta, ficou muito bom.
Comment: Capaz, a `query` tá igual a sua.

Converter script SQL em Linq


Once msw-storybook-addon added, I get Unexpected charachter '#' in node_modules/../Emitter.js

Question: I want to use my mock servers for my stories. The Storybook runs perfectly. Once I go through the steps of adding msw-storybook-addon and set up my preview.js from here and here (preview.js is different in these two resources, I tried both), and I run
start-storybook -p 9009 -s public

I get the error below:
    ERROR in ./node_modules/strict-event-emitter/lib/Emitter.js 14:4
Module parse failed: Unexpected character '#' (14:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|  */
| class Emitter {
>     #events;
|     #maxListeners;
|     #hasWarnedAboutPotentialMemortyLeak;
 @ ./node_modules/strict-event-emitter/lib/index.js 17:13-33
 @ ./node_modules/msw/lib/index.js
 @ ./src/mocks/browser.ts
 @ ./.storybook/preview.js
 @ ./.storybook/preview.js-generated-config-entry.js
 @ multi ./node_modules/@storybook/core-client/dist/esm/globals/polyfills.js ./node_modules/@storybook/core-client/dist/esm/globals/globals.js ./node_modules/webpack-hot-middleware/client.js?reload=true&quiet=false&noInfo=undefined ./storybook-init-framework-entry.js ./node_modules/@storybook/react/dist/esm/client/docs/config-generated-config-entry.js ./node_modules/@storybook/react/dist/esm/client/preview/config-generated-config-entry.js ./node_modules/@storybook/addon-actions/preview.js-generated-config-entry.js ./node_modules/@storybook/addon-interactions/preview.js-generated-config-entry.js ./.storybook/preview.js-generated-config-entry.js ./generated-stories-entry.js

ERROR in ./node_modules/strict-event-emitter/lib/MemoryLeakError.js 5:11
Module parse failed: Unexpected token (5:11)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| exports.MemoryLeakError = void 0;
| class MemoryLeakError extends Error {
>     emitter;
|     type;
|     count;
 @ ./node_modules/strict-event-emitter/lib/index.js 18:13-41
 @ ./node_modules/msw/lib/index.js
 @ ./src/mocks/browser.ts
 @ ./.storybook/preview.js
 @ ./.storybook/preview.js-generated-config-entry.js
 @ multi ./node_modules/@storybook/core-client/dist/esm/globals/polyfills.js ./node_modules/@storybook/core-client/dist/esm/globals/globals.js ./node_modules/webpack-hot-middleware/client.js?reload=true&quiet=false&noInfo=undefined ./storybook-init-framework-entry.js ./node_modules/@storybook/react/dist/esm/client/docs/config-generated-config-entry.js ./node_modules/@storybook/react/dist/esm/client/preview/config-generated-config-entry.js ./node_modules/@storybook/addon-actions/preview.js-generated-config-entry.js ./node_modules/@storybook/addon-interactions/preview.js-generated-config-entry.js ./.storybook/preview.js-generated-config-entry.js ./generated-stories-entry.js
Child HtmlWebpackCompiler:
                          Asset      Size               Chunks  Chunk Names
    __child-HtmlWebpackPlugin_0  6.25 KiB  HtmlWebpackPlugin_0  HtmlWebpackPlugin_0
    Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
    [./node_modules/html-webpack-plugin/lib/loader.js!./node_modules/@storybook/core-common/templates/index.ejs] 2.04 KiB {HtmlWebpackPlugin_0} [built]
ModuleParseError: Module parse failed: Unexpected character '#' (14:4)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|  */
| class Emitter {
>     #events;
|     #maxListeners;
|     #hasWarnedAboutPotentialMemortyLeak;
    at handleParseError (/Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/webpack/lib/NormalModule.js:469:19)
    at /Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/webpack/lib/NormalModule.js:503:5
    at /Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/webpack/lib/NormalModule.js:358:12
    at /Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/loader-runner/lib/LoaderRunner.js:373:3
    at iterateNormalLoaders (/Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/loader-runner/lib/LoaderRunner.js:214:10)
    at Array.<anonymous> (/Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/loader-runner/lib/LoaderRunner.js:205:4)
    at Storage.finished (/Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:55:16)
    at /Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:91:9
    at /Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/graceful-fs/graceful-fs.js:123:16
    at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:68:3)
ModuleParseError: Module parse failed: Unexpected token (5:11)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| exports.MemoryLeakError = void 0;
| class MemoryLeakError extends Error {
>     emitter;
|     type;
|     count;
    at handleParseError (/Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/webpack/lib/NormalModule.js:469:19)
    at /Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/webpack/lib/NormalModule.js:503:5
    at /Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/webpack/lib/NormalModule.js:358:12
    at /Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/loader-runner/lib/LoaderRunner.js:373:3
    at iterateNormalLoaders (/Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/loader-runner/lib/LoaderRunner.js:214:10)
    at Array.<anonymous> (/Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/loader-runner/lib/LoaderRunner.js:205:4)
    at Storage.finished (/Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:55:16)
    at /Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/@storybook/builder-webpack4/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:91:9
    at /Users/akeikha/Documents/code/pharmacy-management-ui/node_modules/graceful-fs/graceful-fs.js:123:16
    at FSReqCallback.readFileAfterClose [as oncomplete] (node:internal/fs/read_file_context:68:3)

WARN Broken build, fix the error above.
WARN You may need to refresh the browser.

info => Loading presets
error Command failed with exit code 1.

I realized from this error that the file Emmiter.js is using es6 syntax and for some reason, my webpack config doesn't have that loader. So I searched for how to override my webpack config without ejecting from here. I also looked for the loader that can interpret es6, and I found this. So I added the code below to my config-override.js
module.exports = function override(config, env) {
  config.module.rules[1].oneOf = config.module.rules[1].oneOf
    .map((one) => {
      if (one.options && one.options.name && one.exclude) {
        one.exclude = [/\.(mjs|jsx|ts|tsx)$/, /\.html$/, /\.json$/, /\.pdf$/];
      }
      return one;
    })
    .concat([
      {
        test: /\.js$/,
        loader: "babel-loader",
        options: { presets: ["es2015"] },
      },
    ]);

  return config;
};

And updated my scripts on package.json
yarn start gets stuck on Starting the development server...
I'm not even sure if this is the right solution.
Any ideas what the problem is and what I should do here?
Answer: Adding these packages to my package.json:
"@storybook/builder-webpack5": "6.5.16",
"@storybook/manager-webpack5": "6.5.16",
"webpack" : "5"

And these lines to my main.ts inside module.export
core: {
    builder: "@storybook/builder-webpack5"
  },
  docs: {
    autodocs: true
  }

resolved the issue.


Sending android "notifications" to a separate system

Question: Basically I'm trying to get the "notifications" present in the notification bar somewhere else, or something similar in effect.*
Mind the ": I'm not really interested in catching and possibly messing with the original notification, I just want to know that it is there. There seems to be more questions around this topic, but mostly the quality is "I WANT THIS" with an expected "YOU CAN'T" answer. Maybe you (we) can come up with another option?
Things I have come up with, but that seem problematic are:

1:
Catching all send notification's. I don't think you can extend/override/change the current notificationManager. People seem to think this is not needed for non-evil apps. I disagree. But nevertheless I don't know any method that can accomplish this. Another option would mean to ask the manager for the current 'live' notification, but there is no such method I believe. Also the conclusion of these threads:

Global intents that are fired for all Android notifications
Receive Android NotificationManager Notifications from Non-System Apps
Is it possible for an app to replace the NotificationManager? (google groups)

2: Catching Broadcasts. This seems more doable, although not everything has a broadcast available. Apart from that last point: This would mean I would have to find out what broadcasts are available, and act on each one hard-coded. How feasable would it be to let users add their own broadcasts? And how would they know if (and what) their favorite program sends out?  (I mean: add their own the app should listen to, not add a broadcast itself obviously)
This might involve something like an activity that catches everything for a certain period of time, and then you make sure you let your program send a notification, hoping it also sends something like a broadcast? Once a broadcast is identified, you want to act on that, but I don't know if you can change your behavior this dynamically.

3: Something completely different that will let me send as many different types of information (user choosable in the end) to an 'outside' place.

* I'm trying to send all notifications to a secondary location (a watch in this case). I can make something for all sorts of different situations (SMS, phone, mail, twitter etc), but this means double bandwith and cpu (battery), and everytime I (or a user) wants to add another type of message, I need to code more.
Answer:
But nevertheless I don't know any method that can accomplish this.

Correct, short of modifying firmware.

Another option would mean to ask the manager for the current 'live' notification, but there is no such method I believe

Also correct, short of modifying firmware.

And how would they know if (and what) their favorite program sends out?

They wouldn't.
You are certainly welcome to:

Define your own broadcast Intent structure for a broadcast saying "hey, if anyone out there has some sort of extended notification thingy, here's one!"
Create one or more end-user applications that consume such events (e.g., routing to your watch)
Document and evangelize your Intent structure, convincing developers to take advantage of it, either to broadcast such events or consume such broadcasts
Comment: Obviously that is possible, but not very likely to be adopted in my humble case. at your "they wouldn't": couldn't you make some sort of catch-all broadcastreceiver, that would catalogue all intents in a period of time, maybe several periods and show the overlapping intents. E.g.: start 'scanning', make the program do its thing (send yourself an email), stop scanning. Repeat. Check for intents that overlap. Dynamically add those. ?
Comment: @Nanne: "couldn't you make some sort of catch-all broadcastreceiver" -- fortunately, no, short of modifying firmware.
Comment: Hmm. Thanks. I'm not ready to completely give up on this idea yet, but have nothing specific to offer to counter your definitives :) I guess dynamically changing filters would be a problem too, right?
Comment: @Nanne: Well, you can't add new filters via the manifest. For broadcasts, you can register ones dynamically using `registerReceiver()`, but that requires some running component.


Tag dataframe origin of rows after merge

Question: I have two dataframes that I need to merge in order to compare the differences between two methods. What I need to do is to track which dataframe to rows in the resulting dataframe come from. I thus want to create a column carrying tht information in some way, either by tagging left, right, left+rihgt or any other way.
So, as an example, comsider the following:
Left =
   A  B
0  a  2
1  b  3
2  c  5
3  d  5

and
Right =
   A  R
0  a  3
1  b  4
2  e  7
3  f  5

which I merge
Both = Left.merge(Right,right_on ="A", left_on="A", how ="outer")

resulting in
   A    B    R
0  a  2.0  3.0
1  b  3.0  4.0
2  c  5.0  NaN
3  d  5.0  NaN
4  e  NaN  7.0
5  f  NaN  5.0

Now, in this elementary example, it is evident which row come from which df, but it might not always be that easy. Furthermore, I do not want to manually append the origin information. What I need is
   A    B    R  Origin
0  a  2.0  3.0  left+right
1  b  3.0  4.0  left+right
2  c  5.0  NaN  left
3  d  5.0  NaN  left
4  e  NaN  7.0  right
5  f  NaN  5.0  right

I know that using conditions and choices works, but I was hoping for something more compact.
Any ideas?
Answer: First add indicator=True, then rename column and replace values if necessary:
d = {'Origin':{'both':'left+right','left_only':'left','right_only':'right'}}
Both = (Left.merge(Right,on ="A",  how ="outer", indicator=True)
            .rename(columns={'_merge':'Origin'})
            .replace(d))
print (Both)
   A    B    R      Origin
0  a  2.0  3.0  left+right
1  b  3.0  4.0  left+right
2  c  5.0  NaN        left
3  d  5.0  NaN        left
4  e  NaN  7.0       right
5  f  NaN  5.0       right


What is ethical scoring?

Question: JJ Redick called Devin Booker an ethical scorer. What does this mean?
https://twitter.com/scooperhoops/status/1654707471934537729
https://www.reddit.com/r/nba/comments/139cd24/highlight_jj_redick_on_devin_booker_he_might_be/
Answer: JJ Redick is referring to the fact that Booker was scoring without making trips to the free throw line. By "ethical" he meant, no flopping, no getting free throws which are considered easy points to pad the points scored statistics.
Based on the timing of the comment and Booker's recent performance prior to that comment made, I'm assuming JJ Redick was referring to Booker's performance in Game 3 of the Western Conference semi Finals against the Denver Nuggets. Booker scored 47 points, only going to the foul line once, at the end of the game. Hence, he scored 40+ "ethically" without getting free throw points.

What is ethical scoring?


How to parse nls fit (multi line text) file using r?

Question: How to parse nls fit (multi line text) file as given below using r?
Nonlinear regression model
  model: A ~ BOTTOM + (TOP - BOTTOM)/(1 + 10^((logEC50 - xdata) * hillSlope))
   data: keep
      TOP    BOTTOM hillSlope   logEC50
  101.027     0.704     1.374    -6.319
 residual sum-of-squares: 581.7

Number of iterations to convergence: 7
Achieved convergence tolerance: 1.798e-06

I would like to get a table of fourth row text as column headers and the fifth row numbers as values s shown below:
TOP      BOTTOM   hillSlope   logEC50
101.027  0.704    1.374       -6.319

Comment: See `help("coef")` for extracting coefficients directly from the model object.
Comment: coef(fit) worked like a charm. Thank you for directing me to coef() function.
Answer: Try these three parameters, skip/nrows/header with read.table:
read.table(text = "Nonlinear regression model
    model: A ~ BOTTOM + (TOP - BOTTOM)/(1 + 10^((logEC50 - xdata) * hillSlope))
     data: keep
        TOP    BOTTOM hillSlope   logEC50
    101.027     0.704     1.374    -6.319
   residual sum-of-squares: 581.7

  Number of iterations to convergence: 7
  Achieved convergence tolerance: 1.798e-06", skip = 3, nrows = 1, header = T)

#      TOP BOTTOM hillSlope logEC50
#1 101.027  0.704     1.374  -6.319

As per @42- required:

Use skip to specify how many rows you want to ignore when reading in;
Specify header = T so the first row after skipping the rows will be read as headers;
Then you only want to read in one more row as the body, use nrows = 1 to specify this;
Comment: Thank you pointing out that there was code (parameter list) after the text. My wetware was not parsing it correctly.
Comment: OK. Explain what happens here. That text did not look like it should have gotten parsed.
Comment: @42- I thought these parameters are self explanatory, but I added the explanation to make it clearer.


Cointegration in quantile regression

Question: I used quantile regression for my research. My variables were significant but my pseudo r was low. So I tested for cointegration.
All my variables are I(1) and when I run the models with raw (nonstationary) data, the residuals are stationary at level. I believe this means my variables are cointegrated.
What should I do about the cointegration? What should my next step be?
Not using quantile regression is not an option.
I used OLS for the residual testing. And I am using EViews.
Answer: Vector error correction model (VECM) is appropriate for cointegrated data. The model only contains I(0) variables*, so no special treatment w.r.t order of integration is needed. You could use quantile regression techniques to estimate the model equations if you like.
*While the error correction term consists of I(1) variables, they enter in a fixed linear combination that is I(0).

Cointegration in quantile regression


Differences between subgroup analysis results from meta and metafor packages

Question: I am doing a meta analysis using R. After running an overall random effect model I wanted to look at subgroups in a mixed-effect model and was using the meta and dmetar package (Doing Meta Analysis in R), using the metagen()function which worked fine.
However, I might have issues with 1) non-independend data and 2) also correlated sampling errors in some cases. Thus, I thought about switching to the metafor package to use 1) the rma.mv() function to account for the non-independet data and using a 3-level model and 2) use the robust () function for the cases where I have correlated sampling errors.
In doing so I compared the metagen with the rma model. I could get similar results for the basic (reduced) random effects model.
But when I run the mixed-effect subgroup analysis I get very different results. I'm trying to figure out why because using one package indicates there is a significant heterogeneity between the groups whereas the other doesn't. Does anyone have any experience with these packages to know why?
Then I ran a random effects model with metagen () ...
MA1 <- metagen(TE, seTE, data = mydata, studlab = paste(ID),comb.fixed = FALSE,comb.random = TRUE,
             method.tau = "REML",  hakn = FALSE, sm = "SMD")

and rma ()
MA2 <- rma(TE, var, data = mydata, method="REML")

This yields the same results.
However if I do this:
MA1.taxa <- metagen(TE, seTE, data = mydata, studlab = paste(ID), comb.fixed = FALSE, comb.random = TRUE, method.tau = "REML",  hakn = FALSE, sm = "SMD", byvar = Taxa)

and the same using rma:
MA2.taxa <- rma(TE, var, mod= ~Taxa, data = mydata, method = "REML")

I get very different results.
It would be great if someone could help me out here. I have the feeling it might have something to do with some of the arguments which I didn't specify correctly. But in looking in the packages I couldn't figure it out.
This is my data frame:
**"ID"**|**"Study"**|**"Organism"**|**"Taxa"**|**"Species"**|**"Ne"**|**"Me"**|**"Se"**|**"Nc"**|**"Mc"**|**"Sc"**|**"TE"**|**"seTE"**|**"var"**
:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:
1|1|1|"A "|"F"|10|259.5|41.1096|10|405.5|15.8114|-4.48970286181781|0.86566827459304|0.74938156163689
2|1|1|"A "|"F"|10|285.9|12.6491|10|452.5|15.8114|-11.1441917779727|1.89336302866627|3.58482355832032
3|1|1|"A "|"F"|10|301.5|12.6491|10|459.1|12.6491|-11.9329315975384|2.02012537466928|4.08090652938268
4|2|2|"B "|"N"|8|40.58|8|8|565.3|8|-62.0123636363636|11.6055591474517|134.689003125
5|2|3|"B "|"Q"|8|15.59|1|8|436.2|5|-110.293157961666|20.6281624673369|425.521086778846
6|2|4|"B "|"R"|8|40.58|8|8|565.3|8|-62.0123636363636|11.6055591474517|134.689003125
7|3|5|"B "|"C"|4|1.887|1.9|4|519.3|26|-24.40757392403|7.05271437893494|49.7407801108356
8|3|6|"B "|"J"|4|18.4|1.5|4|519.3|24|-25.6159441945354|7.39845232761053|54.7370968439256
9|4|7|"B "|"K"|6|0.8174|2.4495|6|296.3|3.1843|-96.0142079773492|21.2399012943102|451.133406992038
10|5|8|"B "|"G"|12|20.2|2.4744|12|30.05|5.8324|-2.12287801050705|0.517088404453606|0.267380418020376
11|6|9|"C"|"A"|4|317.4|44|4|509.2|20|-4.88010696352562|1.5711445799467|2.46849529109589
12|6|10|"C"|"B"|4|333.3|20|4|541.8|16|-10.0108579072198|2.96371122455629|8.78358422256097
13|7|11|"B "|"S"|5|93|8.9443|5|477|11.1803|-34.2583184199475|8.50469827426505|72.329892736287
14|8|12|"B "|"H"|8|175.4|19.799|8|330.4|19.799|-7.4016594042858|1.4714809993973|2.16525633158727
15|9|13|"C"|"E"|6|353|7|6|584|14|-19.2655685142566|4.2992247363139|18.4833333333333
16|10|14|"C"|"O"|5|307.3|8|5|546.798|16|-17.1016587915647|4.28074511636117|18.32477875125
17|11|15|"B "|"D"|12|85.77|9|12|954.8|9|-93.2292720306513|13.9430530966266|194.40872965535
18|11|15|"B "|"D"|12|105.5|9|12|943.5|9|-89.9003831417625|13.4456304955873|180.784979423868
19|11|16|"B "|"I"|12|519.1|9|12|834.2|9|-33.8038314176245|5.06988227434525|25.7037062757202
20|11|16|"B "|"I"|12|504.6|9|12|861.6|9|-38.2988505747126|5.73992676427664|32.9467592592593
21|12|17|"B "|"M"|10|60|12.6491|6|187|31.8434|-5.56823589086092|1.16215466879402|1.35060347419974
22|12|17|"B "|"M"|10|74.6|12.6491|6|227|31.8434|-6.6818830690331|1.35186377624163|1.82753566951429
23|12|17|"B "|"M"|10|92.5|18.9737|12|276|13.8564|-10.7914331134072|1.74445205185438|3.04311296121895
24|13|18|"B "|"P"|6|334.7|29.3939|6|405.3|12.2474|-2.89426691425862|0.861952319419821|0.742961800953209
25|13|19|"B "|"P"|6|397.7|12.2474|6|407.5|39.1918|-0.311566458691052|0.581446713087198|0.338080280159906
26|14|20|"B "|"L"|3|216|36.3731|3|356|39.8372|-2.93620355270232|1.33762126119416|1.78923063839866
27|15|21|"B "|"P"|13|153.4|69.2266|19|163.1|51.8709|-0.159116969627101|0.360514880984436|0.129970979411222
28|16|22|"B "|"M"|5|124.6|2.2361|5|665.6|2.2361|-218.525630021163|54.1029220348491|2927.12617270896

Comment: If nobody answers here you could try the R mailing list dedicated to meta-analysis https://stat.ethz.ch/mailman/listinfo/r-sig-meta-analysis// where the authors of both packages frequently post.
Answer: The meta-regression model fitted via rma() assumes that there is one common $\tau^2$ value within the subgroups, while metagen() with byvar allows $\tau^2$ to differ between subgroups. An illustration:
library(metafor)
library(meta)

dat <- dat.bcg
dat <- escalc(measure="RR", ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat)
dat$sei <- sqrt(dat$vi)

First, we fit the meta-regression model with rma(). I will remove the intercept term, so that the model coefficients are the estimated average effects for each level of the moderator:
rma(yi, vi, data=dat, mods = ~ 0 + alloc)

These are the results:
Mixed-Effects Model (k = 13; tau^2 estimator: REML)

tau^2 (estimated amount of residual heterogeneity):     0.3615 (SE = 0.2111)
tau (square root of estimated tau^2 value):             0.6013
I^2 (residual heterogeneity / unaccounted variability): 88.77%
H^2 (unaccounted variability / sampling variability):   8.91

Test for Residual Heterogeneity:
QE(df = 10) = 132.3676, p-val < .0001

Test of Moderators (coefficients 1:3):
QM(df = 3) = 15.9842, p-val = 0.0011

Model Results:

                 estimate      se     zval    pval    ci.lb    ci.ub
allocalternate    -0.5180  0.4412  -1.1740  0.2404  -1.3827   0.3468
allocrandom       -0.9658  0.2672  -3.6138  0.0003  -1.4896  -0.4420  ***
allocsystematic   -0.4289  0.3449  -1.2434  0.2137  -1.1050   0.2472

---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Now the same analysis using metagen():
metagen(yi, sei, data=dat, comb.fixed=FALSE, method.tau="REML", byvar=alloc)

These are the results:
Number of studies combined: k = 13

                                         95%-CI     z  p-value
Random effects model -0.7145 [-1.0669; -0.3622] -3.97 < 0.0001

Quantifying heterogeneity:
 tau^2 = 0.3132 [0.1197; 1.1115]; tau = 0.5597 [0.3460; 1.0543];
 I^2 = 92.1% [88.3%; 94.7%]; H = 3.56 [2.93; 4.34]

Quantifying residual heterogeneity:
 I^2 = 92.4% [88.4%; 95.1%]; H = 3.64 [2.94; 4.50]

Test of heterogeneity:
      Q d.f.  p-value
 152.23   12 < 0.0001

Results for subgroups (random effects model):
                     k                     95%-CI  tau^2    tau      Q   I^2
alloc = random       7 -0.9710 [-1.5118; -0.4301] 0.3925 0.6265 110.21 94.6%
alloc = alternate    2 -0.5408 [-1.0927;  0.0111] 0.1326 0.3641   5.56 82.0%
alloc = systematic   4 -0.4242 [-1.1293;  0.2809] 0.4003 0.6327  16.59 81.9%

Test for subgroup differences (random effects model):
                    Q d.f. p-value
Between groups   1.86    2  0.3943

We see minor differences between the Model Results versus the Results for subgroups output.
One can fit a meta-regression model that allows for different $\tau^2$ values across subgroups with:
rma.mv(yi, vi, data=dat, mods = ~ 0 + alloc, random = ~ alloc | trial, struct="DIAG")

The results are then:
Multivariate Meta-Analysis Model (k = 13; method: REML)

Variance Components:

outer factor: trial (nlvls = 13)
inner factor: alloc (nlvls = 3)

            estim    sqrt  k.lvl  fixed       level
tau^2.1    0.1326  0.3641      2     no   alternate
tau^2.2    0.3925  0.6265      7     no      random
tau^2.3    0.4003  0.6327      4     no  systematic

Test for Residual Heterogeneity:
QE(df = 10) = 132.3676, p-val < .0001

Test of Moderators (coefficients 1:3):
QM(df = 3) = 17.4587, p-val = 0.0006

Model Results:

                 estimate      se     zval    pval    ci.lb    ci.ub
allocalternate    -0.5408  0.2816  -1.9204  0.0548  -1.0927   0.0111    .
allocrandom       -0.9710  0.2760  -3.5185  0.0004  -1.5118  -0.4301  ***
allocsystematic   -0.4242  0.3597  -1.1792  0.2383  -1.1293   0.2809

---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

These results are now identical to the ones from metagen().
Comment: Thank you @Wolfgang, that clarified a lot. I changed my code and got similar results. I have a couple of follow up questions. 1) Is the `mods= ~0+alloc` the same expression as `mods=~alloc-1`? 2) If I would want to add a nested structure to the model to account for non-independend data. Could I change the `inner|outer` structure like this: `rma.mv(yi, vi, data=dat, mods = ~ 0 + alloc, random = ~ alloc | study/trial, struct="DIAG")` I assume trial is a placeholder for a unique ID.


Visual Studio 2008 cl.exe properties openmp

Question: I need set property for compiler cl.exe /openmp on.
Tell me please, how and where can I do this?
Comment: There is a link on this page... http://openmp.org/wp/openmp-compilers/
Comment: Project properties -> `Configuration Properties` -> `C/C++` -> `Language`. Set `Open MP Support` to `Yes (/openmp)`.
Answer: Assuming you want to set this for a Visual Studio C++ project: See e.g. this article in the knowledge base.
Comment: And if you select `Language` instead of `Command Line` there is the `Open MP Support` drop-down list. Microsoft cannot even get the OpenMP name right (there is no space between Open and MP), not to mention their crappy implementation which stalled somewhere in 2002 (MSVC++ only supports OpenMP 2.0).


How can I remove extraneous virtual directories from Exch 2016?

Question: I am experimenting with setting up Exchange 2016 in a lab environment. Created a VM for DC and another for Exchange (both Server 2016).
I ran in to some issues with the Exchange install and decided to recreate the Exchange VM (No changes to DC VM). Changed the name of the Exchange server from  EX.contoso.com  to  EXCH.contoso.com .
The next install went perfectly , but now I have virtual directories for both EX. and EXCH (OWA/ECP/autodiscover, etc,). Power shell commands to remove the directories fail because of the name change(tried Remove-*VirtualDirectory). I get the "check that the server exists" error.
    I checked IIS but can't seem to find the extra directories listed. I can see the directories when I log in to ECP.
    Is there another way to remove the extra directories??
Answer: These extra directories should be the residual information of the EX server, we can delete the EX server via ADSI Edit tool and check if any helps:
Expand Configuration, CN=Configuration, CN=Services, CN=Microsoft Exchange, CN=, CN=Administrative Groups, CN=Exchange Administrative Group (FYDIBOH…, CN=Servers, select the server, and right-click on it and click Delete


Incluir javascript no Shiny

Question: Gostaria de incluir o evento "Restaurar a visibilidade da coluna
(https://datatables.net/extensions/buttons/examples/column_visibility/restore.html),
o código seria esse abaixo:
$(document).ready(function() {
$('#example').DataTable( {
    dom: 'Bfrtip',
    buttons: [
        {
            extend: 'colvis',
            postfixButtons: [ 'colvisRestore' ]
        }
    ],
    columnDefs: [
        {
            targets: -1,
            visible: false
        }
    ]
} );

No meu código em R, alguém poderia me dizer como?
output$dtDisp4 <- renderDataTable({

datatable(baseFullGI, extensions = 'Buttons', options = list(
  dom = 'Bfrtip',
  buttons = list('excel','colvis'),
  searchHighlight = TRUE,
  columnDefs = list(list(className = 'dt-center', targets = 0:11)),
  scrollX = TRUE,
  pageLength = 50
), filter = 'top',
class = 'cell-border stripe',
rownames = FALSE)

})

Comment: Não está claro qual o seu problema. O que você gostaria que acontecesse e não acontece?
Comment: Tomás, gostaria de incluir o evento "Restaurar a visibilidade da coluna".
Comment: https://datatables.net/extensions/buttons/examples/column_visibility/restore.html
Comment: Para mim já aparece com seu código. Inclusive sem incluir o JS
Comment: O problema acontece se você carrega o `shiny` depois do `DT`. Porque ele sobre escreve as funções `dataTableOutput()` e  `renderDataTable()`. Fazer a pergunta com um [exemplo reprodutível](https://pt.stackoverflow.com/help/mcve) ajuda.
Answer: Solução
Segue abaixo um exemplo mínimo e reprodutível da solução. Troquei sua base pelo  mtcars e a opção targets para 1.
library(DT)
library(shiny)

shinyApp(ui = fluidPage(DT::dataTableOutput("dtDisp4")),
         server = function(input, output) {
           output$dtDisp4 <- DT::renderDataTable({
             DT::datatable(mtcars, extensions = 'Buttons', options = list(
               dom = 'Bfrtip',
               buttons = list('excel','colvis'),
               searchHighlight = TRUE,
               columnDefs = list(list(className = 'dt-center', targets = 1)),
               scrollX = TRUE,
               pageLength = 50
             ), filter = 'top',
             class = 'cell-border stripe',
             rownames = FALSE)
           })
         }
)

Por que isso acontece?
O problema acontece se você carrega o shiny depois do DT. Porque ele sobre escreve as funções dataTableOutput() e renderDataTable().
Uma maneira de contornar este tipo de problema é dizer explicitamente na chamada da função em qual pacote o R deve buscá-la utilizando o operador ::.
Note que isso apenas é necessário porque ambos pacotes possuem funções com os mesmos nomes e o mecanismo de busca pela função do R vai primeiro naquele pacote que foi carregado por ultimo. Isso pode ser claramente observado com o exemplo abaixo. Com o ambiente limpo (reinicie o R), rode:
antigo <- search()
library(DT)
novo <- search()
library(shiny)
mais_novo <- search()

Não à toa, há um aviso quando shiny é carregado

Attaching package: 'shiny'
The following objects are masked from 'package:DT':
dataTableOutput, renderDataTable
Comment: Obrigado Tomás.

Incluir javascript no Shiny


Building hand strength for when tapping on the guitar

Question: I've been practicing on my tapping ability. An example of what I mean by tapping can be viewed here, notice how the right hand hits the strings.
I'm currently using all four fingers excluding the thumb to tap the guitar. I find my pinky is not as strong as my other fingers when it comes to applying the appropriate strength on the string. What are some exercises I can do to increase my overall finger strength when tapping? More tapping?
As a sidenote, I've noticed that I use the momentum of my forearm to help apply the appropriate pressure on the string I'm trying to hit. If I remove that momentum and only use force created by the movement of my finger the pressure is significantly less. I was hoping these exercises would also help me to not rely on my forearm as much.
Answer: From my experience & from forum surfing, I can confidently say that your pinky finger will always be weaker than the others.  I have tried the following techniques and think that they can be used to help bridge the gap for you (aside from unfocused tapping):

Tap softer with the other fingers and tap harder with the pinky finger, slowly and cleanly.  Build up speed keeping the sound clean.
Use hand / finger grips to exercise the fingers, focusing on the pinky.  (Gripmaster, Planet Waves, Xtensor, etc.)
Use finger weights.

Place weights on pinky to make it work harder, which will in turn build strength.  Start off light, slow, and clean -- gradually increasing speed.  After a week or so, increase weight and start back slow.  You can alternate between increasing speed and or increasing weight, depending on what you want to train.

If I were you, I would invest in the finger weights.  I have found them very helpful.  You actually feel faster and stronger after playing with them on and then removing them and playing normally.
Note: I do not consider myself to be an expert guitar player.
Comment: To point #1, I find that when practicing slowly, it is good to make sure that the motions of the individual fingers are done at full speed. This makes the transition from slow to fast more automatic.
Comment: Interesting, haven't heard of finger weights. I'm going to keep this question open a bit longer to see if anyone else has any tips.
Answer: In moments where you have nothing to do (sitting on the bus, watching tv), you could train your hands by tapping on you knee for example. You could also stretch your fingers backwards and try to counter that with your finger muscles to basically train them.
Also, what really helped me building strength in my left pinky was starting to play the piano.
I have pretty small hands and for me it really really helped a lot :).
On top of that, I can play a bit of piano now :).


why std::future template argument type is reference type?

Question: I am looking at the std::future documentation at http://en.cppreference.com/w/cpp/thread/future
What I don't understand is that why the template argument type(in 2) is reference?

template< class T > class future<T&>; (2) (since C++11)

Comment: It's a partial specialization for reference types.
Answer: This is the reference specialization for std::future which accounts for those cases in which the return values is a reference type.
Check for instance the following example code:
// future example
#include <iostream>       // std::cout
#include <future>         // std::async, std::future

int counter = 0;

int& increment_counter()
{
    return ++counter;
}

int main ()
{
    std::future<int&> fut = std::async(increment_counter);

    int &counterRef = fut.get();

    std::cout << "value:" << counterRef << std::endl;

    return 0;
}


user_cancel_reassign() doesn't work when user has more than 10 nodes

Question: I am attempting to delete users with no permissions/roles from our sites. The user's node should be kept.
This code works when the user has a few nodes. On deletion, their ownership is passed to the anonymous user.
use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException;
use \Drupal\user\Entity\User;

function mymodule_preprocess_page(&$variables, $hook) {
  $route_name = \Drupal::routeMatch()->getRouteName();
  $user = \Drupal::currentUser();
  if (count($user->getRoles()) == 1 && ($route_name != "system.401" && $route_name != "user.login")) {
    $userWithoutRole = User::load($user->id());
    if ($userWithoutRole !== NULL) {
      user_cancel([], $user->id(), 'user_cancel_reassign');
      $userWithoutRole->delete();
    }
    throw new UnauthorizedHttpException('insufficient permissions');
  }
}

It doesn't work when the user is the author of more than 10 nodes. All the nodes are deleted when the user is deleted.
Another method is invoked, I suppose.
How can I solve this?
The same issue is present with the Auto purge users module.
Answer: user_cancel() is run in a batch. This means that either it's called in a form, or batch_process() needs to be called after it. For example, this is the code used by UserController::confirmCancel().
$edit = [
  'user_cancel_notify' => isset($account_data['cancel_notify']) ? $account_data['cancel_notify'] : $this->config('user.settings')->get('notify.status_canceled'),
];
user_cancel($edit, $user->id(), $account_data['cancel_method']);

// Since user_cancel() is not invoked via Form API, batch processing
// needs to be invoked manually and should redirect to the front page
// after completion.
return batch_process('<front>');

It's not necessary to delete the account, as that is already done from _user_cancel(), the batch operation callback used from user_cancel().
case 'user_cancel_reassign':
case 'user_cancel_delete':
  // Send account canceled notification if option was checked.
  if (!empty($edit['user_cancel_notify'])) {
    _user_mail_notify('status_canceled', $account);
  }
  $account->delete();
  // …

It's also probable that hook_preprocess_page() is the wrong place to call user_cancel() as it would be called when the page is being rendered, while the batch operations require to redirect users. See batch_process(), which contains the following code.
if (($function = $batch['redirect_callback']) && function_exists($function)) {
  $function($batch_url->toString(), [
    'query' => $query_options,
  ]);
}
else {
  return new RedirectResponse($batch_url->setAbsolute()->toString(TRUE)->getGeneratedUrl());
}

Comment: If the account isn't deleted that means that batch operations are not correctly executed. I would rather use a controller associated to a route, to be sure they are correctly executed.
Comment: Thanks but ...Adding batch_process(); has no effect on my code. If Removing   $userWithoutRole->delete(); in my code the user is not deleted. If not hook_preprocess_page(), where ? for what i am trying to achieve ?
Answer: In my case, I was performing mass user deletion in a Drush command. First I was calling directly the batch operation _user_cancel because calling user_cancel() was leading to perform a batch in a batch, which would not work.
But the problem was that because of that I was skipping some actions of user_cancel(), like for example the call of hook_user_cancel() of any other module implementing the hook in question.
Finally I was able to call user_cancel() :
protected function cancelUsers() {
  $user_settings = \Drupal::config('user.settings');

  foreach ($this->obsoleteUser as $uid) {
    $cancel_method = $user_settings->get('cancel_method');

    $edit = [
      // Use $user_settings->get('notify.status_canceled') in
      // the following if you need to apply the user settings.
      'user_cancel_notify' => FALSE,
      'user_cancel_method' => $cancel_method,
    ];

    // user_cancel() will set batch operations itself. All is needed is a call
    // to process it.
    user_cancel($edit, $uid, $cancel_method);
  }
}

And make sure in my command that I was using the batch initiated by user_cancel() :
$batch =& batch_get();

if (empty($batch)) {
  return;
}

drush_backend_batch_process();


Pass JSP output stream to a method

Question: I've created a class MyClass that intends to output a large amount of text to a JSP. Rather than having the MyClass object return a string to be displayed on the page, I figured it would be a better idea for the MyClass object to use the page's output stream. Is this a good/possible idea?
In testing possible ways to do this...
These output the text, but it displays before the body of the page:
response.getWriter().append("test1");
response.getWriter().println("test2");
response.getWriter().write("test3");

This errors and tells me the output stream was already gotten:
response.getOutputStream().println("test4");

Answer: response.getWriter() will give you different writer than one used in JSP. If you want to write to same writer as JSP page is using, you need to use out variable from JSP page. Difference is that JSP uses buffering on top of standard response.getWriter(). That's why you see your data written to response.getWriter() before JSP body.
You cannot mix response.getWriter() and response.getOutputStream(). out variable in JSP is JspWriter instance wrapping writer obtained response.getWriter() so calling response.getOutputStream() will fail.
What you should do in your JSP:
<%
  new MyClass().writeToWriter(out);
%>

And in MyClass:
public void writeToWriter(Writer w) {
    w.println("My data appended to correct writer");
}

Answer: Have the class return you an iterator that generates the text one small chunk at a time. You could then iterate through the iterator in the JSP and print the data chunks at the appropriate location.

Pass JSP output stream to a method


Como ordenar pelos resultados mais similares ao parâmetro passado?

Question: Tenho uma tabela no meu sistema que guarda todos os aeroportos e em um select autocomplete eu tenho essa lista onde eu posso pesquisar.
O problema é que eu posso pesquisar por "nome", "cidade", "país" e "IATA" e preciso retornar em ordem de mais similar os aeroportos encontrados.
Por exemplo:
meu parâmetro é "GRU" e a função me retorna isto:
{
    "airports": [
        {
            "id": 1059,
            "iata": "BPA",
            "full_name": "Grumman, Bethpage, Bethpage, (BPA)"
        },
        {
            "id": 3410,
            "iata": "GUU",
            "full_name": "Bakki, Grundarfjordur, Grundarfjordur, (GUU)"
        },
        {
            "id": 8083,
            "iata": "GRU",
            "full_name": "Guarulhos, São Paulo, São Paulo, (GRU)"
        }
    ],
}

Como podem ver, o retorno está certo, mas eu, como usuário, pesquisei o IATA e a função me retornou tudo que fosse parecido com o que eu pesquisei.
O código é o seguinte:
$str_where = "CITEXT(
                            TRANSLATE(
                                TRIM(
                                    name || ', ' || city || ', ' || country || ', ' || '(' || iata || ')'
                                ) ,
                                'áàâãäåaaaÁÂÃÄÅAAAÀéèêëeeeeeEEEÉEEÈìíîïìiiiÌÍÎÏÌIIIóôõöoooòÒÓÔÕÖOOOùúûüuuuuÙÚÛÜUUUUçÇñÑýÝ',
                                'aaaaaaaaaAAAAAAAAAeeeeeeeeeEEEEEEEiiiiiiiiIIIIIIIIooooooooOOOOOOOOuuuuuuuuUUUUUUUUcCnNyY'
                            )
                        )";

            $airports = $connection
                    ->newQuery()
                    ->select(['id', 'iata'])
                    ->select(["CITEXT(name || ', ' || city || ', ' || country || ', ' || '(' || iata || ')' ) AS full_name"])
                    ->from('white_label_airports')
                    ->where([$str_where . ' LIKE' => '%' . \Cake\Utility\Text::transliterate($this->request->data('term')) . '%'])
                    ->limit(20)
                    ->execute()
                    ->fetchAll('assoc');

Gostaria de saber se tenho como ordenar pelo mais similar dentre a resposta do servidor e se alguém tem alguma ideia melhor.
Agradeço desde já!
Comment: No Oracle uso a Jaro Winkler e/ou a EDIT_DISTANCE  , para Postgreesql no Google achei isto https://gist.github.com/fjavier/586c713943d76a023a70 , eu uso para buscar strings por "proximidade" veja se ajuda
Comment: Bem interessante essa implementação, eu nem fazia idéia de como funcionavam os algoritmos de similaridade entre strings! Ainda assim sugiro o uso do pg_trgm por ser uma solução "nativa" do Postgres, que suporta indexação por similaridade e tudo o mais, hehe...
Answer: Para classificar esse array você precisa de um índice de similaridade que lhe diga que Guarulhos é a "melhor resposta" dos três, algo que tem que ser retornado pelo servidor que te disse que esses são os resultados mais similares...
Usando pg_trgm
Com PostgreSQL eu usaria o módulo pg_trgm, que te retorna tal índice e já permite classificar com ORDER BY direto na consulta, poupando qualquer trabalho extra no PHP. Para fins de exemplo, criei uma tabela "aeroportos" com os três registros que você mostrou:
create table aeroportos (id int not null, iata text not null, full_name text not null);
insert into aeroportos values
(1059, 'BPA', 'Grumman, Bethpager, Bethpage, (BPA)'),
(3419, 'GUU', 'Bakki, Grundarfjorfur, Grundarfjordur, (GUU)'),
(8083, 'GRU', 'Guarulhos, São Paulo, (GRU)');

Aqui podemos usar a função word_similarity(), que retorna o grau de similaridade entre uma string e a palavra mais parecida com ela em outra string. Quanto maior o valor na coluna grau (de 0 a 1), maior a similaridade entre as strings.
Note que concatenei as colunas iata e full_name para comparar com "GRU" como uma coisa só.
select *, word_similarity(iata||full_name, 'GRU') as grau
from aeroportos
order by grau desc;

  id  | iata |                  full_name                   |   grau
------+------+----------------------------------------------+----------
 8083 | GRU  | Guarulhos, São Paulo, (GRU)                  | 0.166667
 3419 | GUU  | Bakki, Grundarfjordur, Grundarfjordur, (GUU) |    0.125
 1059 | BPA  | Grumman, Bethpager, Bethpage, (BPA)          | 0.047619
(3 rows)

Detalhando um pouco mais...
Como a sua tabela certamente possui mais do que três registros, é interessante utilizar também operadores de similaridade para filtrar somente aqueles que se pareçam o suficiente com a sua busca, senão toda consulta retornará a lista inteira de aeroportos, na maioria com similaridade '0.0'. Você pode simplesmente usar LIMIT e cortar na quantidade de registros que lhe for mais conveniente, mas pode também usar outras funcionalidades do PostgreSQL para filtrar por similaridade, algo que te dará muito mais desempenho para grandes volumes de dados se somado ao uso de índices GIST.
Para isso podemos usar o operador (que também faz parte do pacote pg_trgm) <% na cláusula WHERE. Esse operador retorna true caso o primeiro parâmetro seja uma string que contenha palavra similar ao segundo parâmetro, desde que o grau de similaridade de palavra seja maior do que o limite mínimo especificado pela opção pg_trgm.word_similarity_threshold. Como já notamos pela query anterior, o grau geral de similaridade de nossas comparações é geralmente baixo, já que a "resposta certa" para GRU tem uma pontuação de somente 0.16. Assim, devemos baixar o limitador mínimo para que o nosso WHERE não retorne zero registros. Quanto menor for o pg_trgm.word_similarity_threshold, mais registros serão retornados:
set pg_trgm.word_similarity_threshold to 0.1;

select *, word_similarity(iata||full_name, 'GRU') as grau
from aeroportos
where (iata||full_name) <% 'GRU'
order by grau desc;

  id  | iata |                  full_name                   |   grau
------+------+----------------------------------------------+----------
 8083 | GRU  | Guarulhos, São Paulo, (GRU)                  | 0.166667
 3419 | GUU  | Bakki, Grundarfjordur, Grundarfjordur, (GUU) |    0.125
(2 rows)

Definido todo esse curso de ação, no PHP a coisa fica simples. É só mandar o SET para o limite mínimo de similaridade junto com a query:
$query = "set pg_trgm.word_similarity_threshold to 0.1; select *, word_similarity(iata||full_name, 'GRU') as grau from aeroportos where (iata||full_name) <% 'GRU' order by grau desc;";
$res = pg_query($conn, $query);

Ou ainda, caso não queira passar toda vez o limitador, pode inclusive fixá-lo como propriedade do usuário da sua aplicação:
alter user nunks set pg_trgm.word_similarity_threshold = 0.1;
select usename, useconfig from pg_user where usename = 'nunks';
 usename |                useconfig
---------+-----------------------------------------
 nunks   | {pg_trgm.word_similarity_threshold=0.1}
(1 row)

Instalando a extensão pg_trgm
Caso você não tenha o pg_trgm instalado, use o comando CREATE EXTENSION:
> create extension pg_trgm;
CREATE EXTENSION

Caso o comando falhe você provavalmente precisa instalar o pacote de extensões postgresql-contrib, que pode tanto ser compilado quanto instalado a partir do gerenciador de pacotes de sua escolha. No Windows, o instalador gráfico te dá opção de quais módulos contrib instalar.
Além da função word_similarity() que utilizamos aqui, a extensão pg_trgm oferece outras funcionalidades associadas, como índices GIN e GIST capazes de agilizar bastante a resposta de buscas por similaridade em grandes volumes de dados, operadores especiais e métodos para ajuste fino dos valores limite de similaridade.


Styling two different elements in the option of HTML select tag

Question: In my PHP code, I am pulling a table of two columns from the database and displaying both of them in a dropdown list. Following is the code snippet:
echo "<select id='isv' class='required'>";
while($row = pg_fetch_row($result)){
    echo "<option>" . $row[0] . " " . $row[1] . "</option>";
}
echo "</select>
";

I wanted to separate them both by styling them differently. So I wrote the following CSS:
.options
{
    color: red;
    float: left;
    text-align: right;
    width: 15em;
    margin-right: 1em;
}

However, the style is not getting applied to the options. What exactly do I need to change in this code?
Comment: If you're using Firefox, a very handy add-on to have is Firebug.
Comment: You can't have markup in an option tag
Comment: Just a heads up, but [this related](http://stackoverflow.com/questions/3354979/styling-part-of-the-option-text?rq=1) would indicate that this sort of styling its platform-dependent.
Comment: @Blaine: Firebug is not showing the span element in the style section.
Comment: @jedwards: Thank you for the link. I should have come across that before posting here. :)
Answer: <option> elements can not be styled that way, you'll have to design your own implementation using JavaScript. Drop-down menus (<select>s) are mostly styled by the browser chrome, not by CSS. In addition, the <option> element may not have any child elements.
Here is a good reference for what you can style via CSS: http://bavotasan.com/2011/style-select-box-using-only-css/
Answer: You can make smart use of margin for that instead of the .  (which won't work, needless to say)
Consider using some jQuery plugins for custom drop downs. See an example here. And also the answers tp this SO question.
Comment: Seems to be easy when you have an image along with the element. I have 2 elements in an option though.


AngularJS mechanism to ask server for token based status

Question: In my client side I have a button that triggers an api call that take few minuts to reply, so in the server side I want to return a token to the client and and then the client can ask for status based on the token.
How the client can ask for status every 1 min lets say? and I also dont want to use database and just want to save the token in cache, how can I do that too?
thansk!
Comment: Search for `ngIdle` module. Thats what you need
Answer: This might not be the best or the only solution. But I have been using this library for a while and its good and simple.
ngIdle  helps you track the time against your angular app and perform function as and when that time elapses. This is usually for a timeout and idle type of stuff but I suppose you too can use it.
Usage:
In your app's config, initialize the library as:
 function ConfigFn(IdleProvider) {

        //set configuration for ng-idle
        IdleProvider.idle(60); //in seconds
        IdleProvider.timeout(120); //do not use this if not really required
}

AFAIK, it provides you 2 time hooks and an event is raised at each time hook. You can listen to this event and perform any function.
In your run block :
function runtimeFn(Idle) {
        //setting a timer watch as soon as application bootstraps, you have to reset it every time your time elapses and you call server.
        Idle.watch(); //Idle is just a service from the library

        //responsing to various events in the application
        $rootScope.$on('IdleStart', callServerForToken);
        $rootScope.$on('IdleTimeout', doSomethingAgainIfYouWant); //do not use this if not really required
    }

This should help you. Let me know if something remains unclear.


Is it against the rules to fly in the NBA?

Question: If someone were to miraculously develop the super power to fly (say they could hover up to 1000 feet and swiftly move in three dimensions) would any rules as currently defined by the NBA prevent the use of this power during play?
Comment: Welcome to Sports Stack Exchange. [A previous meta post](https://sports.meta.stackexchange.com/questions/922/) suggests we should not have a problem with this question, though I would advise potential answerers to focus purely on the rules rather than speculate on effects this would have.
Answer: I don't believe flying would break any specific rules in the NBA (or FIBA) rulebook - but that's not really the same as saying "flying is legal in the NBA" as the governing body for a sport (any sport) isn't going to waste its time writing explicit rules to cover situations which can "never" occur.
If we ever got to a state where flying was a reasonable possibility, something would be done to the basketball rules to regulate it. For example, the rules regulate goaltending, something which is a realistic possibility for humans today.
Comment: Thanks for the answer. I probably didn't explain the intention of my question well enough. It wasn't about whether there was some rule that had been created on the off-chance someone developed superpowers, but more about whether there was some pre-existing rule that just happened to forbid that kind of movement as a side-effect of the actual intent of the rule. Say, a rule about traveling that restricts how you can move while in possession of the ball, etc.


Como hospedar site no meu pc

Question: Estou criando uma aplicação em php com usando o xampp.
Gostaria de saber como faço para transformar meu PC em um servidor de hospedagem, para poder acessar minha aplicação de qualquer lugar.
Ja tentei acessar o admin do meu roteador (D-link Dir-608) criei um "servidor virtual", todavia, sem sucesso, ocorre erro ao tentar acessar o ip externo.
Alguém tem alguma dica ou tutorial ensinando? Obrigado.
Comment: Possível duplicata de [acesso externo com wamp](https://pt.stackoverflow.com/questions/50927/acesso-externo-com-wamp)
Answer: Utilize o software No-IP. Realize o cadastro no site, escolha um nome de host externo, exemplo minha-casa.sytes.net, instale o software em seu computador e acesse o software com suas credências.
Uma vez acessado e logado no software, será necessário configurar seu roteador para encaminhar um determinado tráfego a sua máquina. No caso de uma hospedagem, as portas importantes seriam as 80 para acesso via HTTP, e 443 para acesso via HTTPS. Acredito que apenas configurar a 80 seja o suficiente para o seu caso.
Para realizar essa configuração você vai precisar do IP da sua máquina, pois o que será feito é redirecionar todo o tráfego que chegar na porta 80 do seu roteador para sua máquina.
Para pegar seu IP, abra o Prompt de Comando e digite, ipconfig. Seu ip deverá ser algo parecido com 192.168.x.x, 10.x.x.x ou 172.16.x.x.
Acesse o roteador e procure pela configuração de encaminhamento de portas ou no inglês, port forward. Você deverá informar nessa configuração o endereço IP da sua máquina e também a porta de entrada e de saída. Tanto a porta de entrada como de saída será a porta 80 e o endereço IP o da sua máquina.
Com tudo configurado corretamente, você deverá configurar o xampp para responder no endereço do site que registrou no No-ip.
Espero que seja útil e consiga realizar sua configuração.
Comment: Só que a maioria dos ISP's bloqueiam a porta 80, justamente para evitar que as pessoas façam esse tipo de coisas em conexões caseiras, e se ler o contrato de grandes provedores, verá que criar um servidor web utilizando conexões caseiras viola o contrato e é passível de cancelamento do plano.
Comment: Na verdade minha intenção não é deixar hospedado na minha maquina, pretendo pagar um servidor dedicado, mas antes disso, preciso de um ambiente para realizar testes.
Comment: Bruno, fiz oque você sugeriu, mas quando tento acessar o host que o NO-IP forneceu, ocorre o seguinte erro:
Não é possível acessar esse site "..." demorou muito para responder.
Comment: Como nosso amigo acima citou, alguns ISP bloqueiam a porta 80, tente alterar para 81 e ver se consegue conectar. Se conseguir, é porque bloquearam a porta 80, se não, talvez algum passo esteja incorreto. Outro ponto a validar é, desative ou libere a porta correspondente no seu firewall (da sua máquina).
Comment: Coloquei o xampp na porta 888, desativei firewall e antivirus. consigo acessar o xampp através de "localhost:888" ele mostra a tela do dashboard.
Quando coloco o host ou ip externo seguido de :888 ocorre o erro "demorou muito para responder."
Comment: Colocou também no roteador o forwarding da porta 888 para sua máquina?
Comment: Sim, fixei meu IP na maquina. E no roteador, configurei a porta 888 para o meu IP fixo.
Comment: @YagoLima tente o passo a passo da resposta que formulei https://pt.stackoverflow.com/a/50934/3635

Como hospedar site no meu pc


How to stop floats and classes from pushing each other down?

Question: I am simply trying to add a form to my website, however when I added it and used the  above in order for it to fit the frame, it just pushed all the content down Like so

How can I have it so it is all aligned at the top? I cannot figure out why it is being pushed down to the bottom half of the fold.
relevant code:
link to jsfiddle with css: jsfiddle.net/sz2f64hd/

    {$page}

                    <volist name="index_mid4" id="item">

{$item.title}

                            {$item.content}

                    </volist>

categories

                        <volist name="category_list" id="item">

{$item['title']}

                        </volist>

                <form action="{:U('Contact/quickAdd')}" class="frm_contact">
                    <input type="hidden" name="type" value="1" />

              Request FREE Trial

                        <input type="text" class="form-text blue" name="customer_name" id="username" placeholder="Full Name" />

                        <input type="text" class="form-text blue" name="email" id="username" placeholder="Email" />

                        <input type="text" class="form-text blue" name="city" id="username" placeholder="Preferred City" />

                        <button type="submit">Submit</button>

                </form>

Comment: * { vertical-align: top; } ?
Answer: Why does your body end before your header ?
Can you show us the CSS?
Have you tried f12 and ctrl u to analyze the code ?
Maybe there's something hidden and search the element with f12 then you can check and try the CSS
I found it:
Here :
 .serve-apply > .body {

You make
height:450px;

delete that

You have some div there thats just closed and never opened
Comment: I am not seeing where the body ends before the header, here is a jsfiddle with all the css that the webpage uses http://jsfiddle.net/m2rn59pb/ I have tried searching using f12 and ctrl u but I am not coming up with anything
Comment: Your side.shake-an div is not inside the body is that right? I mean do you want that ?


modifying a value in viewstate

Question: Say I have a property like...
public object MyObject
{
    get { return (object)ViewState["myobject"]; }
    set { ViewState["myobject"] = value; }
}

I modify the object like so...
object myObjCopy = MyObject;
myObjCopy.ChangeSomething();
MyObject = myObjCopy;

Is this the correct method? It just feels really clunky and I wonder if I'm missing something. Is there some clever paradigm which enables modifying viewstate more intuitively without using temporary copys everywhere in my code.
Answer: With the property you have defined, you should not need to do any copying like what you have.  I'm not sure what ChangeSomething() does, but you should be able to call it directly on the property.  I would normally not pull it out as an object... It's been a while since I did pure webforms development, but my ViewState helper properties usually looked more like:
public string CurrentUsername
{
    get
    {
        if (ViewState["Username"] is string)
           return (string)ViewState["Username"];
        return null;
    }
    set { ViewState["Username"] = value; }
}

Edit: Thinking about it, I guess the copy is probably there just to remove the potential performance overhead of casting every time you reference the property.  I don't think this is a valid optimization in most cases, but if you feel strongly about it, you could hide it with something like this:
private string m_CurrentUsername;
public string CurrentUsername
{
    get
    {
        if (m_CurrentUsername == null && ViewState["Username"] is string)
           m_CurrentUsername = (string)ViewState["Username"];
        return m_CurrentUsername;
    }
    set { ViewState["Username"] = m_CurrentUsername = value; }
}

Like I said though - I wouldn't recommend this.
Comment: I think you are over-analyzing my question, I'm not bothered about the casting overhead, I was just trying to give a simple example. The issue is that if ChangeSomething() returns an object, I can write MyObject = MyObject.ChangeSomething(); which is fine, but if ChangeSomething() returns void and modifies the instance variable, you can't directly modify the viewstate with MyObject.ChangeSomething() as you could if the property wrapped a normal instance variable. At least thats how it appeared to me when I tried it. I assumed it was something to do with the underlying object being serialised.
Answer: The correct answer is that you shouldn't be modifying viewstate at all.  Your controller should create the models and populate the viewstate only just before returning the view.  If you're writing this code in the view, you've got an even bigger problem.  in general, the view should contain little (if any) code that changes or does things.
Edit: Oops, I think I just got ViewData (in asp.net mvc) confused with viewdata.  sorry ... to answer your real question, yes, that is just about the only way :-) it's not really clunky when you are dealing with a "bag" API like the viewstate is.

modifying a value in viewstate


Is $\frac{1}{x}$ a function?

Question: Consider $f(x)=\frac{1}{x}$ defined on set of real numbers.
If every element in domain has image, then above relation is said to be a function.
But for $x=0$,  $f(x)=\text{infinity}$.
Does it mean that $0$ doesn't have image? And hence $\frac{1}{x}$ not a function?
Comment: $f(x)$ is a function with domain $(-\infty,0)\cup (0,\infty)$ or any subset.
Comment: @Priyanka You need to brush up on your fundamental definitions.
Comment: When $x=0$ $1/x$ is not infinity, it is just not defined.
Comment: It means that 1/x is not a function for real numbers, right?
Comment: It is,  if defined as you say in 3rd statement. You extended the codomain with one element "infinity".
Answer: You are correct, in that a function must be defined for every element in its domain, and that therefore you cannot create a function $f:\mathbb{R}\to\mathbb{R}$ defined by $f(x)=\frac{1}{x}$, because $\frac{1}{0}$ is undefined.
You can however create a function $g:\mathbb{R}\setminus\{0\}\to\mathbb{R}$ defined by $g(x)=\frac{1}{x}$, because we have removed the problematic element $0$ from the domain.
You can also create a function $h:\mathbb{R}\to \mathrm{P}^1(\mathbb{R})$ defined by $h(x)=\frac{1}{x}$, where $\mathrm{P}^1(\mathbb{R})=\mathbb{R}\cup\{\infty\}$ is the real projective line (Wikipedia), which has the element $\infty$ available to be the output of $h(0)$.
Answer: Function is a set of ordered pairs $(x,y)$ where $x$ and $y$ depends to sets $X$ and $Y$ respectively. If your definition satisfies this, it is enough. So strictly speaking, if you  say, that set $Y$ is a real numbers extended with at least one element "infinity", it is a function. Otherwise, you can say it is a function, but not defined for zero.
Answer: A function should be defined by
(a) $f(x)$ and
(b) the domain upon which you want to consider the function
The reason for also including the domain is that many functions are undefined at points where the function is discontinuous.
You could instead define your function f(x) for all real numbers as:
$f(x) = 0$ when $x = 0$
$f(x) = 1/x$ when $x>0$ or $x<0$
Comment: Thank you all of you for clearing my confusion. I understood it properly now.

Is $\frac{1}{x}$ a function?


How to Sum Numbers With Probability

Question: I have a number of quotes sent to customers to produce widgets. Each quote has a maximum potential quantity and a probability of winning. For example, I have 5 quotes with a quantity and a probability of winning:
<code>Q#   Qty    Probability of Winning
----------------------------------
1    1,000  50%
2    5,000  23%
3    4,000  37%
4    2,000  61%
5   10,000  13%
</code>
I want to show a range of likely qualities needed for planning purposes. The max range is the sum of the qty = 22,000. My question is: what is a reasonable number to show as a minimum (understanding that the min could be zero)? Is sum(qty*p) a reasonable number (5,650)? Other insights would be appreciated.
Comment: $1000\cdot 0.5+5000\cdot .23+4000\cdot .37+\dots$ would be the [*expected number*](https://en.wikipedia.org/wiki/Expected_value) of wins, not the minimum.  You could also calculate the [variance](https://en.wikipedia.org/wiki/Variance) using known techniques.
Comment: Having been involved in things like this, I would bet those probabilities are somebody's guess and have little to do with reality.  You can do a number of reasonable calculations, but remember garbage in/garbage out.
Comment: Absolutely! The numbers are pretty much pulled out of the air (or other places). Loosely based on customer relationship and how often a customer selects our widgets.
Answer: Is each quote "all-or-nothing"?  Does this mean that, e.g. for #1, you get $1000$ with probability $0.50$, and $0$ with probability $0.50$, or is it something else?  If something else, then what?
Assuming independence and "all-or-nothing", the probability of winning nothing is $$(1-0.50)(1-0.23)(1-0.37)(1-0.61)(1-0.13) = 0.082297215$$
I wouldn't call that negligible.  If you do want to neglect it, the next possibility is that you just get $1000$ (i.e. just bid #1), which also has probability $0.082297215$.
Comment: You are correct. It's all or nothing with independence which is what prompted my original question. Thanks for a well reasoned answer. That gives me some more insight.

How to Sum Numbers With Probability


Metric spaces "$\iff$" proof

Question: Let $(A, d_1)$ and be a metric. Suppose $d_2: A \times A \rightarrow \mathbb{R}$ be defined in this way:
For $a, b \in A$, $d_2(a, b) = \frac{d_1(a, b)}{1 + d_1(a, b)}$.
Show that $E \subset A$ is open with respect to $d_1 \iff E$ is open with respect to $d_2$.
My friend and I's attempt:
Assume $E$ is open inside $(A, d_2)$. Let $x \in E$. We need $B_{\rho}^{d_1} \subset E$ for some $\rho > 0$. We know that there is some $r > 0$ so that $B_{r}^{d_2} \subset E$.
Choose $\rho = ?$ so that $B_{\rho}^{d_1} \subset B_{r}^{d_2}$. (Not sure what $\rho$ to choose).
In essence, we need $d_1(x, a) < \rho \implies d_2(x, a) < r$.
Going the other way, assume $E$ is open with respect to $(A, d_1)$. Then $d_2(a, b) = \frac{d_1(a, b)}{1 + d_1(a, b)} \leq d_1(a, b) < r$.
Not sure how to proceed from here.
QED.
Is this proof correct so far? We are new to metric spaces and tried to connect the dots as much as possible. Can somebody fill in the holes in the proof and explain it? Any assistance much appreciated.
Comment: First the easy direction. Let $E$ be open w.r.t. $d_2$. Let $x\in E$. Then there exists $r>0$ such that $B_r^{d_2}(x)\subset E$. Let us show that also $B_r^{d_1}(x)\subset E$. For this, let $y\in B_r^{d_1}(x)$. Then $d_1(x,y) < r$. What can we conclude for $d_2(x,y)$ and what follows from there?
Comment: @amsmath $B_{r}^{d_2} \subset B_{r}^{d_1} \subset E$?
Comment: I asked what we can conclude for $d_2(x,y)$.
Comment: @amsmath I'm not sure...
Comment: Well, then I'm sorry.
Comment: @Kraftsman: Given an $r>0$, you want a $\rho>0$ such that $0\le x<\rho$ implies that $\frac{x}{1+x}<r$. Clearly we may as well assume that $r<1$. Now $\frac{x}{1+x}<r$ if and only if $x<r+rx$, i.e., if and only if $x<\frac{r}{1-r}$.
Comment: @BrianM.Scott So choose $\rho = \frac{r}{1-r}$?
Comment: @Kraftsman: Yes, though you should verify that it really does work.
Comment: @BrianM.Scott Could you please check the updated solution? I have posted it as an answer. Is it correct?
Answer: I have replaced $a, b$ with $x, y$*
Proof.
Assume $E$ is open inside $(A, d_2)$. Then there is a $r > 0$ s.t. the open ball $B_2(x, r) = \{y \in A: d_2(x, y) < r\}$ is contained in $E$.
We need to show that for any $x \in E$, there is an $\rho > 0$ so that the open ball $B_1(x, \rho)  = \{y \in A: d_1(x, y) < \rho\}$ is contained in $E$.
Let $r < 1$ and set $\rho = \frac{r}{1 - r}$ then for $y \in B_1(x, \rho)$ we have
$$d_2(x, y) = \frac{d_1(x, y)}{1 + d_1(x, y)} < \frac{\rho}{1 + \rho} = r$$
So $y \in B_2(x, r)$ and so $B_1(x, \rho) \subset E$. Hence $E$ is open inside $(A, d_1)$.
The other way.
Assume $E$ is open inside $(A, d_1)$. Then there is a $\rho > 0$ s.t. the open ball $B_1(x, \rho) = \{y \in A: d_1(x, y) < \rho\}$ is contained in $E$.
We need to show that for any $x \in E$, there is an $r > 0$ so that the open ball $B_2(x, r)  = \{y \in A: d_2(x, y) < r\}$ is contained in $E$.
Set $r = \rho$ then for $y \in B_2(x, r)$ we have:
$$d_2(x, y) = \frac{d_1(x, y)}{1 + d_1(x, y)} \leq d_1(x, y) < \rho = r$$
So $y \in B_1(x, \rho)$ and $B_2(x, r) \subset E$. We may conclude $E$ is open inside $(A, d_2)$.
QED.

Metric spaces "$\iff$" proof