What's a superstrat?

Question: There's a stratocaster with SSS pickups or HSS pickups on Fender web. But some other manufactures made some guitar that they called a Superstrat. What really it is? Is it have a relation with a strat? Or is it a strat that super?
Answer: A superstrat is any guitar that is basically like a strat but has upgrades and extra features. Typical upgrades that make a guitar a superstrat include:

Upgraded tremolo (technically vibrato) unit - Floyd Rose is common
Upgraded electronics/pickups - HSH with coil tap is popular
Upgraded tonewoods - the body might be more of a Les Paul body made from mahogany with or without a maple cap and pickups mounted LP style
Upgraded neck  - usually with more frets (24 is common) and/or a more sophisticated truss rod, compound radius, and higher-end tone woods

When I hear "superstrat", my mind pictures something almost exactly like this.
Comment: a *true* superstrat has flashy colors or motifs :P
Answer: In the 80s, guitarists started experimenting with electronics, pickups (e.g. active pickups) and bridges (think the Floyd Rose) or scalloped fretboards to allow for easier access to extended techniques.
The Stratocaster being often the starting base, the result was called a "Super Strat".
In a way, the evolution of Superstrats is symbiotic with the rise of "shredders", starting with Eddie Van Halen, whose signature instrument is called the "Frankenstrat" and could very well be considered the prototypical Superstrat.
TL;DR: A Superstrat is your garden variety shredder guitar, meant for ultimate playability and popular with prog metal fans.
Comment: I agree when I hear the word Superstrat I immediately think of Eddy

What's a superstrat?


How do I find the period of repetition of this modular equation?

Question: EDITED QUESTION:
I have this equation $$\left(x+\frac{2}{3}\right)\,mod\, \frac{13}{5}$$
and I want to find period after which its value repeats.
It can be written as $$\left(\frac{3x+2}{3}\right)\,-\, \frac{13}{5}q = 0$$
I am equating it to some number (here I am equating it to zero to make the calculations simple), in order to find its period. And $q$ is the quotient of the mod process.
It can be simplified as $$15x+10=39q$$
It can be re-written as
$$(15x+10) \,mod \, 39$$
Its period is 39, but when I checked programmatically, its period is 13. I want the smallest interval as the period. Where is the mistake? Can someone help me?
Answer: First of all, your computations are exact : the smallest period is $36$.
It is of interest to make a zoom on a smaller part. We can observe:

that the curve is made of parabolic arcs, looking very irregular at this scale. Note that the range of values is $[0,1/3].$
that, there is a rather unexpected phenomenon ; the local (aka as "windowed") frequency is increasing till value 4.5 ; there is a big contrast between "just before" 4.5 and "just after", this value,  a little as if the "aperiodic behavior" is all concentrated before this value and a kind of "reset" is done once value $4.5$ has been crossed. A further analysis is necessary.

Matlab program that has generated the figure:

<code>x=35.:0.0001:37.5;
fr=@(x,y)(x-y.*floor(x./y));
u=fr(fr(9*x/4,(3/5)).*fr(2*x/3,3),1/3);
plot(x,u);
</code>
Comment: I don't think you zoomed out far enough. The stated period is 36 and your graph only goes to 2.
Comment: @Parcly Taxel You are right, I just noticed my error...
Comment: I have updated the graphics and the text.
Comment: @JeanMarie This method works except when there is a minus in numerator of mod operator right? I mean, something like ((9-x) % 2). Periodicity gets changed at x = 9. For all other complex cases it works I guess. Right ? – user3219492 48 mins ago
Comment: I have seen that the phenomenon occurs at a submultiple (4.5) of the period. I have modified my text in this direction.
Comment: About the questions you are asking, I will think about them.
Comment: @JeanMarie yes there is a change at 4.5 as you say but that doesn't affect the answer 36 right? The period as per the calculation matches the correct answer, right?
Comment: @JeanMarie I have edited the question now. For (x+(2/3))%(13/5) it does not seem to work
Comment: I confirm : the period of the function in your question is 36.
Comment: The thing is, the method I followed doesn't seem to work properly. And the posted thing doesn't seem to be the answer to my question (to my before and after edit question). Seems like there is a bug in my method. And that is what I asked help for. Not to verify the period as 36. So only I didn't click "ACCEPT BUTTON". Anyways thanks alot for all your time :)
Comment: Correct. Yes I have spent time of it, but with a great pleasure: your question is intriguing and interesting, and I thank you for it.


Laravel Update With Relationships - Boa prática

Question: Criei um Update para uma tabela Produtos que está relacionada com outra tabela que é o Artigo(product_info) desse produto.
Só que quando faço Update eu altero as informações do Produto, apago o artigo e volto a criar um artigo com o mesmo ou novo conteúdo.
Está tudo a funcionar perfeitamente mas queria saber se é uma boa prática de programação ou se existe outro modo.
Basicamente é isto:
Controller:
$product = Product::find($id);
$product->display_name = Input::get('name_display');
$product->save();

$product->Product_info()->delete();

$product_info = New Product_info;
$product_info->name = Input::get('name');
$product_info->description = Input::get('description');
$product_info->Product()->associate($product);
$product_info->save();

Model: Produto.php
public function Product_info()
{
    return $this->hasOne('App\Product_info');
}

PS: Se não fui explicito avisem.
Comment: eu não deletaria `Produto_info()`, eu usaria a mesma instância e salvaria as novas informações, ou seja, *update*!
Comment: @VirgilioNovic O problema é que já tentei de várias formas e esta foi a única que não me deu problemas.
Comment: os dados da relação são obrigatórios? se existir product existe também product_info?
Comment: bom qualquer coisa poste o layout das tabelas se a resposta não der certo e o layout completo do model `Produto` e `Product_info`.!
Answer: Utilizaria a mesma instância, $produto->Product_info() se existir, se não, eu criaria o que você está fazendo.
$product = Product::find($id);
$product->display_name = Input::get('name_display');
$product->save();

$product_info = $product->Product_info();
if (!$produto_info)
{
    $product_info = New Product_info;
    $product_info->Product()->associate($product);
}
$product_info->name = Input::get('name');
$product_info->description = Input::get('description');
$product_info->save();

Se a relação for obrigatória na hora do cadastro, ou seja, é feito o registro de product e product_info pode usar um update:
$product = Product::find($id);
$product->display_name = Input::get('name_display');
$product->save();

$product->Product_info()->update([
    'name' => Input::get('name'),
    'description' => Input::get('description')
]);

Comment: Obrigado, desconhecia a function update()! Acho que fica melhor dessa maneira!


TypeScript: plugin:prettier/recommended for eslint, unable to use the override keyword

Question: Package versions:
email@example.com
firstname.lastname@example.com
firstname.lastname@example.com

I've got the following eslintrc, which is just the stock config from NestJS:
module.exports = {
  parser: '@typescript-eslint/parser',
  parserOptions: {
    project: 'tsconfig.json',
    sourceType: 'module',
  },
  plugins: [
    '@typescript-eslint/eslint-plugin',
    'filenames'
  ],
  extends: [
    'plugin:@typescript-eslint/recommended',
    'plugin:prettier/recommended',
  ],
  root: true,
  env: {
    node: true,
    jest: true,
  },
  ignorePatterns: ['.eslintrc.js'],
  rules: {
    '@typescript-eslint/interface-name-prefix': 'off',
    '@typescript-eslint/explicit-function-return-type': 'off',
    '@typescript-eslint/explicit-module-boundary-types': 'off',
    '@typescript-eslint/no-explicit-any': 'off',
    'filenames/match-regex': [2, "^[0-9a-z-.]+$", true]
  },
};

This is the prettier config:
{
  "singleQuote": true,
  "trailingComma": "all"
}

And this is the tsconfig:
{
  "compilerOptions": {
    "moduleResolution": "node",
    "module": "commonjs",
    "esModuleInterop": true,
    "declaration": true,
    "removeComments": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "allowSyntheticDefaultImports": true,
    "target": "es2017",
    "sourceMap": true,
    "outDir": "./dist",
    "baseUrl": ".",
    "rootDir": ".",
    "incremental": true,
    "resolveJsonModule": true,
    "skipLibCheck": true,
    "strictNullChecks": true,
    "noImplicitAny": true,
    "strictBindCallApply": true,
    "forceConsistentCasingInFileNames": false,
    "noFallthroughCasesInSwitch": true,
    "noImplicitThis": true,
    "noUnusedLocals": true,
    "noImplicitReturns": true,
    "noImplicitOverride": true
  }
}

In my code, I have a class like this:
@Injectable()
export class FirebaseStrategy extends PassportStrategy(
  FirebaseAuthStrategy,
  'firebase',
) {
  constructor(private usersService: UsersService) {
    super({ extractor: ExtractJwt.fromAuthHeaderAsBearerToken() });
  }

  override async validate(payload: FirebaseUser): Promise<User | undefined> {
    return this.usersService.findByFirebaseUid(payload.uid);
  }
}

This code runs fine, but when I try to lint, I get the following error:
/app/src/auth/strategy/firebase.strategy.ts
  22:12  error  Parsing error: Unexpected token  prettier/prettier

Is there a way to fix this? I'd prefer not to have implicit overrides.
Comment: I'm not doing anything, this is nestjs default configuration: https://github.com/nestjs/nest/blob/master/.eslintrc.js and is the recommended config for esplugin-plugin-prettier: https://github.com/prettier/eslint-plugin-prettier/blob/master/README.md?plain=1#L73
Comment: Can you please add .prettierrc & tsconfig.json?
Comment: @LongNguyen added, thanks for looking.
Comment: why you adding `prettier/recommended` to extend instead of plugin list?
Answer: It looks like you need to update prettier to any version after 2.3.1 - support was added in that release for TypeScript 4.3 features like the override keyword. You can update this in package.json or use npm i -D prettier@^2.3.1 (assuming you're using npm as your package manager).
Comment: Sorry, I wouldn't know then other than trying to update all pretter/eslint packages
Comment: I have prettier "^2.3.2" in my pakcage.json, guess that is not it


ssh "WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!"

Question: I've been using ssh to log-in to a remote server I rent for several years. Last week I got a message from them saying they upgraded my account and server. Now when I go to login, I get this message from ssh
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@       WARNING: POSSIBLE DNS SPOOFING DETECTED!          @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
The RSA host key for mydomain.com has changed,
and the key for the corresponding IP address X.X.X.X
is unknown. This could either mean that
DNS SPOOFING is happening or the IP address for the host
and its host key have changed at the same time.
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
@    WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED!     @
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
IT IS POSSIBLE THAT SOMEONE IS DOING SOMETHING NASTY!
Someone could be eavesdropping on you right now (man-in-the-middle attack)!
It is also possible that the RSA host key has just been changed.
The fingerprint for the RSA key sent by the remote host is
XXxXXXXXXX
Please contact your system administrator.
Add correct host key in /home/myaccount/.ssh/known_hosts to get rid of this message.
Offending key in /home/myaccount/.ssh/known_hosts:7
RSA host key for mydomain.com has changed and you have requested strict checking.
Host key verification failed.

Now, I assume that this has been triggered by my host upgrading my server. So I want to trust this site again. But I can't quite see how.
I looked in known_hosts and all there are there are public-keys. But I can't tell which of these comes from the old version of this particular server. Nor do I know how to get a correct key for the host; the previous time I made contact, I think ssh just confirmed with me and automatically saved it. Now it says I've requested strict checking, but I have no idea when I did this or where to reset it.
Answer: The line:
Offending key in /home/myaccount/.ssh/known_hosts:7

indicates that the old key is on line 7 of your known_hosts file.  Use your favourite editor to delete line 7.   That should make it go away.
You can also use ssh-keygen -R to remove a entry:
# ssh-keygen -R hostname -f ~/.ssh/known_hosts

FYI, those are not public keys but a hashed representation of the hosts.
You can list the known hosts file with:
$ ssh-keygen -lv -f ~/.ssh/known_hosts

It will then display the key and ascii art representation:
2048 0f:3b:8a:02:75:f1:68:0f:32:8a:7a:0f:ef:69:f8:a0 |1|aa3F96t0nzhqLpt+lJx4msNAGQI=|740B4+NTrQhAx/DWXHf6QLrBpz8= (RSA)
+--[ RSA 2048]----+
|                 |
|  .              |
|   =             |
|o * .            |
|o= o    S        |
|+   .    +       |
|..o.    o .      |
|..++.o . .       |
|E. *B .          |
+-----------------+

In theory you print this out and keep it in a safe place.  When something suspicious happens you have a copy for reference.
Comment: See note from Matt below about double checking with the hosting provider.
Answer: I'm going to just add that before taking the advice of my esteemed fellow serverfaulties and erasing the line from your known_hosts file, you should talk to customer service at the other end and make sure that they did do something that would have caused this key change.
Comment: yes, good point :-)
Answer: You'll need to edit your /home/myaccount/.ssh/known_hosts file and remove the entry that matches the IP address or hostname of your old server.  Afterwards, you should just ssh to your server like you normally do and it will prompt you with a new key and ask if you want to add it.  Simply say 'yes' and that's that! :)  It shouldn't ask you again unless something has changed.
Hope that helps.
EDIT: your known_hosts entry would most likely look something like this
[hostname or IP address] [keytype, generally ssh-rsa] [key here, i.e. ASDFJAKj3klje35u9086095468kjflADf...]
Comment: thanks, Glen and Zoredache. It's exactly Zoredach's problem I had.
Comment: If HashKnownHosts is enabled then the ip address/hostname will not be readable in your known_hosts.  If that is the case the line number reported by the ssh client is about the only thing you have to work with.
Comment: Hugely upvoted answers didn't work for me but this did.


Como acessar os SQLs dos updates feitos pelo orm:schema do Doctrine?

Question: Estou com uma aplicação rodando em um servidor (produção) que não dá permissão de acesso ao ../vendor/bin/doctrine e por isso não consigo rodar os comandos, como o orm:schema-tool:update, por exemplo. Estou executando os comandos no meu ambiente de desenvolvimento, normalmente.
Como faço para acessar os comandos executados pelo orm:schema para que eu possa rodá-los corretamente em meu ambiente de produção, simulando a ação do próprio ORM e mantendo os bancos devidamente pareados?
Answer: Ao invés de acessar o comandos do executável ../vendor/bin/doctrine, você pode criar um script, acessível via web (claro, com alguma autenticação necessária) para fazer o que precisa.
Veja essa seção na documentação do Doctrine.
Resumidamente, basta instanciar o SchemaTool passando seu EntityManager como argumento, e chamar o método updateSchema passando as classes de sua aplicação como argumento:
<?php

$tool = new \Doctrine\ORM\Tools\SchemaTool($em);

$classes = array(
  $em->getClassMetadata('Entities\User'),
  $em->getClassMetadata('Entities\Profile')
);

$tool->updateSchema($classes);

Comment: Grato @Rodrigo Rigotti


How to save PDF file on Sdcard created using iText?

Question: I am using iText library to create a pdf file from given string. But how can i save this document file to external storage ?
        Document document = new Document();
        fileName = "Hello" + ".pdf";
        PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();
        document.add(new Paragraph("Hellooo"));
        document.close();

What should i do after it to save this document to external storage ?
Answer: Have fileName point to a location on external storage, rather than be "Hello" + ".pdf".
You can access your own app's specific spot on external storage via getExternalFilesDir(), called on your Activity or other Context. Or, you could consider storing the file in a common location, such as those available from getExternalStoragePublicDirectory() on Environment.
Most likely, you will need to hold the WRITE_EXTERNAL_STORAGE permission, by having a <uses-permission> element for it in the right spot in your manifest. If your minSdkVersion is 19 or higher, and you are using getExternalFilesDir(), you will not need this permission.


Weierstrass continuity vs sequential continuity

Question: The real function $f(x)$ defined so that $f(x)=x$ when $x \in \mathbb{Q}$ and $f(x)=1 $ when  $x \notin \mathbb{Q}$ is Weierstrass continuous.
But, it doesn't have sequential continuity. If you try the sequence $(x_n)$ of rationals that converges to $\pi$ or any real number $c$ for that matter, you realize that there's no $N$ that's large enough so that $\forall \epsilon > 0, |f(x_N)-c|<\epsilon$ where $c$ is considered the limit of that particular sequence.
So, it appears that Weierstrass continuity doesn't imply sequential continuity.
Comment: Yes, it's the $\epsilon-\delta$ definition of continuity. Why do you say it's wrong? $\mathbb{Q}$ is dense in $\mathbb{R}$
Comment: What's the definition of Weierstrass continuous you are using? If it's the classical $\epsilon$-$\delta$-continuity then the assertion does not hold.
Answer: Your function isn't continuous (except at $1$).
Weierstrass continuity is the same thing as sequential continuity in first-countable spaces (thus in metric spaces in particular, and more specifically, in $\mathbb R$ with the usual metric).
However, in general topological spaces, the two are not the same thing: a W-continuous function is necessarily sequentially continuous, but the converse isn't necessarily true (and that's why in general topological spaces we use the notions of nets instead of sequences).
Anyway, the final answer to your question is: W-continuity always implies sequential continuity, but not the other way around.
Comment: Ok. I thought about it more, tried epsilon equals 1, and I realize that I was wrong...


How to disable browser back button after logout in JSP?

Question:
Possible Duplicate:
Restrict user from accessing the previous page after signout

Am developing a JSP application in netbeans 6.5.1. I need to disable browser back button after login as well as log off. How is it possible?
Answer: There's nothing you can do in JSP to directly influence that browser's back button.  Your JSP markup/code is all evaluated server-side as part of generating the response that is set to the client.
That said, you can add the following JavaScript to the  section of the post-logoff page to accomplish roughly the desired effect:

Source:  http://answers.google.com/answers/threadview/id/574062.html
More generally, however, there's nothing you can do to prevent a determined user from finding a previously visited URL in their history and pointing their browser to it after logging out.  Instead your session-management code needs to be robust enough to know that it should not service a request for a stale URL if the user no longer holds a valid session.
Or, if what you're really trying to do is prevent the browser from displaying a cached version of a post-login page after a user has logged out, you can accomplish that (in most browsers) by setting an HTTP Cache-Control header with a value of no-cache on all of your post-login pages.
Comment: Thank you... Will try now and ping you back.


$1 + \frac{1}{3}\frac{1}{4} + \frac{1}{5}\frac{1}{4^2} + \frac{1}{7}\frac{1}{4^3} + ..........$

Question: $1 + \frac{1}{3}\frac{1}{4} + \frac{1}{5}\frac{1}{4^2} + \frac{1}{7}\frac{1}{4^3} + ......$
Can anyone help me out how to solve this.
My try : I was thinking about the expansion of $tan^{-1}x$. But in that series  positive and negative will come alternatively.
Comment: Another one: https://math.stackexchange.com/questions/580143/evaluate-1-frac13-frac14-frac15-frac142-frac17-frac – both found instantly with [Approach0](https://approach0.xyz/search/?q=%241%20%2B%20%5Cfrac%7B1%7D%7B3%7D%5Cfrac%7B1%7D%7B4%7D%20%2B%20%5Cfrac%7B1%7D%7B5%7D%5Cfrac%7B1%7D%7B4%5E2%7D%20%2B%20%5Cfrac%7B1%7D%7B7%7D%5Cfrac%7B1%7D%7B4%5E3%7D%20%24&p=1)
Answer: $$\sum_{r=0}^\infty\dfrac1{(2r+1)}\left(\dfrac12\right)^{2r}=2\sum_{r=0}^\infty\dfrac{x^{2r+1}}{(2r+1)}$$ where $2x=1$
Now $-\ln(1-x)=\sum_{n=0}^\infty\dfrac{x^n}n$ for $-1\le x<1$
$\ln(1+x)-\ln(1-x)=?$
Alternatively, $$\sum_{r=0}^\infty\dfrac{x^{2r+1}}{(2r+1)}=\int\sum_{r=0}^\infty(x^2)^rdx$$
Comment: Which is more or less your answer https://math.stackexchange.com/a/580148/42969 to an older question :)
Comment: khubbbb bhalo @lab bhattacharjee
Comment: @MartinR, Thanks for searching out. I've voted for Duplicate
Answer: A different approach would be to use binomial theorem . Consider the series expansion of $\ln (\frac {1}{1-x}),\ln (\frac {1}{1+x})$ using binomial expression for negative index we have $\ln (\frac {1}{1-x})-\ln (\frac {1}{1+x})=2 (x+\frac {x^3}{3}+\frac {x^5}{5}+.. ) $ now pull out $x $ common from $RHS $ and put $x=\frac {1}{2} $ thus we have $\frac {1}{2x}\ln(\frac {1}{1-x})-\ln(\frac {1}{1+x})=S $ thus $S=\ln (3) $
Comment: did you mean "series expansion of $\ln (\frac{1}{1-x})$ and $\ln (\frac{1}{1+x})$", because the answer must be $\ln 3$?
Comment: Oh yes i made a mistake
Comment: It is ok. Two more points: 1) although it doesn't affect the final result, in the last part $1/2x$ is missing. 2) I am afraid your method repeats the previous method. Luck.


Is it possible to load and automatically play a project in Reaper?

Question: I'm working on an art installation which features Unity, VR and Reaper. Ideally I'd like to be able to start Reaper, load a project and start it playing from the command line.
I don't have much experience with Reaper, but given its popularity and quality I'm hoping that some faculty for this exists in the program.
Comment: tbh, for an installation I'd be looking towards 'video of one I played earlier'… Blue Peter style.
Comment: You might be able to do this using reaper keyboard commands and some kind of macro made from operating system tools. There might be a better stack for that approach, depending on the OS.
Answer: I don't think you can. At least the command line options don't mention anything  about playback: https://github.com/ReaTeam/Doc/blob/master/REAPER-CLI.md
But maybe that's not really what you want, i.e. why do you want to play a reaper project and not a sound file ?
Comment: @ToddWilcox  yeah sure, there could be all kinds of reasons, but sometimes people are too focused on a specific direction they don't realise there are completely different possibilities. But we'll only know when we know what exactly he tries to achieve
Comment: From my audio engineer - "We want to play a Reaper project instead of a sound file because our output is a custom multi-channel speaker array and we have a lot of control over channel routing in Reaper...!"
Comment: One reason why a regular sound file might not work could be the need for multi channel audio in a way not supported by consumer audio formats.
Answer: For playback, after loading reaper with the project/clip just send a spacebar keypress for "play." (Maybe after sleeping for a few seconds, if the keypress gets invoked before reaper has the track loaded and ready.) No need for any Reaper API stuff for something that the script can accomplish in one line.
To run reaper on CLI with a project or audio file loaded, looks like that's just <code>/path/to/reaper.exe /path/to/audio.wav</code>


Improving convergence with compactness criterion

Question: Let $(X, \tau)$ be a Hausdorff topological space and $x_n \to x$ in $(X, \tau)$. Let $\tau' \supseteq \tau$ be a finer topology such that $\{ x_n \mid n \in \mathbb{N} \}$ is relatively compact for $\tau'$. Does it follow that $x_n \to x$ in $(X, \tau')$?
Comment: Welcome to MSE. Please read this text about [how to ask a good question](https://math.meta.stackexchange.com/questions/9959/how-to-ask-a-good-question).
Comment: Shouldn't $x$ be added to the set?
Comment: @HennoBrandsma Even when forcing relative compactness?
Comment: If $x$ is not in the set it cannot be compact in $\tau$ let alone in $\tau'$. So the assumption forces $x \in \{x_n : n \in \Bbb N\}$. But I think it should be explicit I think.
Comment: @HennoBrandsma $\{ x_n \mid n \in \mathbb{N} \}$ relatively compact for $\tau'$ means that closure of this set in $(X, \tau')$ is $\tau'$-compact or equivalently, that $\{ x_n \mid n \in \mathbb{N} \}$ is contained in some $\tau'$-compact subset of $X$.
Answer: Yes, this is true. There is a subnet of $(x_n)$ converging to some point $y$ w.r.t. $\tau'$. This subnet also converges to $y$ w.r.t. $\tau$. Since $(X,\tau)$ is Hausdorff we get $x=y$. No we can repeat this with any subnet of $(x_n)$ to see that every subnet has  further subnet converging to $x$. This implies $x_n \to x$ in $\tau'$.
Comment: Thank you. An interesting alternative approach to circumvent relative sequential compactness of $\{ x_n \mid n \in \mathbb{N} \}$.


Stuck on C++ functions and arrays

Question: #include <iostream>
using namespace std;

const int monkeys = 3;
const int weekdays = 7;
double monkeyWeek[monkeys][weekdays];
double largest;
double least;
double average;
int index;
int dayCount;
double amount;

double amountEaten(double[] [weekdays], int);
double mostEaten (double[] [weekdays],int);
double leastEaten (double[][weekdays], int);

int main(){
cout << "Ch 7-4 Monkey " << endl;
cout << "Created by Aaron Roberts" << endl;

double mostBananas (double[] [weekdays],int);
double leastBananas (double[][weekdays],int);
//double bananaAverage (double[][weekdays], int);

}

double amountEaten(double array[] [weekdays], int){
    cout << "Please enter the amount of food eaten per monkey per day." << endl;
double amount = array[0][0];
for (index = 0; index < monkeys; index++)
{
    for (dayCount = 0; dayCount < weekdays; dayCount++)
    {
    cout << endl <<"Please enter the amount of pounds eaten by     monkey"
        <<(index +1)
            << endl << "for day " << (dayCount +1) << ": ";
        cin >> monkeyWeek[monkeys] [weekdays] ;
        if (monkeyWeek[monkeys] [weekdays] < 1)
            cout << endl <<"Must feed positive amount" << endl;
    }

}
}

double mostEaten( double array[] [weekdays], int size)
{
double largest = array[0][0];
for (int count = 0; count < size; count++)
{
    for (int col = 0; col < count; col++)
    {
        if (array[count][weekdays] > largest)
            largest = array[count][weekdays];
    }
}
return largest;
}

double leastEaten(double array[] [weekdays], int size)
{
double least = array[0][0];

for (int count = 0; count < size; count++)
{
for (int col = 0; col < size; col++);
{
if (array[count][weekdays] < least)
least = array[count][weekdays];
}
}
return least;
}

This project requires the utilization of a 2 dimensional array to store the pounds of food eaten by 3 monkeys each of the seven days of the week.
Create a function to obtain the pounds eaten for each monkey, each day of the week.
Create a second function to determine pass through the array to calculate the total all of the moneys ate, and then the average eaten on one day.  (Some of you interpretted this as sum all values, then divide by number of values.  Others interpretted this as summing the values for each day and calculating the average for that day.  So, there would be 7 lines of output, not just one.)
Create a third function to determine which monkey ate the least amount of food and on what day.  Also output the amount the monkey ate on that day.
Create a fourth function to determine which monkey ate the most amount of food on a single day.  Output the monkey number, the pounds eaten, and the weekday.
I'm new at c++ and stuck and don't really know how to complete this. Thanks for any help i really appreciate it.
Comment: Explain what you've achieved so far and what's wrong with it. This will make it much easier for others to help.
Comment: Hi and welcome to StackOverflow. S.O. is not here to do your homework for you. Try to reduce your problem to where exactly you're stuck instead of dumping your complete implementation and the original task.
Comment: I don't get how this has received a +1. "This question shows research effort; it is useful and clear.". It neither shows research effort nor it is useful or clear.
Comment: There's also an [obvious duplicate question](http://stackoverflow.com/questions/13281089/c-cant-figure-out-arrays-and-functions) created 20 minutes later under a different SO account.
Answer: You keep doing this sort of thing:
for (int count = 0; count < size; count++)
{
    for (int col = 0; col < count; col++)
    {
        if (array[count][weekdays] > largest)
            largest = array[count][weekdays];
    }
}

See you are using weekdays to index your array.  But that index is invalid.  It might sort-of work, but will always return the first element of the next row (and then have more definite undefined behaviour on the last row).
I'm pretty sure you meant to use col instead of weekdays here.
As WhozCraig pointed out in the comments, you probably need to loop over the entire weekdays range too.  Here is a slightly repaired loop:
for (int count = 0; count < size; count++)
{
    for (int col = 0; col < weekdays; col++)
    {
        if (array[count][col] > largest)
            largest = array[count][col];
    }
}

Similarly for everywhere else you've done this...
Comment: +1: And I'm pretty sure the col-for-loop should be from 0 to weekdays.
Comment: Thanks for that - have edited accordingly...  I didn't really think about the logic of the loop, just noticed the obvious no-no. =)

Stuck on C++ functions and arrays


.htaccess add an extra word to add all my URLs

Question: I need to a add a extra word right after my domain name to all my website URLs.
Lets say my url is http://www.example.com/somecategory/someproduct.html, it should be http://www.example.com/logado/somecategory/someproduct.html.
Is it possible to do it with .htaccess file ?
If so what should i add to my .htaccess file ?
Answer: You can use this code in your DOCUMENT_ROOT/.htaccess file:
RewriteEngine On
RewriteBase /

# prefix each URL by /logado/ if it is not present
RewriteCond %{THE_REQUEST} !\s/+logado/ [NC]
RewriteRule ^ logado%{REQUEST_URI} [R=302,L,NE]

# internally remove /logado/ from all URLs
RewriteRule ^logado/(.*)$ $1 [L,NC]


How to use check box in select list for multiple selection in content type?

Question: I simply want a select list like this.
Is there any options to add a field like this.
Answer: You can simply achieve that by following way.
Choose Field Widget Type 'Checkbox' instead of Select list.
If you want to make appear checkboxes field as multiple select list,Add the following line in your CSS file
   #field-id-name{ height: 100px; overflow: auto; width: 100px;  }

Note: replace field-id-name with id name of the field; change the width and height according to your requirement.
After applying CSS, the checkbox list field in content type appears as follows.

I hope this simple solution helps
Comment: It works fine sir:)
Comment: Sure sir.Its useful for me:)
Answer: Try Dropdown Checkboxes module

This module helps to convert multiple select lists into dropdown checkboxes using ddcl library.
Comment: I enabled this module..But it have an option as like before
Comment: Follow README.txt under module directory. This requires ddcl library.
Comment: I have one more doubt sir.Where I should put ddcl library..Have to put inside the Dropdown Checkboxes module ah..
Comment: No,Place that under sites/all/libraries and rename the extracted library to ddcl
Comment: actually library module is there..but ddcl contains cc,js,doc,src folder..where it should be put?
Comment: sorry sir..I got it
Comment: But still  I didn't get what i expected.
Comment: @Dhivya I've posted another answer below. I hope it helps. I've tested in on my local and works great!


Express routes and middleware

Question: I'm using a role authorisation (connect-roles), and trying to add more than one role for each route. This is using express, and monogoose. Here is the code I currently have:
 router.get('/admin/:slug', function (req, res) {

   if (user.can('vip')) {

     adminController.showVipView // <-- this is what I need to work

   } else {

     // call a different view

   }

});

This is how it normally works without the if statement. This seems like super basic express, but I just cannot get it to work.
router.get('/admin/:slug', user.can('vip'), adminController.showVipView);

Answer: Just pass request and response into it:
adminController.showVipView(req, res);

It might also requires the next callback, then you should pass that into it too...
By the way, your if statement wont work either as it returns a middleware. Might do this:
user.can('vip')(req, res, function(){
  adminController.showVipView(req, res);
});

Express routes and middleware


Dropdown hover funcionar apenas acima de 1200px

Question: Se alguém puder me ajudar, preciso que o JavaScript do hover funcione apenas na resolução acima de 1200px, fiz o código mas não tá dando certo.
$(function() {
    if($(window).width() > 1200) {
        $('ul.nav li.dropdown').hover(function() {
                $(this).find('.dropdown-menu').stop(true, true).delay(100).fadeIn(400);
            },
            function() {
                $(this).find('.dropdown-menu').stop(true, true).delay(100).fadeOut(400);
            });
    }

});

Answer: $(document).ready(function(){
    if($(window).width() > 1200) {
        $('ul.nav li.dropdown').hover(function() {
                $(this).find('.dropdown-menu').stop(true, true).delay(100).fadeIn(400);
            },
            function() {
                $(this).find('.dropdown-menu').stop(true, true).delay(100).fadeOut(400);
            });
    }

});

Se vc quiser usar enquanto vc redimensiona o window, então va iter que usar o jquery resize
Answer: Você pode fazer a verificação dentro da função do hover, e se for verdadeiro não faz nada, veja o código:

var $meuLink = $('#meuLink');
var $divMostrarOcultar = $('#divMostrarOcultar');

$meuLink
  .on('mouseover', function() {
    var tamanhoJanela = $(window).width();
    if (tamanhoJanela > 1200)
      return;

    console.log('A janela tem ' + tamanhoJanela + 'px');
  })
  .on('mouseout', function() {
    var tamanhoJanela = $(window).width();
    if (tamanhoJanela > 1200)
      return;

    console.log('A janela tem ' + tamanhoJanela + 'px');
  });

Passe o mouse

Conteudo a mostrar/ocultar

Nesse caso, se a janela for maior que 1200 não irá fazer nada, mas caso seja menor ou igual irá imprimir no console do navegador o tamanho da janela.
Apenas uma observação ao seu código, prefira utilizar .on('event' ao invéz de utilizar o evento diretamente. Veja nessa resposta o motivo.
Agora como poderia ficar em seu código:
$('ul.nav li.dropdown')
  .on('mouseover', function() {
    if (janelaMaiorQue(1200))
      return;

    $(this).find('.dropdown-menu').stop(true, true).delay(100).fadeIn(400);
  })
  .on('mouseout', function() {
    if (janelaMaiorQue(1200))
      return;

    $(this).find('.dropdown-menu').stop(true, true).delay(100).fadeOut(400);
  });

function janelaMaiorQue(tamanho) {
  var tamanhoJanela = $(window).width();

  return tamanhoJanela > tamanho;
}


CSS: Border Radius

Question: Estou fazendo um projeto onde estou usando o border radius para fazer um menu vertical.
Gostaria que o Menu ficasse com a border radius reta, desta forma arredondada :

E atualmente está ficando desta forma:

.teste{
 height:12%;
 width:65%;
 background-color: rgb(56, 66, 65);
 opacity:0.5;
 position:absolute;
 margin-left:30%;
    border: 2px solid red;
 border-bottom-left-radius: 250px 170px;
}
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Menu Vertical</title>

Como faço para ficar reta?
Comment: Possível duplicata de [Como fazer botão Inclinado?](https://pt.stackoverflow.com/q/56819/3635) e [Criação de div diagonal](https://pt.stackoverflow.com/q/238393/3635)
Comment: E a parte de cima, como é?
Comment: Atualmente estou tentando fazer somente a div como a forma da imagem, ao invés de ficar meio arredondada, ficar ponte-aguda (como uma espada)
Comment: Dê uma olhada nisso: https://pt.stackoverflow.com/questions/109200/criar-bot%C3%A3o-com-borda-octagonal-usando-somente-html-e-css
Comment: Bom dia! encontrei esse site aqui, ja da pra tirar uma ideia: http://www.howtocreate.co.uk/tutorials/css/slopes
Comment: @Sora eu estou tentando aplicar o princípio dessa pergunta na sua resposta: [O que significa / no border-radius](https://pt.stackoverflow.com/questions/101324/o-que-significa-a-barra-no-border-radius)
Answer: Não é com border-radius, pois radius = raio, ou seja essa propriedade cria um raio de curvatura nos vértices da div por isso fica arredondado.
Mas com um pseudo-elemento e skewX() vc consegue.

.teste{
 height:12%;
 width:65%;
 background-color: rgb(56, 66, 65);
    color:#ddd;
 position:absolute;
 margin-left:30%;
    padding-left: 50px; /* mesma largura que o elemento after */
    border: 2px solid red;
    border-top: none;
    border-right: none;
    box-sizing:border-box;
}
.teste::after {
    content: '';
    position: absolute;
    height: 100%;
    width: 50px;
    background-color: rgb(56, 66, 65);
    top: 0px;
    left: -25px;
    border: 2px solid red;
    border-top: none;
    border-right: none;
    transform: skewX(25deg);
}

Comment: Vou estudar este código @hugocsl, muito obrigado !! perfeito
Comment: O que significa o ::after
Comment: @Sora então MUITO resumidamente um ::after é um pseudo-elemento, são elemento construídos no CSS, eles não são tags html, o assunto é um pouco extenso, mas não é difícil de entender. Vou te indicar um artigo que vale a pena parar 15min pra dar uma olhada, vai ser mais didático do que eu tentar explicar aqui no comentário rss, da uma olha aqui que vai abrir sua cabeça https://www.devmedia.com.br/css-conheca-os-pseudo-elementos/38183
Comment: Vou ler, obrigado !!

CSS: Border Radius


PDFtk throws a Java Exception when attempting to use 'fill_form' function

Question: I have a PHP application that fills out a form from a database call. At present I am putting this together using PDFtk, I am able to run a number of PDFtk commands with no issue and I am currently working out the desired command at command line.
My call is currently this:
pdftk /var/www/html/CSR/template/job_card.pdf fill_form /var/www/html/CSR/template/wwwwu7mMH.fdf output /var/www/html/CSR/template/filled4.pdf

This exact call run multiple times generates this error sometimes:
    Unhandled Java Exception in create_output():
java.lang.ClassCastException: pdftk.com.lowagie.text.pdf.PdfNull cannot be cast to pdftk.com.lowagie.text.pdf.PdfDictionary
   at pdftk.com.lowagie.text.pdf.FdfReader.readFields(pdftk)
   at pdftk.com.lowagie.text.pdf.FdfReader.readPdf(pdftk)
   at pdftk.com.lowagie.text.pdf.PdfReader.<init>(pdftk)
   at pdftk.com.lowagie.text.pdf.PdfReader.<init>(pdftk)
   at pdftk.com.lowagie.text.pdf.FdfReader.<init>(pdftk)

and this error sometimes:
Unhandled Java Exception in create_output():
Unhandled Java Exception in main():
java.lang.NullPointerException
   at gnu.gcj.runtime.NameFinder.lookup(libgcj.so.10)
   at java.lang.Throwable.getStackTrace(libgcj.so.10)
   at java.lang.Throwable.stackTraceString(libgcj.so.10)
   at java.lang.Throwable.printStackTrace(libgcj.so.10)
   at java.lang.Throwable.printStackTrace(libgcj.so.10)

The error message alternates but the command never works and the form is never filled. As I say though, the PDFtk works with other commands, I have been able to generate encrypted PDFs and run the fixed commands succesfully.
My question is what is causing this error and how do I fix it?
Answer: I see my name in the StackTrace. That's not a coincidence: PdfTk is based on a mighty old version of iText. iText is a Java PDF library that was originally written by me, but used by a third party to create PdfTk.
The error tells you that iText is parsing a PDF that has either an error, or an unexpected feature.
A PDF consists of PDF objects such as PDF string objects, PDF number objects, PDF array objects, PDF dictionary objects, PDF stream objects, and so on. iText is able to retrieve these objects and to reuse them to create a new PDF. In your case, a new PDF with some form fields that are filled out is created based on the objects of the original PDF.
It is impossible to answer your question without seeing the PDF that causes the problem, but let's say that your PDF contains an /AcroForm entry with a /Fields array. In this fields array, there is a reference to a field dictionary. Suppose that one of the field dictionaries in your PDF isn't a dictionary, but a PDF null object. The form shows up perfectly in Adobe Reader, but internally, there is a flaw that prevents proper processing of the form.
In that case, iText will loop over the entries in the fields array, and one of those entries won't return a field dictionary, but a PdfNull object. In that case, you'll get a ClassCastException, because you can't cast PdfNull to PdfDictionary.
This being said:

If I see my name in your stack trace, this triggers an alarm, because it means that you're using an iText version that predates iText 5. Such a version should no longer be used. You should use a more recent version of iText. There is a high chance that a more recent version of iText gives you either a better error message, or tolerates (and maybe even fixes) the error in the PDF.
If you find a PdfTk version that uses a more recent version of iText, that would surprise me, because as far as I know, PdfTk isn't available under the AGPL, nor is PDF Labs (the owner of PdfTk) a customer of iText Software.
If you want to keep on using PdfTk, you shouldn't expect an answer as long as you don't share the PDF document that you're trying to fill.

One thing you could try: open the form in Adobe Acrobat. Save the form in Adobe Acrobat. There is a chance that the saved form no longer has the problem. Adobe Acrobat is very tolerant towards errors in PDFs. It tries to fix as many as it can. Then when you save the form, the error is gone.
Comment: Hi Bruno, I really appreciate you taking the time to give the explanation. I am happy to link to the PDF but it sounds like you have a very clear idea of what the problem is. The form I need to populate won't change and there are no options for users to add their own forms, as such perhaps it is easier to generate the form using a different method to bypass this issue?
Comment: Yes. If you shared the form, the first thing I would try is this: open the form in Adobe Acrobat. Save the form in Adobe Acrobat. There is a chance that the saved form no longer has the problem. Adobe Acrobat is very tolerant towards errors in PDFs. It tries to fix as many as it can. Then when you save the form, the error is gone.
Comment: Hi Mate, I ran the PDF in question through Acrobat but to no avail. The PDF can be found here: https://www.dropbox.com/s/jyh3yz7crr4143p/job_card.pdf?dl=0

If you could take a look I would appreciate it immensely.
Comment: Figured it out, problem was not related to the PDF itself, will post as answer.
Answer: As it turns out the issue was not as Bruno Lowagie suggested regarding the consistency of the PDF.
I had run out of ideas and just thought I would try generating the FDF a different way. By running the command:
pdftk /full/path/to/template.pdf generate_fdf output /full/path/to/output.fdf

And then inspecting the resulting file, I was able to get a more accurate FDF and then when I ran the fill_form command:
pdftk /full/path/to/template.pdf fill_form /full/path/to/output.fdf output /full/path/to/output.pdf

I got a proper response and everything worked. So the problem I was getting was in fact caused by the FDF being malformed in some way.
My final solution was this if anyone is interested. It takes a template PDF with fields, generates an FDF to fill it, creates a new PDF by adding the data from FDF with the template PDF, redirects the browser to the PDFs location.
Big thanks to Bruno Lowagie for helping understand the system better and rule out a few things.
Comment: Thank you this is helpful, @user3192649. However, can I check if the FDF file is allowed to have SOME of the fields I would like to replace in the PDF, or does it have to include every field that the PDF expects?
Comment: I also had a malformed FDF file after following this [sitepoint](https://www.sitepoint.com/filling-pdf-forms-pdftk-php/) tutorial with some bad code. Reviewing your FDF function showed me where the sitepoint code was wrong.
Answer: It looks like PDF TK was not able to process stings that had char ( and ) I replaced them with \) and \( to escape them, and it worked well.
Comment: Thanks! I had the same problem, this fixed it!
Comment: This also solved my problem!
Interestingly I've also found that this problem only happens if you have ```(``` and don't have ```)```
Answer: I had the same problem. In my case changing the string encoding solved it.
Previously I was encoding it in utf-8 then I changed it to utf_16_be.
Root cause is that form fields data are stored in fdf form where values are stored inside brackets so if your data has brackets then it throws error.
Answer: Font issue:
https://stackoverflow.com/a/44442957/2150220
The link above is a better solution than just changing your font.
I was receiving the same error, however, none of the above solutions worked for me.
As I was testing:
pdftk a.pdf fill_form a.fdf output b.pdf

I was able to generate a pdf if my original pdf had not been altered, IE: all of the acrobat settings where default.
Only when I changed the font to "Arial" for a fill_form element did I receive the error.
I changed the font, and it was working again.
Answer: I just wanted to follow up for anyone else who encounters this. In our case, the problem was in the contents of the FDF file. Specifically, we were automating the process of filling in PDFs and user-generated content sometimes includes an unclosed ( [ or { character. These cause this same exception. If this is happening to you, verify that the contents of your FDF file do not contain "unclosed" parens, brackets, or curly braces.


How to organize webforms on (admin/content/webform) into groups

Question: Goal: I want to be able to organize the list of webforms on the admin/content/webform page, which is in a View to my understanding, in groups. Either via visual groups (using some header or box) or add a filter to the page so that I can specifically look up a term ID that is associated with one or multiple webforms (like you can on the admin/content page).
So for example: if I had several webforms about housing, I would like to be able to create the header 'Housing' and have associated webforms underneath. Or be able to select the Vocab or TID associated with one or multiple webforms and filter the results.
I'm a very new user to Drupal (couple months experience on the job only). I've spent the last ~4 days searching the internet to find info to help me and have found some promising things but haven't gotten anything to work. Many things are over my head.
The best two things I've tried are the following:
1) I've tried editing the Webform View. I've tried adding a TID field but that's not listed as an option to add. My plan was to add a Contextual Filter for TIDs.
2) I've tried adding a Term Reference field and Node Reference field to a Webform. This seemed promising until I realized they became Select List options on the actual webform presented to the user. Obviously this will not do what I want to do on the developer side of things.
I've heard about creating custom admin pages with views but I was hoping for a simpler way to accomplish this. If that is the only way to do so, so be it.
I'm using Webforms 7.x-4.4 fyi.
Thanks for any help! Sorry this is long and probably newbish.
Answer: I solved my own question.
Ended up creating a new Administration View of type content for only webforms. I then added the field 'Content: Term Group' which I added to the Webform Content type which is a term reference. I should mention I already created a new Taxonomy Vocabulary and gave that vocabulary three children taxonomy terms. From then it was as simple as noticing that 'Term reference' showed up when I hit Edit on a specific Webform so I can select one of the taxonomies. Then I changed the Format Setting 'Grouping field Nr.1' to 'Term Group' and thats it! Now my custom link (/admin/content/webform-groups) page shows all the webforms separated into separate boxes with their respective Term ID name above.


Need to run a cron job on Google compute engine (gce) to execute a gcloud snapshot with service account

Question: I've been successful at creating and executing a snapshot script if I use gcloud auth to use my personal account. but if I have the cron run as root or as a selected user nothing happens during the cron.
I used this script https://gist.github.com/peihsinsu/73cb7e28780b137c2bcd and it works great and as the author notes: "Install gcloud and auth first" are required.
My problem is in using my personal account and not the service account.
When you execute gcloud auth login you get a very important message
Your credentials may be visible to others with access to this
virtual machine. Are you sure you want to authenticate with
your personal account?
Any thoughts or suggestions to avoid this security risk.
Comment: Solved the problem! turns out that the gcloud sdk path was not available to cron user because it does not load the bash script. The simple solution was to add the PATH environment to my cron right above the cron task
Comment: Thank you for sharing your solution. In fact, the path of pre-installed gcloud command which comes with a GCE VM instance is: /usr/local/bin/gcloud
Comment: @DrakeZabriskie I can see from your comments that you have resolved this issue can you post your solution as an answer, which will help other users with the similar issue. Thanks
Comment: gcloud does not install globally in /usr/bin by default and installs to your local directories. So the path is only added to your own bash script.
Answer: Took some time to figure it out. The script is valid. The tricky part is the user permissions. There are 2 user types - the OS user and the GCE user.
The gcloud uses the GCE user, which is most likely something like email@example.com. You need to figure out what is the OS user that can use GCE credentials. In my particular case (i've set up VM instance using Bitnami) the user was bitnami (NOT root!!!).
You need to make sure that:

you set up the default gcloud user your GCE user (gcloud config set account firstname.lastname@example.com)
your script file is executable (chmod +x)
your script file's owner is the user that has GCE credentials
you set up cron for the particular user (in my case sudo -u bitnami crontab -e)
you include full path to the script inside crontab


Bayes Optimal Classifier for multinomial classification

Question: I understand the meaning and how to deduce a Bayes optimal classifier in binary classification, but I am not sure how to derive this in the context of multinomial classification. Do we use the naive bayes approach?
Answer: It doesn't have to be naive. Once modeled the joint distribution, Bayes classifier chooses the class with the maximum posterior regardless of number of classes. Two class examples are typically used because it's easier to analytically calculate the decision boundary.


Javascript url-redirection with pound-bang char in path

Question: How can I redirect my url from the form :
 http://example.com/#!foo

to the form :
http://example.com/folder/#!foo

using javascript?
I know that url redirection with hashbang is imposible on server side because # is never sent to the server.
I have tried the following code but redirection is not happening.

Any idea?
Answer: Try:
window.location.assign(<the path you want>)

Answer: Try:
window.open('http://example.com/folder/'+window.location.hash);

As you said, the hash tag will not pass to server anyway.


Comparators, Collections, and HashMaps

Question: I earlier needed to sort a HashMap by its values, and I used the comparator with the collections, like so:
private LinkedHashMap<String, Integer> sortMap(Map<String, Integer> results, int count)
{
    List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(results.entrySet());

    Comparator<Entry<String, Integer>> comparator = new Comparator<Entry<String, Integer>>() {
        @Override
        public int compare(Entry<String, Integer> a, Entry<String, Integer> b) {
            return b.getValue().compareTo(a.getValue());
        }
    };

    Collections.sort(entries, comparator);

    LinkedHashMap<String, Integer> sorted = new LinkedHashMap<String, Integer>();
    for (Entry<String, Integer> entry : entries)
        sorted.put(entry.getKey(), entry.getValue());

    return sorted;
}

Now the situation changed, and I needed it to be a HashMap that was sorted. So I changed the code to look like this:
private LinkedHashMap<String, Double> sortMap(Map<String, Double> results, int count)
{
    List<Map.Entry<String, Double>> entries = new ArrayList<Map.Entry<String, Double>>(results.entrySet());

    Comparator<Entry<String, Double>> comparator = new Comparator<Entry<String, Double>>() {
        @Override
        public int compare(Entry<String, Double> a, Entry<String, Double> b) {
            return b.getValue().compareTo(a.getValue());
        }
    };

    Collections.sort(entries, comparator);

    LinkedHashMap<String, Double> sorted = new LinkedHashMap<String, Double>();
    for (Entry<String, Double> entry : entries)
        sorted.put(entry.getKey(), entry.getValue());

    return sorted;
}

and it throws an error, namely java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Double at:
    at myPackage.myClass$1.compare(myClass.java:124)
    at myPackage.myClass$1.compare(myClass.java:1)
    at java.util.TimSort.countRunAndMakeAscending(Unknown Source)
    at java.util.TimSort.sort(Unknown Source)
    at java.util.TimSort.sort(Unknown Source)
    at java.util.Arrays.sort(Unknown Source)
    at java.util.Collections.sort(Unknown Source)
    at myPackage.myClass.sortMap(myClass.java:128)

myClass.java.128 : Collections.sort(entries, comparator);
myClass.java.124 : return b.getValue().compareTo(a.getValue());
Any help from you guys would be deeply appreciated, thank you!
Comment: Try doing a clean build, and see if you run into the same error. This error is happening because it's receiving values that are of type `Integer` rather than `Double`.
Answer: You have two choice:

change the sort method to get Integer instead of Double.
change the return type of entry.getValue() to Double!
Answer: You changed the signature of the sortMap() method from Integer to Double, but are still calling it with Integers. Is using a TreeMap perhaps an option to do implicit sorting?

Comparators, Collections, and HashMaps


What's the equivalent of drupal_build_css_cache()?

Question: Our client uses an external website for some of their pages. This provider does not enable us to theme their website directly, but they do allow us to load a single JS file from the Drupal site that we maintain.
We create this JS file through a Drupal route/controller, assembling the header and footer blocks, including CSS and JS files, and inserting them into the content by appending them to the appropriate elements.
We've ported all of the functionality to Drupal 8 from 7 and it's more efficient than before. However, we used to use drupal_build_css_cache() to aggregate the subset of CSS files from themes and modules that we need before injecting them into the website's head.
Keeping in mind that all we're delivering to the external website is a single JS file (so we can't attach a library in the usual way), is there a way of programatically creating an aggregated CSS file in Drupal 8, as that function used to do?
Answer: drupal_build_css_cache() is a Drupal 7 function that was removed very early in the Drupal 8 development cycle. The change notices back then weren't very good, so simply searching for that function name won't find anything. (Change notices may be found at https://www.drupal.org/list-changes). The relevant change notice is Pluggable CSS & JS preprocessing (aggregation/minification)
This does not say what drupal_build_css_cache() was replaced with, but searching the code of the patch that removed the function shows that the code of that function is now in the asset.css.collection_optimizer service (implemented in \Drupal\Core\Asset\CssCollectionOptimizer)
Answer: https://api.drupal.org/api/drupal/core%21includes%21common.inc/function/_drupal_flush_css_js/8.5.x
Try the above. it will clear all caches of JS and CSS.
https://api.drupal.org/api/drupal/core%21includes%21common.inc/function/drupal_flush_all_caches/8.5.x
It will clear all caches and rebuild.
Comment: The question does not ask about clearing caches, it asks about aggregating CSS. Your answer does not address the question.
Comment: As anonymous states above, that's not even remotely close to what I was asking.
Comment: Your answer explains how to use core functions to clear the cache. This is not what OP asked for. Thanks for taking time to post an answer anyway.


How many RJ45 outlets is too many?

Question: This is going to be a silly question.
Good friends of mine are opening an ophthalmologist office, and have asked me to provide input on their plans for the IT network. I'm a cybersecurity expert, not a network specialist however.
The job is to be taken care of by a small and local consulting firm. Looking at the design, I was very surprised to see that they have been advised to add an RJ45 outlet per device in every room. Overall, this will result in 80+ RJ45 outlets arriving in the machine room, with some rooms with many devices having over 15 outlets.
Now, my intuition would have been to just have one RJ45 outlet per room, maybe two for the really crowded ones, and use switches to connect everything. It feels to me that having one RJ45 plug per device is going to be very expensive, impractical (How do you handle 80+ cables arriving in the machine room? What happens when you need to add a new device?) and completely overkill.
Is there something I'm missing here? Is this state-of-the art infrastructure design?
Grateful for any input!
Comment: The design is correct. Your proposal to use switches in each room to uplink multiple devices to the core switch is a recipe for disaster for too many reasons to list here. Good friends and good consultants don't undertake projects or provide advice and guidance on subjects they have no  experience to speak on. Good friends and good consultants put their friends and customers in touch with people who do have the required experience. That's not a dig, that's advice from me to you.
Comment: It sounds like they have already gotten advice from good consultants and instead of seeking a second opinion from another expert, they chose not to.  80 ports if far from a high number.  Two 48 port patch panels will handle that and still leave room for 16 more.  There are 1000s of available ports in my server room.  Well, were.  I don't work in a server farm anymore.
Comment: Appreciated, but good SO answers also help people understand the stakes better. Good friends may have a hard time figuring out which consultants are good or not and double-checking makes sense in that regard.
Comment: best practice would be that each device has its own socket and port on the switch. there I could then lock down to a single allowed Mac address and no one else could use it in the first try with out knowing that Mac. but it is only one of a part of security you should have. I would suggest that you maybe draw a simple infrastructure plan to show the network topology
Comment: @Executifs The less spread devices are, the better. If you can keep all active equipment in a single place (server/communication room), you can serve the network better. You can provide all of them with filtered reliable power, etc. Also, you can have several managed larger devices versus many small unmanaged devices, which is huge increase of control over the network. It is not uncommon to see 400+ jacks in single server room going into big stacked switch (like 6 units of 48 ports each).
Answer:
they have been advised to add an RJ45 outlet per device in every room

That's the way to do it. You should also plan for additional devices in the future.

my intuition would have been to just have one RJ45 outlet per room, maybe two for the really crowded ones, and use switches to connect everything.

If you're pressed for ducting space then that's plan B. Increasing the number of switches that way increases installation cost, power usage and complexity, increasing operative cost and reducing resilience.
Using cheap, consumer-grade switches may be least expensive, but a professional network should use decent, managed switches, costing more than decent cabling.
Note that a cabling installation is going to be used for decades while switches last 5-10 years.

How do you handle 80+ cables arriving in the machine room?

That's not a problem, just two patch panels. Distribution points with many hundred ports are common.

What happens when you need to add a new device?

You plan ahead.

How many RJ45 outlets is too many?


VSCode, Javascript - change syntax color for data types

Question: What is the scope selector for changing the syntax color of data types (Number, String, Boolean) with textMateRules?
"editor.tokenColorCustomizations": {
 "[Monokai Pro (Filter Spectrum)]": {
   "textMateRules": [
     {
       "scope": ["???"],
       "settings": {
         "foreground": "#ff6188"
       }
     }
   ]
 }

NOTE: I dont want to change theme. Im trying to only change the color of data types from white current setup to another color, like in wanted setup
Answer: The TextMate scope you're looking for is variable.other.readwrite.js, so:
"[Monokai Pro (Filter Spectrum)]": {
  "textMateRules": [
    {
      "scope": ["variable.other.readwrite.js"],
      "settings": {
        "foreground": "#ff6188"
      }
    }
  ]
}

How to find the TextMate Scope

Open Command Palette and search for "Developer: Inspect Editor Tokens and Scopes"
Place your mouse caret on top of the code you wish to change its color
The TextMate scope you're looking for is usually the first line of "textmate scopes"
Comment: Thanks. Inspecting scopes is a great tip I'll take with me. This does however change more than just data types. Do you know if it's possible to target words? Like "String" or "thisWordShouldBeGreen"?
Comment: Sorry I don't know a method to do that. Judging from [this question](https://stackoverflow.com/q/45631153/11067496), I guess that is not possible
Answer: You have to change your color theme in VS Code. For example the color theme you're using is Monokai. The required theme seems to be Dark ++ italic.
Step 1

So to change your theme first head on to extensions tab and search for Dark++ Italic  and install it. The sample of Dark++ Italic
is

Step 2

Hit ctrl K + ctrl T and Select Dark++ Italic.
Comment: I see that my question was poorly defined. I updated the post to better describe what Im trying to do. Thanks for taking the time to answer
Answer: Bottom left of your screen select settings then go to Color Theme

Then, Select Dark+ (default Theme)
Comment: I see that my question was poorly defined. I updated the post to better describe what Im trying to do. Thanks for taking the time to answer


Problem solving recurrences with generating functions

Question: I'm trying to solve this linear recurrence with generating functions, but I keep getting stuck on the last few steps. I found the generating function, but after splitting it into partial fractions and putting it in sigma notation, I don't know how to simplify it into one summation:
$g_0$=1, $g_1$=2, $g_2$=-2
$g_n$=7$g_{n-1}$-16$g_{n-2}$+12$g_{n-3}$
I got up to the point;
$$\frac{1-5z}{1-7z+16z^2-12z^3}=\frac{7-8z}{(1-2z)^2}+\frac{-6}{1-3z}$$
and finally;
$$=(7-8z)\sum_{n=0}^\infty(n+1)2^nz^n-6\sum_{n=0}^\infty3^nz^n$$
I have no clue what to do now, but the final result should be;
$$g_n=(3n+7)\cdot2^n-6\cdot3^n$$
The question is from here if I missed anything (pg 15-18). Any help would be GREATLY aprreciated.
Answer: $$\begin{align*}
(7-8z)\sum_{n\ge 0}(n+1)2^nz^n&=7\sum_{n\ge 0}(n+1)2^nz^n-8\sum_{n\ge 0}(n+1)2^nz^{n+1}\\\\
&=7\sum_{n\ge 0}(n+1)2^nz^n-4\sum_{n\ge 0}(n+1)2^{n+1}z^{n+1}\\\\
&=7\sum_{n\ge 0}(n+1)2^nz^n-4\sum_{n\ge 1}n2^nz^n\\\\
&=7+\sum_{n\ge 1}7(n+1)2^nz^n-\sum_{n\ge 1}4n2^nz^n\\\\
&=7+\sum_{n\ge 1}(3n+7)2^nz^n\\\\
&=\sum_{n\ge 0}(3n+7)2^nz^n\;,
\end{align*}$$
so
$$(7-8z)\sum_{n\ge 0}(n+1)2^nz^n-6\sum_{n\ge 0}3^nz^n=\sum_{n\ge 0}\Big((3n+7)2^n-6\cdot3^n\Big)z^n\;,$$
and $g_n=(3n+7)2^n-6\cdot3^n$.
Comment: Thank you so much! This question has been keeping me up at night the last few days.
Comment: @user102120: You're welcome!


Granting access to a virtual machine?

Question: I have an internal website running on IIS 6 that denies access to everyone except for a few select IP addresses.  This is set by going to "Directory Security -> IP addressees and domain name restrictions" and entering the ip addresses that are allowed to access.
When I try to access this site from my laptop after VPNing in, I can get to the site.  But if I try to access the site from a VM running on my laptop I get a 403 error.  I have checked the IIS logs and don't see anything that would point me to what IP address it is denying access to.
I have tried looking at the output of ifconfig on my laptop (macbook) and ipconfig on my VM (Windows Server 2003) but adding those IPs does not seem to grant access.  I am using NAT on my VM.
Does anyone know how I can either grant access to my VM or figure out what IP my VM is using to access the site?
Answer: You could try to set the VM to used bridged mode instead of NAT.  This would have the VM pull an IP from the network (closest DHCP source) and you could try and test with that IP to see if you get the same results.
Comment: Gave it a shot but it didn't work.
Comment: This might be a dumb question but are you trying to access the site after setting up the VPN tunnel inside the VM?
Comment: Actually I was wrong when I said I was connecting from inside the VM.  I had made a VPN connection from my laptop, but not within the VM itself.  Once I did this I was able to access.  Thanks!
Comment: I'm somewhat curious as to why it wouldn't let you connect through the NAT then, but I'm glad it worked.

Granting access to a virtual machine?


Use Different port for Different IP bind

Question: I am using bind for internal networking it is working good,
now I am a another requirement.
bind9 resolving the domain myweb.example.com from ip 192.168.1.1 port 80
now I want to resolve domain myweb.example.com:82 from 192.168.1.2:82.
is that possible?
Comment: DNS does *not* resolve ports (except for IN SRV request). Is resolves names and adresses.
Answer: No. DNS is only about mapping host names to IP addresses, except for SRV records, but these can only be used in very specific circumstances with apps supporting this.
What is your end goal? Could a reverse proxy help you? With that, you would have one frontend server that listens both on port 80 and 82 and then delegates requests for one or both ports to a different backend server.
Comment: i have apache server on machine 192.168.1.1 and now I installed iis on 192.168.1.2 using port 82, we need to use same domain for both ip, so user will not confuse because this used by same application
Comment: Use a reverse proxy. Search for it, this is simple.
Comment: Ok, i will search for it


What is the new C#_LSP entry under the Text Editor options for?

Question: Visual Studio 2019 has a new entry under the Text Editor options named C#_LSP. I guess it has something to do with the Language Server Protocol, but I couldn't find what the entry is used for exactly.
Is there certain standard tooling that uses it? Or is it there for extensibility?
Answer: This is a bug. Internally some stuff is implemented with an LSP for Visual Studio Live Share, but a side-effect of that implementation was the C#_LSP entry appears. The entry doesn't do anything.
Answer:
The Language Server Protocol (LSP) is a common protocol, used to provide language service features to various code editors. Using the protocol, developers can write a single language server to provide language service features like IntelliSense, error diagnostics, find all references, and so on, to various code editors that support the LSP. Traditionally, language services in Visual Studio can be added by using TextMate grammar files to provide basic functionalities such as syntax highlighting or by writing custom language services that use the full set of Visual Studio extensibility APIs to provide richer data. With Visual Studio support for LSP, there's a third option.
Source: https://learn.microsoft.com/en-us/visualstudio/extensibility/adding-an-lsp-extension?view=vs-2019

Based on this I assume that the C#_LSP option is for a case when you decide not to use build-in C# services and use LSP instead.
Personally I don't see any common use case for it, but I am sure there are people out there who like it that way.
Comment: Hi Jakub, should there be two of these entries? I have two of them, but they're both identical.
Comment: @paul I have the same two duplicate entries in a fresh VS community edition install.


Generic collection  with ability sorting and get by position

Question: I know that ArrayList provide ability to get item at position get(position), and LinkedHashTable provide sorting, but it not able to get item at position. So,  question: is any generic collection in java with features:

sorting
get by position
provide Key/Value generic type.

Please, give me code example of listed features, if required generic exists.
Answer: Are you looking for TreeMap or SortedMap ??
Both TreeMap and SortedMap provides:

Provides Natural Sorting of Key Element.
Is a key/value pair
Gets a value based on a Key.

BTW:
LinkedHashMap just maintains an Insertion Order, it isn't Sorted, It is just has an Order
Comment: SortedMap get(key) - get by key but not by position, TreeMap - same i not found method like ArrayList.get(pos) - which provide get by position functionality.
Comment: @testCoder java.Util.Map implementing classes can only get elements based on key/value. LinkedHashMap maintains an Insertion order, it doesnt have indexes.
Comment: Does it mean that there is no way to get item by position?
Comment: @testCoderumm, none that i know of from standard java API
Answer: I apologize for over complicating things earlier!
Use a TreeMap. When you want to
get(position)

just do the following:
K key = treemap.getKeys().get(position)
V value = treemap.get(key);

==========================
My old over complex incorrect answer from before:
You can use an ArrayList<Pair<K implements Comparable,V>> where you implement comparable on the Pair<K,V> and K has Comparable implemented. Then you can use Collections.sort(List<Pair<K,V>) on the Arraylist.
Then you would maintain a HashMap<K,V> so that you can retrieve elements by K. That means you will have to remember to update both data structures. That means O(N) to add an element :( . Also, to simplify the logic, you would wrap the HashMap and ArrayList in an object.
public class Pair<K extends  Comparable<K>, V> implements Comparable {

    private final K first;

    private final V second;

    public Pair(K first, V second) {
        this.first = first;
        this.second = second;
    }

    public K getFirst() {
        return first;
    }

    public V getSecond() {
        return second;
    }

    public int compareTo(K other) ; // TODO
}

Comment: Can you provide any code sample which explain how to accomplish that?
Comment: Thanks, but in that case i not be able to get item `Pair` by key, is any way to get item by key too?
Comment: No, in that case, I recommend maintaining a HashMap<> and an ArrayList<>. With that you'll be able to index by position, and retrieve values by a key.


Not able to run an app on Android

Question: I am parsing Json data from a URL in Android. I am not getting any error while executing. But nothing is coming up.
Here is my MainActivity.Java code:
public class MainActivity extends ListActivity {
<code>/** Called when the activity is first created. */

@SuppressWarnings({ "rawtypes", "unchecked" })

@Override

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    setListAdapter(new ArrayAdapter(this, android.R.layout.simple_list_item_1,
 this.fetchTwitterPublicTimeline()));

}

public ArrayList<String> fetchTwitterPublicTimeline()

{

    ArrayList<String> listItems = new ArrayList<String>();

    try {

        URL twitter = new URL(

                "http://twitter.com/statuses/public_timeline.json");

        URLConnection tc = twitter.openConnection();

        BufferedReader in = new BufferedReader(new InputStreamReader(

                tc.getInputStream()));

        String line;

        while ((line = in.readLine()) != null) {

            JSONArray ja = new JSONArray(line);

            for (int i = 0; i < ja.length(); i++) {

                JSONObject jo = (JSONObject) ja.get(i);

                listItems.add(jo.getString("text"));

            }

        }

    } catch (MalformedURLException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    } catch (IOException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    } catch (JSONException e) {

        // TODO Auto-generated catch block

        e.printStackTrace();

    }

    return listItems;

}

}
</code>
And this is my manifest.xml content:

<code>  package="com.example.harsh"

  android:versionCode="1"

  android:versionName="1.0">

<uses-sdk android:minSdkVersion="8" />

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

 <application

    android:allowBackup="true"

    android:icon="@drawable/ic_launcher"

    android:label="@string/app_name"

    android:theme="@style/AppTheme" >

    <activity android:name=".MainActivity"

              android:label="Android List View">

        <intent-filter>

            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />

        </intent-filter>

    </activity>

</application>
</code>

This is the R.java file:
<code>package com.example.harsh;

public final class R {

public static final class attr {

}

public static final class dimen {

public static final int activity_horizontal_margin=0x7f040000;

  public static final int activity_vertical_margin=0x7f040001;

}

public static final class drawable {

    public static final int ic_launcher=0x7f020000;

}

public static final class id {

    public static final int action_settings=0x7f080000;

}

public static final class layout {

    public static final int activity_main=0x7f030000;

}

public static final class menu {

    public static final int main=0x7f070000;

}

public static final class string {

    public static final int action_settings=0x7f050001;

    public static final int app_name=0x7f050000;

    public static final int hello_world=0x7f050002;

}

public static final class style {public static final int
 activity_horizontal_margin=0x7f040000;

    public static final int activity_vertical_margin=0x7f040001;

}

public static final class drawable {

    public static final int ic_launcher=0x7f020000;

}

public static final class id {

    public static final int action_settings=0x7f080000;

}

public static final class layout {

    public static final int activity_main=0x7f030000;

}

public static final class menu {

    public static final int main=0x7f070000;

}

public static final class string {

    public static final int action_settings=0x7f050001;

    public static final int app_name=0x7f050000;

    public static final int hello_world=0x7f050002;

}

public static final class style {

public static final int AppBaseTheme=0x7f060000;

    public static final int AppTheme=0x7f060001;
}
}
</code>
While running it nothing is coming up after this:
<code>[2013-10-15 23:37:39 - FirstApp] adb is running normally.

[2013-10-15 23:37:39 - FirstApp] Performing com.example.harsh.MainActivity activity launch

[2013-10-15 23:37:40 - FirstApp] Automatic Target Mode: using existing emulator 'emulator-5554' running compatible AVD 'abc'

[2013-10-15 23:37:40 - FirstApp] Uploading FirstApp.apk onto device 'emulator-5554'

[2013-10-15 23:37:46 - FirstApp] Installing FirstApp.apk...

[2013-10-15 23:38:26 - FirstApp] Success!
</code>
So i am not able to figure out what is the problem.
Comment: Have you checked the log (LogCat)?
Comment: Have you tried logging out the lines you are getting back from the HTTP request? Personally, when I paste that URL into a browser, I get this for example: {"errors":[{"message":"Sorry, that page does not exist","code":34}]} . If that's what your code is getting, it makes sense your JSON parsing code doesn't find any rows.
Comment: It is sending signal in Logcat.
Now i am getting this :

[2013-10-15 23:58:50 - FirstApp] Failed to install FirstApp.apk on device 'emulator-5554!
[2013-10-15 23:58:50 - FirstApp] (null)
[2013-10-15 23:58:51 - FirstApp] Launch canceled!
Comment: Here, add this after your while statement: Log.d("MyApp", "Received string: " + line); . Then see what the server is sending you. The console message you are talking about is meaningless, you hit cancel or something when launching or it timed out trying to install the app, etc.. Just run it again.
Comment: In logcat under verbose i am getting this: Thread AudioOut_2 cannot connect to the power manager service
Answer: It looks like you're doing network/internet access on the main UI thread by calling your fetchTwitterPublicTimeline method in the activities onCreate. This will throw an exception in API levels newer than Honeycomb.
You should move that to an AsyncTask or background thread that is kicked off in the onCreate method and then fill your adapter when the AsyncTask completes and has data.
Comment: I have given the internet permission in manifest file. You can check above in the code mentioned.
Comment: @user861938  You missed the point.  It does not matter what permissions you have, you cannot do network IO on the UI thread.  Please read the answer again.
Comment: @user861938 after posting my answer I saw your manifest permissions and edited to remove the internet permission comment. thanks.
Comment: @PatrickKafka Now i am getting failed to install .apk on the emulator. Is it because of the reason you mentioned?
Comment: Can you tell me about that?
Comment: I'm not sure about the fail installing the apk. It sounds like it's not related to this issue you were having. You can try commenting all of your onCreate code so it's essentially doing nothing and see if the install succeeds... Also, sometimes the emulators just get out of whack and just need to be restarted or recreated.

Not able to run an app on Android


Meu banco de dados tem "sim", "não" e "-". Gostaria de substituir todo o banco de dados por "1" e "0" em uma operação do dplyr

Question: Vi que há formas de substituir coluna a coluna usando as funções mutate() e coalesce(), mas como substituir todos os valores de um banco de dados de uma vez?
Answer: Uma forma simples.
library(dplyr)

Criando dataframe de teste
df <- as.data.frame(list(col_sn = c("sim", "nao", "sim", "-")))
df
  col
1 sim
2 nao
3 sim
4   -

Mudando valores
df <- df %>% mutate(col_sn = case_when(col_sn == "sim" ~ 1, TRUE ~ 0))

Resultado
df
  col_sn
1      1
2      0
3      1
4      0

Nota: Caso existam outros valores na coluna col_sn diferentes de sim, nao, ou - eles também serão substituídos pelo valor 0
Atualizado em 14-03-23
Caso você possua várias colunas, você pode iterar conforme abaixo:
df <- as.data.frame(list(col_sn = c("sim", "nao", "sim", "-"), outra_sn = c("sim", "nao", "-", "-")))

df
  col_sn outra_sn
1    sim      sim
2    nao      nao
3    sim        -
4      -        -

for (col_name in names(df)) {
    df <- df %>% mutate(!!sym(col_name) := case_when(!!sym(col_name) == "sim" ~ 1, TRUE ~ 0))
}

df
  col_sn outra_sn
1      1        1
2      0        0
3      1        0
4      0        0

Comment: Olá, obrigado pela resposta. Há alguma forma de substituir todo o banco de dados? Há muitas colunas para nomear uma a uma na função mutate.
Comment: Resposta atualizada.
Comment: nossa, muito obrigado. vou demorar um tempo até entender sua resposta pois ainda estou acabando de começar no R.
Comment: Para quem votou negativo, poderia dizer o motivo para que eu melhore a resposta?
Comment: 3 votos positivos e 3 votos negativos. Se têm comentários para melhorar a resposta, comentem. Se sabem responder melhor, respondam. Se a resposta está ruim, vote negativo e diga o porquê.


How to get field value from multiple items? Twig

Question: <code>{% for item in items %}
  {{ item.content }}
{% endfor %}
</code>
I need to get some values from fields in item (displayed in screenshot)
Answer: Example -
<code>{{ item.content['#paragraph'].field_NAME.value }}
</code>
original source - https://www.drupal.org/forum/support/theme-development/2018-08-01/get-reference-entity-values-in-field-level-twig-template


CCNetIntegrationStatus is always UNKNOWN when used in the publishers section

Question: I have a build process running with CCNET v1.8.5. When the build completes, successfully or not I want to send a notification to Slack. I have the notification piece working with Slack's web hooks (see below) but I cannot seem to obtain the status of the current build via the CCNetIntegrationStatus property. The result of using $[$CCNetIntegrationStatus] in my config is always Unknown.
I have a hunch that the reason is that these CCNET integration properties (at least they way that I am declaring them) are processed and defined when the build starts. Of course, when the build starts the build status would be UNKNOWN.
I have also tried:

$[CCNetIntegrationStatus], the result is an empty/blank string.
$(CCNetIntegrationStatus), ccnet.config cannot be processed, variable not found
$CCNetIntegrationStatus, the result is the literal string $CCNetIntegrationStatus

Ultimately, what I want to achieve is to send an HTTP request (notification) once the build is complete that includes the current builds integration status, the prior builds integration status, the version number, and project name. How would I go about doing this?
Here is the sample configuration:

<cb:define name="SlackNotificationBlock">
    <checkHttpStatus>
        <httpRequest>
            <method>POST</method>
            <uri>$(slackUrl)</uri>
             {{
                      "username": "Build Bot",
                      "icon_emoji": ":build:",
                      "attachments": [
                        {{
                          "fallback": "Warning! A New Build Approaches!",
                          "pretext": "Warning! A New Build Approaches!",
                          "color": "#D00000",
                          "username": "Build Bot",
                          "icon_emoji": ":build",
                          "fields": [
                            {{
                              "title": "Project",
                              "value": "$[$CCNetProject]",
                              "short": true
                            }},
                            {{
                              "title": "Version",
                              "value": "$[$CCNetLabel]",
                              "short": true
                            }},
                            {{
                              "title": "Status",
                              "value": "$[$CCNetIntegrationStatus]",
                              "short": true
                            }},
                            {{
                              "title": "Last Status",
                              "value": "$[$CCNetLastIntegrationStatus]",
                              "short": true
                            }},
                            {{
                              "title": "Location",
                              "value": "$(appUrl)",
                              "short": false
                            }}
                          ]
                        }}
                      ]
                    }}

            <timeout>5000</timeout>
        </httpRequest>
    </checkHttpStatus>
</cb:define>

<publishers>
    <xmllogger/>

    <cb:scope slackUrl="url-to-slack"
              appUrl="application-url">
        <cb:SlackNotificationBlock/>
    </cb:scope>

</publishers>

Comment: Do any of the other replacements work like `CCNetUser` or more importantly `CCNetLastIntegrationStatus`?
Comment: See this page for the syntax of in-place replacements in the configuration preprocessor: http://cruisecontrolnet.org/projects/ccnet/wiki/Parameters
Answer: First I had to chuckle at the variations you tried like $(CCNetIntegrationStatus]. I mean really? But your hunch is right. The ccnet config code is static. The only way to make it dynamic is to source stuff from a file that you change during the build. This can be done with the build label but not apparently with the httpRequest.
I would do the url stuff in Nant. That gives you more flexibility. You can call it whenever you want.
Comment: It is possible to inject dynamic values, why its not resolving to a value I'm not sure just yet. See http://cruisecontrolnet.org/projects/ccnet/wiki/Direct_Dynamic_Value
Comment: Doh! The 'odd' variations were a typo in the original post. It has been fixed. Thanks for the info, I'll need to look into this further.
Comment: The dynamic values Simon talked about would be from ccnet parameters which are set at build start time. I don't think that's going to help you.
Comment: @Adam Bruss the `direct dynamic values` are there to allow you to replace any run-time parameter into a string, therefore any ccnet environment variable for the build can be injected using this technique. These are not static/constant values, the replacement happens for each build occurrence.
Comment: However, @Adam you may have stumbled on one point. If the replacement is happening at build start rather than at task execution then this would exhibit 'static' like behaviour; I'm not sure how its working at the moment. I know i have used the technique to introduce dynamic values into the build but admittedly those values were supplied at the start of the build.
Answer: I found a solution via the CCNetSlackPublisher. It accomplishes via a custom task what I was attempting to do entirely within the CCNET configuration syntax. Specifically, by implementing a custom task CCNetSlackPublisher is able to correctly obtain the current integration status. It then send that along to my configured slack channel. An additional benefit is that my CCNET configuration is simpler as well!
I was never able to 100% confirm my hunch that the CCNetIntegrationStatus property is evaluated once when the build starts. However, given the behavior that I was seeing I believe this to be the case.


SQL command not properly ended or invalid identifier

Question: Unable to determine why this query is causing an exception. any help is appreciated.
ORA-00933: SQL command not properly ended
SELECT COUNT(sd.URI) AS OrchCount FROM  SDETAIL AS sd, ORCH_ASSOC  AS orch WHERE sd.uri=orch.OPERATION_ AND sd.LEVEL='OrchA'
SELECT COUNT(SDETAIL.URI) AS OrchCount FROM SDETAIL WHERE SDETAIL.URI=ORCH_ASSOC.OPERATION_ AND SDETAIL.COMPONENTLEVEL='OrchA'

ORA-00904: "ORCH_ASSOC"."OPERATION_": invalid identifier
Comment: Please show ALL relevant details - like the table schemas in question. Edit your original question with the addtional details. http://stackoverflow.com/questions/how-to-ask
Answer: The AS keyword is only used in assigning column aliases, not tables:
FROM SDETAIL AS sd, ORCH_ASSOC AS orch

You can leave out AS and it should work fine:
FROM SDETAIL sd, ORCH_ASSOC orch

Comment: smacks head.. Thanks willOEM that did it.
Answer: @clav is right about the ORA-00904. As for the ORA-00933, that's because you did this:
... FROM SDETAIL AS sd

Do this instead (no "as"):
... FROM SDETAIL sd

Comment: Glad to hear it! @willOEM had the same answer and answered first, so can you mark the willOEM post as the correct answer? It will help anyone else who ends up with a similar problem to see which solution worked.


How to prove that $2A+B^2$ is nilpotent matrix

Question: I have $A,B \in \mathbb C^{3\times3}$ nilpotent matrix's.
We can suppose that $AB^2=B^2A$, is it true that $2A+B^2$ is nilpotent?
what i did is $(2A+B^2)^3$= $8A^3+12A^2B^2+6AB^4+B^6$
so now i know A,B are nilpotent so i am left with $12A^2B^2$.
But i don't know what to do from here
Comment: Hint. Since $B$ is nilpotent, $C:=B^2$ is also nilpotent. As $A$ commutes with $C$, they are simultaneously triangulable.
Comment: Alternatively, consider $(12A^2B^2)^2$.
Comment: Try $(2A+B^2)^4$
Comment: Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking.
Comment: Generally, when you say a matrix is nilpotent, there usually exists an $n \in \mathbb N$ such that $A^n = 0$. What is this $n$ for $A$ (there should be one for $B$ as well).
Answer: To determine whether the matrix (2A + B^2) is nilpotent given that matrices (A) and (B) are nilpotent, we need to examine their properties and apply the definition of nilpotent matrices.
A matrix (X) is said to be nilpotent if there exists a positive integer (k) such that ($X^k$ = 0), where (0) denotes the zero matrix.
Let's consider the matrix $(2A + B^2)$. Since (A) and (B) are nilpotent, there exist positive integers (m) and (n) such that $(A^m = 0)$ and $(B^n = 0)$.
Now, let's evaluate $((2A + B^2)^{m+n})$:
$[(2A + B^2)^{m+n} = (2A)^{m+n} + {m+n}C{1} (2A)^{m+n-1} (B^2) +{m+n}C{2} (2A)^{m+n-2} (B^2)^2 +......+ (B^2)^{m+n}]$
Since $(A^m = 0)$ and $(B^n = 0)$, every term in the expansion will contain either $(A^m)$ or $(B^n)$, resulting in a zero matrix. Therefore, we can conclude that $((2A + B^2)^{m+n} = 0)$, implying that $(2A + B^2)$ is nilpotent.
Hence, if matrices (A) and (B) are nilpotent, then $(2A + B^2)$ is also nilpotent.
Comment: Since the matrices are $3\times3$, you can take $m=n=3$.


Adding Data-Bind to Bootrstrap Dropdown

Question: I am trying to pull in a list of values through data-bind into a Twitter Bootstrap dropdown.

          <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
            Action
          </button>

I came across Knockout_bootstrap JS but am not sure it works with drop downs
http://billpull.github.io/knockout-bootstrap/
(no example provided)
Answer: HTML List vs HTML Select
The bootstrap dropdown is an html list.

The knockout js options binding is a binding for html select elements.
<select>
   <option></option>
</select>

I cannot tell for sure what you want to do, but what you are currently doing is adding the knockout options binding to a
, when the binding is supposed to be for a <select>.
Live Example in JS Bin
Here is an exmaple in jsbin that uses knockout for binding in both scenarios.
http://jsbin.com/ITOZUPI/1/edit
part of HTML with ko data-bindings

  <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">
            Action
          </button>

  <select data-bind="options: my.VM.Artists,
                 optionsCaption: 'Please select an Artist...',
                 optionsText: 'artistName',
                 optionsValue: 'artistId',
                 value: my.VM.artist_selected"></select>

Adding Data-Bind to Bootrstrap Dropdown


How to create a rule to conditionally send a notification email, based on field value?

Question: In the Article content type, I have a field called "Assign to" which is a reference to a User entity. So that the users (editors) can know witch articles are assigned to them by the administrators.
How should I configure the Rules module to send an email to editor when article is assigned to an editor, telling editors witch article is assigned to them, and who assigned this article?
Comment: *"Finally if it's possible to make the template"* sorry, we can't develop a whole functionality for you. We can answer questions, but here you are closer to giving specification and waiting for solution, than to asking a precise narrow question to get precise, direct answer.
Comment: Yes sure I do not need that you develop for me the code but I'm wondering if my question can be done with rules module!
I'll change the question maybe I have explain badely :)
Comment: I have edited the post now, hope is more specific this one :)
Comment: I edited it a bit for you and retracted my vote to put your question on hold. Of course if my edit is not exactly right, feel free to correct it, just keep the same "spirit", OK?
Comment: No, your edit is fine, and it's the same what I want to say, thank you :)
Answer: Here is a sample of a rule (in Rules export format), which will send an eMail to the userid selected via the field field_article_reviewer (= a field I added to my "Article" content type that is defined as an entity reference to a 'user'), and this whenever content of content type "Article" is saved:
{ "rules_notify_editor_about_outstanding_review" : {
    "LABEL" : "Notify editor about outstanding review",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_presave--article" : { "bundle" : "article" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_article_reviewer" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[node:field-article-reviewer]",
          "subject" : "Article waiting your review",
          "message" : "[node:author] has submitted a new Article post waiting your review.\r\n\r\nYou can review it at: [node:edit-url].",
          "from" : "[site:current-user:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

If (before importing this rule in your environment) in the above exported rule you'd change the field field_article_reviewer to match with your field name of the editor, you should be pretty close to getting it to work.
PS: I'm assuming this question is about D7.