How to manage a set of private patches while working on new features?

Question: I'm working with this legacy code which I need to introduce some new features.
Problem is that it imposes some ergonomic problems, like some very slow pages and bad logging messages.
I can solve those problems, but it has no unit tests so I cannot be sure my fixes really stand by themselves if I push them to production. They would not be approved either, as those parts are not really connected to the new features.
Sometimes, it's just my comments I made to better understand the code.
So, my workflow has been:

Dig deep in the code, make some comments, include some logging.
Fix some very slow parts, just enough as the path from logon to the feature I'm working on is fast and I can iterate quicker.
Carefully commit those small changes to a "my" branch.

So, when I need to work on a new feature:

Pull development branch (shared with others)
Rebase "my" to the development (important to the next step)
Branch "feature" branch from "my" (feature tip is now development + my changes)
Create the feature code changes
Rebase "feature" from "my" onto "development" (git rebase --onto development my)
Merge "feature" into "development"

If I need to make other fixes in unrelated parts of the code while working on the "feature" branch:

git stash unfinished changes (worktree is now "feature" HEAD)
checkout "my"
make the small change and commit
rebase "feature" to the new "my"
checkout "feature"
unstash the unfinished changes

As you may think, this is a pita, but better safe than sorry.
So, what I wanted was:

have some sort of patch system
make a small change (as a new log message)
make a patch out of it
keep working and committing my feature changes
unapply the patches
merge "feature" with "development"
make a "other feature" branch out of "development"
apply patches
repeat

Does anyone managed to find a good way to deal with it? Some sort of patch management system?
Stacked Git seems to be a nice tool, but I couldn't find a way to save patches to apply into another branch.

git switch development
git checkout -B feature
stg init
how to bring my patches from thy "my" branch? (or any other place they can be stored at?)
Comment: Why not make a script that cherry pick your private patch ?
Comment: My current workflow is basically that, just instead of cherry picking a set of "my" commits, I "cherry-pick" them all (rebase them to development and then branch from them) and then "revert" them (rebase parent back to development, basically deleting them from the feature branch.
Answer: It seems to me that the problem is already solved with the way you handle it already. Maybe a real solution is to actually incorporate some or all of your improvements/changes into the mainline (if even possible, up to management/team).
Apart from that, a couple of workarounds are to work only with stashes, or to work on top of my branch and then rebase -i and just move the feature commits an the beginning of the branch, or another possible solution is to create your own git format-patch files and apply then where and when necessary.
Disclaimer - this solutions might not bring you the benefit you were looking for, it's just an alternative.

Option 0 - stashing
Just stash all your my changes and then apply them to each feature you work on. git add -p just want you need to and then discard the rest of the changes. This is flexible as you would see conflicts when they arise and you don't have to manage and rebase your my branch all the time.
You can always change your stashes are modify them and create new stashes (dropping old obsolete ones)
The negative here is that working with stashes is sometimes difficult when it comes to conflict resolution. Another not so nice thing is that you always have dangling stashes and if they are a lot, managing them might be difficult.
Option 1 - rebasing
Here you still have your my branch. When you need to work on a feature, just work on your my branch. Once done:
git rebase -i HEAD~N

And them move your feature changes at the beginning and your improvement changes should be the latest commits. Now the state of the code should be exactly the same, but with differently ordered commits. All you need to do is checkout the commits that is before your my changes/improvements and create a feature branch.
# Go to your last feature commit
git checkout 3ab959ba
# Create a branch off of that
git switch -c my-feature

You're all done. You can push your changes.
Note - this is not much different from the current approach you are taking
You would still need to rebase your my changes constantly to keep up to date with develop.

Option 2 - patches
You can create patch files which you can save locally and apply them whenever you want.
Example:
git format-patch -2 HEAD --stdout > 0001-my-patch.patch

Would create a patch from the last two commits starting from HEAD. If you create a patch for your my branch then you can take all those changes into a single *.patch file.
Then once you start working on a feature you can do the following:
# Check that the patch won't produce errors
git apply --check 0001-my-patch.patch

# Apply the patch without actually making the patches into commits
git apply -- 0001-my-patch.patch

Now you just have a working directory with unstaged changes from your patch. You can start working on your feature. Once you are done, commit only the changes for that feature without touching the patch changes (ex: using git add -p to add only what you need). Commit and then re-apply the patch in reverse.
git apply -R 0001-my-patch.patch

Then you won't see the changes from your initial patch apply.

This will break in the following scenarios

If you touch the patch changes.
If your feature changes are way to close to your patch changes and you can't separate them (through git add -p for instance).
If you add changes between the patch changes, thus causing the git apply -R invalid (you can discard the changes of your patch, but then you won't be able to apply it again...).

So basically, this method is useful if your improvements won't interact with any other feature changes.
Comment: Great answer. The reordering of commits seems like a good ideia. The patch could be, but trying to isolate changes to commit (stage by chunk) has bites me more than enough so that I know I can't do it without accidentally forgetting something.
Comment: I would also suggest going for stashing, if that is even possible in your specific case


Django - create ForeignKey reference based on existing value in referenced model

Question: models.py:
class Thread(models.Model):
    title = models.CharField(max_length=400)
    discussion = models.URLField(max_length=250, unique=True, blank=True, null=True)
    ...

class Comment(models.Model):
    thread = models.ForeignKey('Thread', null=True, on_delete=models.SET_NULL)
    thread_name = models.CharField(max_length=100)
    thread_link = models.URLField(max_length=250)
    ...

addcomments.py:
....

clean_comments = list(zip(thread_name, thread_link))

for thread_name, thread_link in clean_comments:

    # if thread_link exists in Thread model
    Comment.object.create(
        thread=???,
        thread_name=thread_name,
        thread_link=thread_link)

    # if not exists
    Comment.object.create(
        thread=Null,
        thread_name=thread_name,
        thread_link=thread_link)

I want to create Comment object with ForeignKey referencing Thread object if the value of thread_link (Comment model) exists in Thread model (thread_link == discussion). If thread_link != discussion i want ForeignKey to be set to None.
for thread_name, thread_link in clean_comments:
    filtered = Thread.objects.filter(discussion=thread_link)

    if filtered:
        Comment.object.create(
            thread=???,
            thread_name=thread_name,
            thread_link=thread_link)
    else:
        Comment.object.create(
            thread=None,
            thread_name=thread_name,
            thread_link=thread_link)

Here's what im trying. Not sure if that the right thing but if it is, what do i reference in "thread=???"?
edit:
solved this one:
            try:
                exists = Thread.objects.get(discussion=thread_link)
            except Thread.DoesNotExist:
                exists = None

            Comment.objects.create(
                thread=exists,
                thread_name=thread_title,
                thread_link=thread_link)

Answer: solved:
            try:
                exists = Thread.objects.get(discussion=thread_link)
            except Thread.DoesNotExist:
                exists = None

            Comment.objects.create(
                thread=exists,
                thread_name=thread_title,
                thread_link=thread_link)


cygwin g++ can't find pmr namespace and related issues

Question: Ok so I decided to compile some code from godbolt locally on my Windows 10 64bit using Cygwin and the cygwin terminal. It compiles fine on godbolt, but cygwin/mingw64 g++ spits out loads of errors along the lines of:
jsontest.cpp:310:23: error: 'string' is not a member of 'std::pmr'; did you mean 'std::string'?
  310 | auto expand(std::pmr::string s, ospolicy policy) {
      |                       ^~~~~~
In file included from /usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/string:39,
                 from jsontest.cpp:2:
/usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/bits/stringfwd.h:79:33: note: 'std::string' declared here
   79 |   typedef basic_string<char>    string;
                  ^~~~~~

There are a lot more issues but I think they are all related to this one. When I looked into the headerfile for #include<string> (which I did), std::pmr::string is defenitely defined there. The file stringfwd.h just forward declares basic_string templates so it should still find the definitions.
This is the section inside the string headerfile:
#if __cplusplus >= 201703L && _GLIBCXX_USE_CXX11_ABI
namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
  namespace pmr {
    template<typename _Tp> class polymorphic_allocator;
    template<typename _CharT, typename _Traits = char_traits<_CharT>>
      using basic_string = std::basic_string<_CharT, _Traits,
                         polymorphic_allocator<_CharT>>;
    using string    = basic_string<char>;
#ifdef _GLIBCXX_USE_CHAR8_T
    using u8string  = basic_string<char8_t>;
#endif
    using u16string = basic_string<char16_t>;
    using u32string = basic_string<char32_t>;
#ifdef _GLIBCXX_USE_WCHAR_T
    using wstring   = basic_string<wchar_t>;
#endif
  } // namespace pmr
//...
} // namespace std

You can see that the std::pmr::string typedef is guarded and only availabe when the C++ version is greater than 17 (as polymorphic memory resources are only available from C++17) and something about the CXX ABI.
I'm using gcc 11.3 which should be able to support even C++20 language features. I'm not getting it... what am I doing differently than godbolt?
EDIT:
Try this to reproduce:

Download cygwin from here and install it the usual way (add g++ to environment vars)
Create testfolder with the following file:

test_pmr.cpp (CompilerExplorer)
#include <iostream>
#include <memory_resource>

int main()
{
    std::pmr::string str = "Hello World!";

    std::cout << str << std::endl;
}

Compile using the following command:
g++ -std=c++20 test_pmr.cpp -s -o test_pmr

When I follow this I get this error:
test_pmr.cpp: In function 'int main()':
test_pmr.cpp:6:15: error: 'string' is not a member of 'std::pmr'; did you mean 'std::string'?
    6 |     std::pmr::string str = "Hello World!";
      |               ^~~~~~
In file included from /usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/iosfwd:39,
                 from /usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/ios:38,
                 from /usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/ostream:38,
                 from /usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/iostream:39,
                 from test_pmr.cpp:1:
/usr/lib/gcc/x86_64-pc-cygwin/11/include/c++/bits/stringfwd.h:79:33: note: 'std::string' declared here
   79 |   typedef basic_string<char>    string;
      |                                 ^~~~~~
test_pmr.cpp:8:18: error: 'str' was not declared in this scope; did you mean 'std'?
    8 |     std::cout << str << std::endl;
      |                  ^~~
      |                  std

EDIT2:
It works using only MSYS with static linking:
g++ -std=c++20 -static-libgcc -static-libstdc++ test_pmr.cpp -s -o test_pmr

So the problem seems to lie in an incorrect stdlib configuration that ships with cygwin.
Comment: what is your `g++` command line? Copy+paste it from the console output.
Comment: @DougHenderson `g++ jsontest jsontest.cpp -o -s -I ../../include -std=c++20`
Comment: Given a choice, I would use this `g++ -std=c++20 -I ../../include jsontest.cpp -s -o jsontest`, so general options, input options, input, output options, output. In my own code I always add more options: `-Wall -Wextra` and sometimes `-Werror`.
Comment: @DougHenderson Thanks but that doesn't make a difference. The problem is in compiling. I will add an example for reproduction to original post ^^
Answer: To use anything in the std::pmr namespace, it looks like you need to add -D_GLIBCXX_USE_CXX11_ABI to your general compiler flags. I got a clean and successful compile and execute with g++ -std=c++20 -Wall -Wextra -Werror -D_GLIBCXX_USE_CXX11_ABI test_pmr.cpp -s -o test_pmr.exe
Comment: Thank you, interesting. Any clue on why the flag is not set by default?
Comment: No. I have never needed to use it. When I used the right option, I could see that the section from the string header that you quoted in the initial question was not getting included in the pre-processed source (the .i file).


No visible @interface in my main

Question: i can not figure out why I am getting the error No visible @interface for 'StockHoldings' declares the slector
I have googled it and looked thru here and I am still confused could some one point me in the right direction. Thank you.
StockHoldings.h
#import <Foundation/Foundation.h>

@interface StockHoldings : NSObject
{
    //three instance varibles
    float purchaseSharePrices;
    float currentSharePrices;
    int numberOfShares;
}

@property float purchaseSharePrices;
@property float currentSharePrices;
@property int numbeOfShares;

-(float)costInDollars; //purchaseSharePrice * numberOfShares
-(float)valueOfShares; //currentSharePrice * numberOfShares

StockHoldings.m
#import "StockHoldings.h"

@implementation StockHoldings

@synthesize purchaseSharePrices, currentSharePrices, numbeOfShares;

-(float) costInDollars
{
    return ([self purchaseSharePrices] * [self numbeOfShares]);
}

-(float) valueOfShares
{
    return ([self currentSharePrices] * [self numbeOfShares]);
}

@end

main.m
#import <Foundation/Foundation.h>
#import "StockHoldings.h"
int main(int argc, const char * argv[])
{

    @autoreleasepool {

        NSLog(@"Hello\n");

        StockHoldings *stock1 = [[StockHoldings alloc]init];
        [stock1 currentSharePrices:1.0];
        [stock1 purchaseSharePrices:2.0];
        [stock1 numbeOfShares:3];

    }
    return 0;
}

Comment: The most important part of the error message is missing: the selector name.
Comment: Forget about it: you are calling the getter-named method to set the value. Use `[stock1 setCurrentSharePrices:1.0]` instead ;)
Answer: The setter method name for properties is set[PropertyName], so your code should probably read like this:
StockHoldings *stock1 = [[StockHoldings alloc]init];
[stock1 setCurrentSharePrices:1.0];
[stock1 setPurchaseSharePrices:2.0];
[stock1 setNumbeOfShares:3];

At your preference, you may also want to use the dot syntax instead:
StockHoldings *stock1 = [[StockHoldings alloc]init];
stock1.currentSharePrices = 1.0;
stock1.purchaseSharePrices = 2.0;
stock1.numbeOfShares = 3;

And finally, you may want to fix that numbeOfShares typo (missing an R for "number").
Answer: You are not using the setters properly. For a @property (weak) id data once synthesized the setter method would be like [self setData:@"foo_bar"]. And getter method will be like [self data] The default name for a setter method is set<Property>
So in your case :
[stock1 setCurrentSharePrices:1.0];
[stock1 setPurchaseSharePrices:2.0];
[stock1 setNumbeOfShares:3];

No visible @interface in my main


Is it possible to restore a Redshift database from snapshot?

Question: I want to restore a Redshift DB from one cluster to another. Is it possible?
Comment: what did u try?
Comment: @ItayMoav-Malimovka I tried to look for such an option in the "Restore from snapshot" UI in the Redshift console and also in boto3 docs, but I didn't find anything
Comment: What is the situation in which you find yourself? Did you lose some data that you now wish to restore? Is it a whole database, or just a table?
Comment: @JohnRotenstein I want to create a pre-prod environment which will be identical to the production cluster and will be recreated every night. The issue is that I don't want the redshift version to be updated since there's a bug in the queries rewriter which affects us. The production version is suspended so it won't be updated and I want the same to be in the pre-prod but it will be created with the latest (or trailing) version as default.
Answer: From Amazon Redshift snapshots - Amazon Redshift:

When you restore from a snapshot, Amazon Redshift creates a new cluster and makes the new cluster available before all of the data is loaded, so you can begin querying the new cluster immediately.

Thus, a new cluster is always created from the snapshot. It is not possible to restore a snapshot to an existing cluster.
You would need to create a new cluster, then somehow migrate your desired database/schema/tables to the existing cluster.


How do I export a content type, views as a single module

Question: I've a view, content type, field collection, flexslider to satisfy a single user case. May I know how to export all these three as a single module.
Answer: You could use some Drupal Console export commands for this:

config:export:content:type
config:export:view

You could use the <code>--module</code> option to specificy which module to export.
It's easier to use the Features module though. From the project page:

A feature is a collection of Drupal entities which taken
  together satisfy a certain use-case.
Features provides a UI and API for taking different site building
  components from modules with exportables and bundling them together in
  a single feature module. A feature module is like any other Drupal
  module except that it contains additional information in its info file
  so that configuration can be checked, updated, or reverted
  programmatically.
Examples of features might be:

A blog
A pressroom
An image gallery
Comment: There is no way to export it using console?
Comment: I updated my answer with some more information.
Answer: Install and configure Features module.

Features provides a UI and API for taking different site building
  components from modules with exportables and bundling them together in
  a single feature module.

To export using terminal use Drush.
Drush commands for features : https://drushcommands.com/drush-7x/features/features-add/
Comment: There is no way to export it using console?
Comment: Drupal Console != Drush. But I agree, using features + drush is easier than using DC.
Comment: @WimMostrey I guess FazeelaAbuZohra asking about terminal.


Bootstrap multiple cols not working

Question: So, when I type multiple cols for my imgs tags only the md one is working.
Thats how its structured:
And thats how the lg screen is looking like:
Answer: Number of columns must be 12 in each row class.also use img-responsive class for image.
http://www.w3schools.com/bootstrap/bootstrap_grid_system.asp
Please check this codepan
    codepen.io/payalpatel2299/pen/dOaLgd
Comment: the thing is, how to do it then since the amount of lg,md,sm are different and need to be inside the same rows as lg?
Comment: Check the codepan again please. I have added clearfix div. you can use offset as well  http://codepen.io/payalpatel2299/pen/dOaLgd
Comment: A Bootstrap row can exceed 12 columns in a row. It's called column wrapping.
Answer: Between each class="row" the sum of segments should be 12. Please notice the following code...

.col-md-1

.col-md-1

.col-md-1

.col-md-1

.col-md-1

.col-md-1

.col-md-1

.col-md-1

.col-md-1

.col-md-1

.col-md-1

.col-md-1

.col-md-8

.col-md-4

.col-md-4

.col-md-4

.col-md-4

.col-md-6

.col-md-6

Comment: I know I know... but and when I need to put an lg,md and sm size? For example 6 col-lg-2 and 3 col-md-4 ? They dont fit in the same row...
Comment: Develop for `sm`. Get rid of `md` and `lg` and try your code in all resolutions with just `sm`.

Bootstrap multiple cols not working


Views filter criteria date field is greater than current date

Question: I have a overview page with different events. Now it shows all events which were created. But I will that it just shows all the future events.
The content type has a datefield for the eventdate. I selected the field_date_event by the filter criteria but there I can not enter the token [current-date] or a dateformat like d.m.y.
How can I solve this problem?
Answer: You should be able to choose the Operator Is greater than or equal to, and the Value type set to offset with value Today:

This will include events happening today. If you want strictly from tomorrow you can choose Is greater than as the Operator.
Answer: Add filter:
Operator "Is less than" value "today +24 hours" to remove future dated content if needed.
See: Filter nodes by today's date


Mostrar mensagem se uma determinada palavra for digitada

Question: Como faço para que quando alguém escrever no cmd:
> tree

Apareça uma mensagem usando o seguinte comando:
Console.Write("");

Comment: Qual o objetivo dessa escrita?
Comment: Só isso? Não é apenas o caso de criar uma *Console Application* chamada `tree`?
Comment: vou fazer uma brincadeira com amigos e eu precisava de fazer quando escrever tree no cmd apareça repetidamente no cmd vírus não encontrado
Comment: O obejetivo é que quando escrever tree apareça uma mensagem
Answer: Você pode usar Console.ReadLine():
string entrada = Console.ReadLine();
if (entrada == "tree"){
    Console.WriteLine("Mensagem!");
}

Comment: Obrigado pela ajuda :D tenho de esperar 5 minutos para por como resposta certa


How to deal with troll user

Question: This user (https://economics.stackexchange.com/users/13326/liu?tab=topactivity) submitted several answers in the last 9 hours, all of which seem to be nonconstructive comments. Is there anything we could do to prevent such activities other than flagging the answers individually?
Answer: For the community very widely, the tools are fairly limited: down-voting and flagging being the main options. Higher rep users have some more privileges (see here: https://economics.stackexchange.com/help/privileges). In particular, "trusted users" (4k+ rep) can vote to delete answers. Right now, there are only 7 users at that level, but the more people reach this reputation target the easier it will be for the community to self-police (another great reason to vote more, I guess!).
The mods have much wider powers, including deletion or destruction of the offending account. So our best response for the time being seems to be to try to be active in flagging bad behaviour for moderator attention. we'll try to respond as swiftly as we can. I have dealt with the specific case you mentioned. In the medium-long run, hopefully we can get a core of users with fairly wide policing privileges.

How to deal with troll user


MySQL not allowing remote connections from new server

Question: I currently have one server that's connecting to a centralized MySQL server (say, 192.168.0.10). This server already allows remote connections from this IP address (say, 192.168.0.20), and in spite of my changes so far, continues to work. For this one IP address.
When I try to grant access to this same username and password from different hosts like this:
update db set host='192.168.0.%' where user='username';
update user set host='192.168.0.%' where user='username';
flush privileges;

Everything still stays the same. I can still connect from 192.168.0.20, but I also still can't connect from 192.168.0.25. I get the error message

ERROR 1130 (HY000): Host '192.168.0.25' is not allowed to connect to
  this MySQL server

I can't see how this is wrong. All the documentation says it should work. I'm also not firewalling connections from 192.168.0.25. Even restarting MySQL has no effect. Other IPs on this network can connect to MySQL without any issue - even ones that were previously not allowed - and I can ping 192.168.0.10 from 192.168.0.25.
Answer: You have to modify mysql.user table, not  only the mysql.db.
The proper syntax is:
RENAME USER 'user'@'192.168.0.10' TO 'user'@'192.168.0.%';
FLUSH PRIVILEGES;

Comment: Oops, I already had. I'll add that to my question.
Comment: Or... not? I had before, but I used a hostname and wildcard instead of an IP address with wildcard. I'd changed that in the host table but not the user table. Fixing this inconsistency now allows me to connect. Thanks!
Comment: You shouldn't have put it in with the bread-knife :)


How to get all allowed languages for Wikidata

Question: I'm writing a tool for interacting with Wikidata where labels and descriptions are added to items. But I would like to validate that the language is supported before trying to add it.
So my question is how do I get a list of the allowed language codes. The documentation describes this as UserLanguageCode but gives no info on retrieving the allowed values.
I know I can get a list of all of the used languages by doing the following SQL operation on the database, but that is both slow and inefficient: SELECT DISTINCT term_language FROM wb_terms.
As an aside is the list of allowed languages the same for MonolingualText statements?
Comment: Are those the same as [`action=query&meta=siteinfo&siprop=languages`](https://www.wikidata.org/w/api.php?action=help&modules=query%2Bsiteinfo)?
Comment: Per https://www.mediawiki.org/wiki/API:Siteinfo those are the UI languages for MediaWiki. It is unclear whether this is the same list as that of allowed label languages. It is not the same as the allowed MonolingualText languages though. E.g. `nl-informal` appears there and is allowed for labels but not for MonolingualText.
Comment: See also https://stackoverflow.com/a/48240614/7879193
Answer: There is now an API for getting the supported content languages (API sandbox):

https://www.wikidata.org/w/api.php?action=query&meta=wbcontentlanguages&wbclcontext=term&format=json&formatversion=2

By default it just returns the language code, but you can add the name and/or autonym (name in that language) via the wbclprop parameter. (To control the language in which the name is returned, set the global uselang parameter.)
To get allowed monolingual text languages, set wbclcontext to monolingualtext instead of term; on Wikidata, you can also set it to term-lexicographical for all language codes supported on lexicographical data (almost but not quite identical to the term languages).
Answer: User hoo on IRC channel #wikidata found this solution:
Get the JSON payload at this address:
https://www.wikidata.org/w/api.php?action=paraminfo&modules=wbsetlabel
And extract
 modules[0].parameters[8].type

There are indeed less languages in this list than all the UI languages for MediaWiki.
Comment: Thanks. This worked for getting the allowed languages for `label` and `alias`. It seems as though the list for allowed languages for `MonolingualText` is different and not accessible today.

Small note. In case the order of the parameters change I would probably iterate over them and then select the `type` corresponding to `'name' == 'language'`
Comment: As per https://meta.stackoverflow.com/questions/335658 I've changed the accepted answer now that the API finally supports these requests.


Is $x^y$ - $a^b$ divisible by $z$, where $y$ is large?

Question: The exact problem I'm looking at is:
Is $4^{1536} - 9^{4824}$ divisible by $35$?
But in general, how do you determine divisibility if the exponents are large?
Comment: Are you familiar with Euler's theorem: http://en.wikipedia.org/wiki/Euler%27s_theorem ?
Comment: Note that the question in the title is different (and much easier!) than the question in the _text_; the former only involves a power of a single number, whereas the latter involves a difference of numbers, which can complicate things.
Comment: Edited title to reflect that.
Comment: $\phi(35)=24= gcd (1536, 4824)$
Answer: Use Fermat's little theorem, which says that, for prime $p$,
$$a^{p-1}\equiv 1\mod p$$
for $a\in\mathbb{Z}$, $a$ not a multiple of $p$. In particular, your combination is easily shown to be zero both mod $5$ (because $4\mid 1536$ and $4\mid 4824$) and mod $7$ (because $6\mid 1536$ and $6\mid 4824$), so it is divisible by both $5$ and $7$ and hence divisible by $35$.
Comment: If $a^4 \equiv 1\pmod 5$ then $a^{1536} = a^{4\cdot 384} = (a^4)^{384}\equiv 1^{384} = 1$.
Comment: How do the exponents 1536 and 4824 work with fermat's theorem? $a^{5-1} = 1$ mod $5$ and $a^{7-1} = 1$ mod $7$? I understand your second point, but how do you incorporate fermat's into that?
Comment: For instance, $4^{1536}=(4^4)^{384}\equiv 1^{384}\mod 5$
Comment: Your statement of little Fermat is incorrect - it requires $\, p\nmid a,\ $ (which is true here).
Answer: Hint $\ $ It is a very special case of either of the following theorems.
Theorem $\rm\  lcm(m,n)\:|\: a^j - b^k\ $ if $\rm\,(ab,mn)=1\,$ and $\rm\ \phi(m),\phi(n)\:|\:j,k,\ $ with $\,\phi = $  Euler totient
Proof $\rm\ \ mod\ n\!:\ a^j-b^k = (a^{\phi(n)})^{\,j/\phi(n)}\!-(b^{\phi(n)})^{k/\phi(n)}\equiv 1^{j/\phi(n)}\!-1^{k/\phi(n)}\equiv 0;\ $ similarly mod $\rm\,m.\:$ Therefore $\rm\:m,n\:|\:a^j-b^k\:\Rightarrow\:lcm(m,n)\:|\:a^j-b^k\ \ $ QED
Theorem $\ \ \rm  35\ |\ a = (5j\!-\!1)^{6m} \!- (5k\!-\!1)^{6n}\ $ if $\rm\,\ j,k\not\equiv 3\pmod 7$
Proof $\rm\ \ mod\ 5\!:\ a \equiv (-1)^{6m} - (-1)^{6n} \equiv 1 - 1\equiv 0$
$\rm mod\ 7\!:\ 5x\equiv 1\iff x\equiv \frac{1}5 \equiv \frac{-6}{-2}\equiv 3,\:$ so $\rm\:j,k\not\equiv 3\Rightarrow5j\!-\!1,\ 5k\!-\!1 \not\equiv 0,\:$ so by little Fermat
$$\rm\:x\not\equiv 0\:\Rightarrow\:x^6\equiv 1,\ \  so\ \ a = (5j\!-\!1)^{6m} \!- (5k\!-\!1)^{6n}\equiv  1^m\! - 1^n\equiv 0$$
Therefore $\rm\ 5,7\:|\:a\:\Rightarrow\: lcm(5,7)=35\:|\:a.\ \ $ QED
Answer: You can use binomial theorem to break up the individual bases into multiples of the divisor and then you can expand binomially to check divisibilty. This is in a general case of doing such a problem . There may be more methods of doing such a problem.
Comment: How does the binomial theorem apply in a case of unequal powers?
Comment: No i meant to convert say 4^3 as (63-1). say you have 4^9 you can break this as (63-1)^3 and then expand binomially if you want to check divisibilty, say by 7.
Answer: $$4^{1536} \equiv 256^{389} \equiv 11^{389} \equiv 11*{14641}^{97}
\equiv 11*11^{97} \equiv 121^{49} \equiv 121* 14641^{24} \equiv 16* 11^{12}
\equiv 16*14641^3 = 16*11^3 \equiv 16*1331 \equiv 16.  $$
I use $\equiv$ to denote equivalence mod 35.  Just keep tossing out 35s.  YOu can do this on the other piece too and compare.


Replace text through the entire database without assigning table or column

Question: I've been using the following query to replace certain data:
UPDATE wx3_t1 SET umo = REPLACE(umo, 'stringbefore', 'string after');

wx3_t1 = Table
umo = Column

I am looking for a way to update across the entire database, without needing to put the table or the column into the query.
Something as simple as just REPLACE('stringbefore', 'string after')
I realize that doing it this way is really aggressive but that's fine.
Comment: I don't think there is one native query that can do this - but you can do it manually using phpMyAdmin
Comment: I dont understand what is the question here. You already have a query working and want a solution doesnt exist but looks better?
Comment: @JuanCarlosOropeza I have 300 tables with many many columns, I want an aggressive replace rather than having to change every single table and column manually.
Comment: I just answer a question very similar. But in that case only `LOOP` for columns, you will need loop for tables as well. http://stackoverflow.com/questions/35758493/searching-through-all-columns-in-a-table/35758643?noredirect=1#comment59190809_35758643
Comment: Have you considered using a dynamic query (using SELECT from information_schema to get all the column names, and then using exec sp_executesql with parameters to get it to run in every table)?
Answer: You can create a simple script that query information_schema.COLUMNS to get list of all your columns by table:
select TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME from information_schema.COLUMNS;

Then you have to iterate on the result to play your UPDATE query.


Merge menus for mobile menu

Question: Hi I have 3 menus on my site and for display on mobile/tablet I would like to merge these menus to only 1 menu. Do you know how to do it. I tried to use menu_tree_all_data
and then merge them but I get Call to undefined function menu_tree_all_data. I'am confused that the function doesn't exist.
Comment: [`menu_tree_all_data()`](https://api.drupal.org/api/drupal/includes%21menu.inc/function/menu_tree_all_data/7.x) doesn't exist in D8.
Answer: As I'm also looking for a solution to this issue I've come a bit further and maybe it will get you in the right direction.
To load a menu in Drupal 8 you can put this in a theme_preprocess_page in your .theme-file.
  $menu_tree = \Drupal::menuTree();
  $menu_name = 'main';

  // Build the typical default set of menu tree parameters.
  $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);

  // Load the tree based on this set of parameters.
  $tree = $menu_tree->load($menu_name, $parameters);

  // Transform the tree using the manipulators you want.
  $manipulators = array(
    // Only show links that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  $tree = $menu_tree->transform($tree, $manipulators);

  // Finally, build a renderable array from the transformed tree.
  $menu = $menu_tree->build($tree);
  $menu_html = \Drupal::service('renderer')->renderPlain($menu);

I have not yet worked out how to merge different menus into one big menu but I will let you know if I come up with a solution.
You can find out more about the code above at Drupal 8.2.x » menu.api.php which is where I found it.
Ok, I now have found the solution which I found in the module Responsive and off-canvas menu
  $menus = array("main-menu","footer-menu","utility-menu");

  $combined_tree = array();
  $menu_tree = \Drupal::menuTree();
  $parameters = $menu_tree->getCurrentRouteMenuTreeParameters(trim($menus[0]));
  $manipulators = array(
    // Show links to nodes that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkNodeAccess'),
    // Only show links that are accessible for the current user.
    array('callable' => 'menu.default_tree_manipulators:checkAccess'),
    // Use the default sorting of menu links.
    array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
  );
  // Force the entire tree to be build by setting expandParents to an
  // empty array.
  $parameters->expandedParents = array();
  // Iterate over the menus and merge them together.
  foreach($menus as $menu_name) {
    $tree_items = $menu_tree->load(trim($menu_name), $parameters);
    $tree_manipulated = $menu_tree->transform($tree_items, $manipulators);
    $combined_tree = array_merge($combined_tree, $tree_manipulated);
  }

  $menu = $menu_tree->build($combined_tree);

  $vars['mobile_menu'] = array(
    '#prefix' => '

',
    '#suffix' => '

',
    '#markup' => \Drupal::service("renderer")->renderRoot($menu),
  );

If you put this in your theme_preprocess_page in your .theme-file you could then in your page.html.twig print the twig variable {{ mobile_menu }}.
Comment: Make sure `$vars` corresponds to the function parameter:

`MYTHEME_preprocess_page(&$vars){

}`
Comment: Also `'#prefix'` and `'#suffix'` seem to break things for me... Not had time to look into this... :)

Merge menus for mobile menu


Tizen SDK installation - the installmanager.conf or Package file cannot be saved

Question: Trying to install the Tizen SDK on Mac OS X Mavericks thru the Package Server and thru the SDK image (zip). In both instances it gives the error "the installmanager.conf or Package file cannot be saved" error towards the end. I tried doing the 'chown -R $USER ~/tmp' and 'sudo chown -R $USER ~/tmp' but it did not work.
Is there a work around or am I doing something wrong?Thanks
Answer: Guess, I found the solution: if the installation folder does not have permission then it throws weird errors. Install the sdk on a folder which has full permissions for the user.
Comment: feel free to accept your own answer if it solves problem you posted. And thanks for sharing solution!


Terraform dynamic group creation

Question: In my below terraform code I am trying to assign groups to the instances. But for the instances test1, test2 i am able to assign groups app1, app2, app3. But I want to assign groups app1,app2,app3 to test1 instance, groups t1,t2,t3 to test2 instance. Is there any logic that I am missing in the group_assignments block. Thanks.
locals {
  instances = [
    {
      instance  = "test1"
      baseUrl   = "url"
      subDomain = "sd"
      groups = [
        "app1",
        "app2",
        "app3",
      ]
},
    {
      instance  = "test2"
      baseUrl   = "url2"
      subDomain = "sd2"
      groups = [
        "t1",
        "t2",
        "t3",
      ]
},
  ]
}
resource "og" "press" {
  for_each = { for k, instance in flatten(local.instances[*].groups) : k => instance }
  name     = each.value
}
resource "ol" "press2" {
  for_each                   = { for k, instance in local.instances : k => instance }
  label                      = "press-${each.value.instance}"
  preconfigured_app          = "press"
}
resource "oag" "assignment" {
  for_each = { for k, instance in local.instances : k => instance }
  app_id   = ol.press2[each.key].id
  dynamic "group" {
    for_each = each.value.groups
    content {
      id = og.press[group.value].id
    }
  }
}

Answer: I think it should be:
resource "okta_group" "press" {
  for_each = toset(flatten(local.instances[*].groups))
  name     = each.value
}

This way you can refer to individual instances of okta_group, as okta_group.press["app1"], okta_group.press["t1"] and so on.
Comment: @Nikhilbrusli Sorry, but its not clear what you want. What does it mean "make this dynamic"? You are using dynamic blocks, there is nothing else for "dynamic" block creation.
Comment: @Nikhilbrusli I already explained in my answer what you should do. Did you try that?
Comment: @Nikhilbrusli There shouldn't be needed. Just try and post error if you get any.
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/238649/discussion-between-nikhil-brusli-and-marcin).

Terraform dynamic group creation


Why is there more than one major/minor scale in use?

Question: Sorry if this is a silly question, I'm a total newbie to music and trying to wrap my head around things. :)
From what I've learned, there is a pattern to all major/minor scales. For example, a major scale follows the pattern tone-tone-semitone-tone-tone-tone-semitone. For minor scales there were several variations depending on which type of minor scale you used.
So, like, a C major scale starts on C and follows this pattern, thus resulting in notes C D E F G A B. A D major scale starts on D and, following this pattern, results in D E F# G A B C#. Etc.
Now, any piece of music can be rewritten (transposed) to a different scale that follows the same pattern as the original simply by shifting all the notes by a certain amount of semitones. So, take a piece of music in D major, shift all notes down by 2 semitones, and you've got that same piece in C major.
What I don't understand is - unless you've got absolute hearing or are listening to the pieces side-by-side, you won't hear any difference between the two versions. It'll sound exactly the same, even to the most trained ear. So why bother with it? Why are there so many pieces of music in different scales when you could just transpose them all to the same scale?
Some ideas that I came up with on my own but wasn't convinced:

So that writing is simpler. But no - as long as you don't stray from the notes in the scale, you don't need to use any extra signs. Those are only used when you use notes outside the scale, thus they will be there in the same places no matter how you transpose.
To match the available range of a specific music instrument/voice. However they all span at least a few octaves, so why would you need to adjust so precisely? Just move them up or down by a whole octave. Unless the piece has a so wide range of sounds that it spans nearly all of the available sounds on the instrument/voice, but I think that's a pretty rare case. And anyway, most of those odd E-major-whatever pieces are for the piano which has the biggest range of them all.
When playing together several instruments, you might wish to have them play the same melody just a few (semi)tones apart for some specific effect. But then why do these scales then appear for pieces that are meant to be played solo (including all the piano exercises)?
Because some combinations of notes are easier played (as in the mechanical finger motion is simpler) in a specific scale. Doesn't seem convincing though, most instruments are pretty uniform, and it doesn't apply to voice at all.
Tradition?

So... is there a better explanation as to why so many different scales are employed today?
Comment: "It'll sound exactly the same, even to the most trained ear." - Sorry, but that is just wrong - though until *your* ears become "trained" you will have to take other people's word for it! "Most instruments are pretty uniform" - again, that is not true at all. Most instruments are extremely non-uniform. (As a straight forward example, take  the black and white keys on the piano, and the fact that humans have short thumbs and pinky fingers compared with the other three - so the short fingers "fit better" on the white keys not the black ones.
Comment: I think you are asking why there are different keys, not different scales. Different scales most assuredly _do_ sound different, even to untrained ears. Different keys sound different in temperaments other than equal temperament. Some keys lay better than others on different instruments. The nature of sound production for a musical instrument means that the actual sound made is different in different keys, i.e., if you have to play higher-up on the instrument to fit a key into the instrumental range, the timbre changes. And, given that we have 12 tones to work with, the keys are just there.
Comment: The [Levitin effect](https://en.m.wikipedia.org/wiki/Levitin_effect) indicates that *close to everyone* can hear the difference between (major) keys well enough to remember that certain pieces are in different keys from each other.
Comment: Also, in various musical contexts, you *will* be hearing the same melody in different keys in relatively quick succession (e.g. both major). Listen to the famous first movement of Beethoven's Fifth Symphony and you'll hear the famous opening bars in C minor and F minor, then the major-key section in E flat major and C major. Play *Mario Kart: Double Dash!!* for one course and you'll hear the music go up one semitone (typically) in the final lap.
Comment: First - Keys vs scales - I'm not sure, what's the difference? I mean things like "C major", "D major", etc. Those are scales, aren't they? Second - yes, I'm talking about equal temperament. It didn't occur to me to specify this since it's so ubiquitous today, but I guess it should be noted. Third - so... all of my guesses are right?
Comment: Confusingly, "C major" can mean both a key and a scale. An (oversimplified) description of the difference is that a "key" is a *collection* of notes, plus some conventions (in much of western music at least) about ways to use different sequences of chords made from selections of those notes. A "scale" is a sequence of single notes in a particular order. Major scales use all the notes of the corresponding major key, but there is more than one sort of minor scale, and some minor scales (like the so-called "melodic minor") use *different* notes from the minor scale when ascending and descending.
Comment: ... there are also "scales" which use notes that are *not* all in one "key" - for instance chromatic scales (all 12 notes), whole-tone scales (C D E F# G# A# C), octatonic scales (C D Eb F F# G# A B C), and many of the scales used in folk music in different countries and regions of the world.
Comment: Your first guess is often (but not always) right. The others are right IMO - but your reasons for making the guesses were not all right, as the comments and answers have pointed out!
Comment: " It didn't occur to me to specify this since [equal temperament] is so ubiquitous today" - yes, in western popular music (and also the most popular type of western "classical" music). In the rest of the world, not so much!
Comment: @Dekkadeci Great reference about the Levitin effect.  I find sometimes if I don't know a song as well, I will remember it in a different key that is a close harmonic relative to the correct key.  A lot of people said to be "tone deaf" also appear to be hearing in this type of relative-key even when actively listening or singing along.  Anyway, very interesting to see that the effect is not well studied.
Answer:
What I don't understand is - unless you've got absolute hearing or are listening to the pieces side-by-side, you won't hear any difference between the two versions. It'll sound exactly the same, even to the most trained ear.

There's many reasons, but your premise here is false. You may not be able to tell the exact key if you don't have absolute pitch, but a trained musical ear will still notice differences to the warmth, timbre and other qualities of the sound regardless.
In addition:

Some keys are easier to play on some instruments than others, especially those instruments not in C - so your point that "most instruments are pretty uniform" is also not correct.
Many pieces will transition between keys in different sections, so you can't just have one key if you (for instance) want to transpose up a minor third for an interlude.
Some instruments simply sound better (or at least different) in different keys. On a violin for example there's a very distinct sound obtained by using open strings, but you've only got four to choose from! If you force everything to be written in C, then want the sound of an open string on the tonic... you're out of luck.
Comment: Disagree slightly with the second sentence -- all except the very most tone-deaf will be able to tell a difference, even if they don't know what the difference is.
Comment: @MatthewRead - your comment puts me into the very most tone deaf category. Thanks! I've been a muso for 60 odd years! If I play a piece in G that's supposed to be in Ab, I doubt most people would notice without an external reference.


Terraform creates local tfstate when using remote backend

Question: I defined remote backend for managing tfstate with Swift.
terraform {
  backend "swift" {
    container = "example"
  }
}

After I run "terraform init", I get following error sometimes:
Do you want to copy existing state to the new backend?
Pre-existing state was found while migrating the previous "swift" backend to the
newly configured "swift" backend. An existing non-empty state already exists in
the new backend. The two states have been saved to temporary files that will be
removed after responding to this query.

Previous (type "swift"): /tmp/terraform704677678/1-swift.tfstate
New      (type "swift"): /tmp/terraform704677678/2-swift.tfstate

Do you want to overwrite the state in the new backend with the previous state?
Enter "yes" to copy and "no" to start with the existing state in the newly
configured "swift" backend.

Enter a value:

This really makes hard to automate running Terraform because of unexpected input required.
I need Ansible to operate only with remote tfstate saved in container and no local files.
After terraform init task is finished, there is no /tmp/terraform*.
Thanks in advance for help.
Answer: Looks like you're working with two state files. If you're sure it's trying to use the correct one now, you can say yes and have it copy the old state to the new, then this error won't show up again.
Comment: No matter "yes" or "no" answer, it will appear randomly again.
Answer: Problem was fixed in next version of OpenStack provider.


Finding the limit of $\left(\dfrac{a^\frac{1}{n}+b^\frac{1}{n}+c^\frac{1}{n}}{3}\right)^n$

Question: I'm trying to solve this limit, for which I already know the solution thanks to Wolfram|Alpha to be $\sqrt[3]{abc}$:
$$\lim_{n\rightarrow\infty}\left(\frac{a^\frac{1}{n}+b^\frac{1}{n}+c^\frac{1}{n}}{3}\right)^n:\forall a,b,c\in\mathbb{R}^+$$
As this limit is an indeterminate form of the type $1^\infty$, I've been trying to approach it by doing:
$$\lim_{n\rightarrow\infty}\left(\frac{a^\frac{1}{n}+b^\frac{1}{n}+c^\frac{1}{n}}{3}\right)^n=\lim_{n\rightarrow\infty}\left(1+\frac{a^\frac{1}{n}+b^\frac{1}{n}+c^\frac{1}{n}-3}{3}\right)^n=\lim_{n\rightarrow\infty}\left(1+\frac{1}{\frac{3}{a^\frac{1}{n}+b^\frac{1}{n}+c^\frac{1}{n}-3}}\right)^n=\lim_{n\rightarrow\infty}\left(1+\frac{1}{\frac{3}{a^\frac{1}{n}+b^\frac{1}{n}+c^\frac{1}{n}-3}}\right)^{\frac{3}{a^\frac{1}{n}+b^\frac{1}{n}+c^\frac{1}{n}-3}\cdot\frac{a^\frac{1}{n}+b^\frac{1}{n}+c^\frac{1}{n}-3}{3}\cdot n}=e^{\lim_{n\rightarrow\infty}\frac{a^\frac{1}{n}+b^\frac{1}{n}+c^\frac{1}{n}-3}{3}\cdot n}$$
But now when I approach that top limit this is what I get:
$$\lim_{n\rightarrow\infty}\frac{a^\frac{1}{n}+b^\frac{1}{n}+c^\frac{1}{n}-3}{3}\cdot n=\lim_{n\rightarrow\infty}\frac{n\cdot a^{\frac{1}{n}}}{3}+\frac{n\cdot b^{\frac{1}{n}}}{3}+\frac{n\cdot c^{\frac{1}{n}}}{3}-n=\lim_{n\rightarrow\infty}\frac{n\cdot a^0}{3}+\frac{n\cdot b^0}{3}+\frac{n\cdot c^0}{3}-n=\lim_{n\rightarrow\infty}\frac{n}{3}+\frac{n}{3}+\frac{n}{3}-n=0$$
And hence the final limit should be $e^0=1$ which is clearly wrong but I honestly don't know what I did wrong, so what do you suggest me to solve this limit?
Comment: http://math.stackexchange.com/questions/397376/find-the-limit-lim-n-to-infty-left-fraca1-nb1-nc1-n3-righ
Comment: The problem with your approach lies in the step when you add three infinities ($n/3$) and subtract another infinity ($n$) from them.
Comment: consider that $a^{1/n}\to 1$ as $n\to\infty$
Comment: @Peter Oh I didn't think that substraction wouldn't be legit, thanks for pointing it out.
Answer: By Taylor series we have:
$$\frac{a^\frac{1}{n}+b^\frac{1}{n}+c^\frac{1}{n}}{3}=\frac 1 3\left(3+\frac1 n(\log a +\log b+\log c)++o\left(\frac 1 n\right)\right)=1+\frac 1 n \log\sqrt[3]{abc}+o\left(\frac 1 n\right)$$
so
$$\left(\frac{a^\frac{1}{n}+b^\frac{1}{n}+c^\frac{1}{n}}{3}\right)^n=\exp\left(n\log\left(1+\frac 1 n \log\sqrt[3]{abc}+o\left(\frac 1 n\right)\right)\right)\sim_\infty \sqrt[3]{abc} $$
Comment: Taylor again helps here+
Answer: While $\sqrt[n]a\to 1$, it is not correct to say $(n\sqrt[n]a-n)\to 0$. Actually, $\sqrt[n]{1+\epsilon}\approx 1+\frac1n\epsilon$ so $n\sqrt[n]a-n\approx a$.
Comment: Oh thats a pretty neat approximation, I'll keep that in mind for the future, though is that approximation easy to obtain?
Answer: This is not an answer to the question itself I think, but still a useful observation.
This can be found using the Generalized means. Say that
$$
M_p(x_1,\dots,x_n)=\left(\frac 1n\sum x_i^p\right)^\frac 1p
$$
In general, we have $M_m(x_1,\dots,x_n)\geq M_n(x_1,\dots,x_n)$ when $m\geq n$, with equality if and only if $x_i=x_j$ for all $i$ and $j$. Also, (I now realize THIS is your question, although I'll just assume it's true), we have
$$M_0(x_1,\dots,x_n)=\sqrt[n]{x_1\cdots x_n}$$
Thus, we have
$$\lim_{p\to 0} M_p(a,b,c)=M_0(a,b,c)=\sqrt[3]{abc}$$
Comment: Thanks for the observation Ragnar, it's interesting indeed ;)
Answer: Fact I.
$$
\lim_{n\to\infty}\left(1+\frac{a}{n}+\frac{b}{n^2}\right)^{\!n}=\mathrm{e}^a.
$$
Fact II. For every $a>0$, there exists a $b>0$, such that
$$
1+\frac{\ln a}{n}\le a^{1/n} \le 1+\frac{\ln a}{n}+\frac{b}{n^2}.
$$
Using the two facts:
$$
1+\frac{\ln a+\ln b+\ln c}{3n}\le\frac{a^{1/n}+b^{1/n}+c^{1/n}}{3}\le
1+\frac{\ln a+\ln b+\ln c}{3n}+\frac{k}{n^2}
$$
and hence
$$
\left(1+\frac{\ln\sqrt[3]{abc}}{n}\right)^{\!n}\le
\left(\frac{a^{1/n}+b^{1/n}+c^{1/n}}{3}\right)^{\!n}
\le\left(1+\frac{\ln(\sqrt[3]{abc})}{n}+\frac{k}{n}\right)^{\!n}
$$
and as the both the left and right hand side tend to $\sqrt[3]{abc}$, so does the middle one.


Como fazer uma função que "chama" um html

Question: Estou me aprimorando no html e JavaScript ao mesmo tempo que crio um projeto meu. Não sei se minha pergunta está da forma correta, mas estarei explicando da melhor forma.
Estou criando uma ferramenta para auxiliar os turnos de combate em RPG de mesa, para isso estou usando html e css para criar cards contendo informações dos personagens e monstros, só que o código acaba ficando enorme e com muitas linhas repetidas.
Os cards estão seguindo esse padrão:

 1º

     <input placeholder="Nome" class="inpNome">

           <button class="btnDano">Dano</button>
           <input type="number" min="0" class="inpValor">
           <button class="btnCura">Cura</button>

                  <input placeholder="0" class="varLife">
                  /
                  <input placeholder="0" class="lifeTotal">

                 <input placeholder="0" class="varEscudo">
                 /
                 <input placeholder="0" class="escudoTotal">

Perception

15

Investigation

12

Insight

13

Com isso estava pensando numa forma de salvar as informações dos mobs prontas em outro arquivo para diminuir o tamanho do código. Tipo ter vários arquivos html contendo informações de mobs diferentes, exemplo: minotaur.html, goblin.html ..., e deixar apenas o card vazio no código principal pronto para receber as informações do monstro ou personagem clicando em um botão.
Dessa forma:

 6º

      <input placeholder="Nome" class="inpNome">

         <button onClick="puxar informações">

Aceito dicas de como melhorar o código, como resolver o problema, links para estudar.
Comment: Aparentemente você pode usar o `template` e o `slot`: https://developer.mozilla.org/en-US/docs/Web/Web_Components/Using_templates_and_slots.
Answer: Tudo bem?
Vamos lá ver, pelo que eu entendi você quer carregar num botão e mudar as informações do html, certo? Se for isso que você quer fazer, eu posso dar um exemplo:

carta

Dano:

<button type="button" onclick='document.getElementById("damage").innerHTML = "110"'>monstro 1</button>

<button type="button" onclick='document.getElementById("damage").innerHTML = "250"'>monstro 2</button>

Comment: Tá mais para pegar o trecho do código contendo informações do card em outro arquivo html e renderizar ela no card. Mas o que você disse tbm é bem útil.


Ritardando, Rallentando, and Allargando

Question: Three common musical markings for gradual slowing down are ritardando, rallentando, and allargando. How do these differ from each other in interpretation and execution? For example, I was taught many moons ago that where ritardando meant to slow down gradually, rallentando meant to slow down more dramatically, but others have said that rallentando can be more gradual, still allowing for rubato and such effects.
Is there a most common interpretation of these, or is it really up to the performer how it comes out? Does the execution change by the period of the music being played (e.g., a rit. in a Classical piece being more measured than the same in a Romantic one)?
Answer: Ritardando and rallentando both mean gradually getting slower and according to my AB guide to music theory book they are both supposed to imply a gradual slowing down. And allargando means broadening, implying getting a little slower and probably also a little louder.
Without a doubt execution sometimes changes in some cases, since words can change meaning over time. For example, ritenuto originally meant an abrupt change, although now it carries the same meaning as rallentando or ritardando.
However, to my knowledge and access to information, I could not find any reliable citation anywhere that states that rallentando and ritardando may be interpreted differently. However, there is this blog where some worthwhile digging around has been done and the researcher indicates that there may be a subtle difference between the two words, as they are two different words of the Italian language. From an Italian-English dictionary the author found:

Ritardare: "be late, wait, retard, lag, stay, lose, delay, set back, defer, put off."
Rallentare: "slow down, reduce speed, slacken, slow, die down, decelerate, check, put back."

This implies that ritardando seems to be a deliberate slowing or being late, while rallentando seems to be more of a letting go or dying away.(although it becomes similar to smorzando and raising the same question all over again).
Therefore, I come to the conclusion that composers may have used all three words differently but what the differences were, especially between rallentando and ritardando (discounting allargando as my book has given distinct directions on that), might be too subjective and individual specific to define properly and therefore, if one must be pedantic, it is best to leave it to experts who have studied the composer to give the final opinion. The blog gives an idea on this. So yes, it should vary slightly not just from era to era but also from composer to composer.
Comment: "Ritardare" is like reining in a horse. The animal *wants* to go stampeding off, and you actively prevent it. "Rallentare" is simply any slowing down - even a rolling ball will slow down over time, but there is no willpower and no conflict involved. That may or may not be helpful in deciding how you interpret one of these "slow down" indications.
Comment: Kilian: great description.  That helps me.
Comment: What? When did ritenuto change meaning? And why did nobody tell my piano teacher?
Answer: Yesterday a young American choral director said that the difference between ¨rallentando¨ and ¨ritardando¨ was that the first implies a diminishing of the volume as well as a slowing down of the tempo. I kept myself back from telling him that he was wrong, that I'm fluent in Italian and lived 20 years in Italy, that I've sung with prominent conductors (e.g. Riccardo Chailly at La Verdi di Milano), and that in my opinion they were synonyms. Instead I decided to do some research and find out if he knew of something that had previously eluded me.
Well, I spent at least two hours researching and my conclusion is that there is some validity to his claim. "Rallentare" has a secondary meaning of dying away, or losing inertia, whereas "ritardare" means to make late. Emma, Azid, and Kilian's answers to this thread are the most enlightening. I think this is not common knowledge and most modern composers use the two terms synonymously, even in Italy. I'll be visiting there this summer and I'll talk with some musicians and update this post.
Answer: Looking at the translations from Italian, I would say ritardando "holds back" the tempo to build tension and rallentando slows the music to a conclusion (decelerate, die down). I have noticed that rall. appears at the end of pieces or sections, where rit. appears before a tempo in the middle of a phrase or section. Examples:
1. Mozart's Magic Flute ( Die Zauberflöte, K.620) For a Girl or a Woman (Ein Mädchen oder Weibchen) has a rall. at the end.
2. Prokofiev The Cat, from Peter and the Wolf, which has both poco rit. where the cat is moving stealthily and rall. at the end.
Answer: Oxford Dictionary of Music gives the following help.
RITARDARDE, RITARDANDO, RITARDATO (It.) 'To hold back.' 'Holding back' Held back.' (gradually, ie the same as as Rallentando.)
ALLARGANDO (It.) 'Enlarging', ie getting slower and slower and fuller in tone.
Source THE OXFORD COMPANION TO MUSIC 10TH EDITION.
Answer: Being a very visual person, I like to think of things graphically. I visualize "ritardando" as being a straight linear slope, whereas "rallentando" is more of a parabolic curve.
When choosing which one to write, the most important distinction in either case is knowing what the target is. Then you can implement the best tool to convey the correct sound.
Answer: Every composer writes whatever the heck he wants.  Ultimately we have to try to get into his head and FEEL what he wanted.  However, I will give you my knee-jerk reaction to these terms when I come across them while sight-reading in an ensemble situation.  I tend to think of rallentando as not particularly subtle.  Ritardando could be subtle or it could be not subtle.  Allargando, to me, has potentially a theatrical, dramatic (pompous) feel.  I speak Spanish, which sometimes gives me a helpful clue for Italian.  In Spanish, 'alargar' (the verb), talks about making something longer.  So when I see this in a piece, my first reaction will probably be that I need to get significantly slower, and lengthen the notes in a dramatic way.
It's different when I'm studying a difficult solo piece.  There I experiment with singing and conducting the phrase that has to slow down, so I can discover what seems to work well.

Does the execution change by the period of the music being played (e.g., a rit. in a Classical piece being more measured than the same in a Romantic one)?

Romantic pieces can have lots of rubato, lots of ebb and flow (which is not necessarily marked in the piece).  Think Chopin!  Classical -- often a more structured tempo.

Ritardando, Rallentando, and Allargando


Sharepoint 2007 - Webpart - Add New Item

Question: We are using SharePoint Server 2007 to maintain a calendar. There is a view that contains a webpart (Agenda, see picture) with a 'Add New Item' (Nieuw Item Toevoegen) button.
On the left side, you will see a list of dates. When we select a date, eg. 10/12/2013 and click 'Add New Item' below, the new Item isn't added to this date, but to the date closest to the current date of today.
This ONLY happens in Internet Explorer (8, 9, 10). In FireFox/Chrome, the item is added to the correct date.
I'm not a SharePoint hero so I have no clue where to start. Can I change/check this behaviour somewhere?
Answer: It looks like SP3 for Sharepoint solved this problem.


Sum of Hour and Time value in diffrent column in excel 2010

Question: I have an Excel file which contains two columns for hours and minutes, like:
hr |min
---+---
 7 |  2
10 | 16
 9 | 12

I would like it to present in additional column as
07:02
10:16
09:12

How to do that in Excel 2010?
Answer:     A         B      C
1   hr       min  hr:min
2   1          2
3   2         12
4   3         15
5   10        45

click on the cell C2 and put follwing formula at the formula bar and drag it for other rows.
=CONCATENATE(CONCATENATE(IF(A2 >9, A2, CONCATENATE("0",A2)),":"),CONCATENATE(IF(B2 >9, B2, CONCATENATE("0",B2))))

To get Sum of the of hr:min column
click on the cell where you want to display total and put follwing formula at the formula bar.
=CONCATENATE(CONCATENATE((SUM(A2:A5) + INT(SUM(B2:B5)/60)),":"),MOD(SUM(B2:B5),60))

Comment: Hello Vijendra, this formula works to bring in required format, but it doenst allow me to sum all and get total of all hours and mins.
Comment: you want to sum after bringing them in required format,you didn't write that in the question.
Comment: just go through the answer again, I have write a formula to sum these values.
Comment: Vijendra, i am sorry to bother you again, with first formula, it brought value as hr:min in column C.. as per example above, it will fill value from C2 to C5, at C6, i am looking for total of hours (above range C2:C5), that is not happening :(
Comment: second formula gives you total hr:min. do you want hours only?
Comment: second formula gives very big numbers (5.0368287037037:10.9775578703704),   its not look like HR:MIN format..  i have tried all possible formats plus searched on net..  i have image but i dont know how to attach it with comment.
Answer: Here you go
=SUM(TIME(A2,B2,0))


Altering relationship in Views contextually

Question: I need to alter a Views relationship contextually: since the View is embedded into another node, the relationship is defined by a field's value of a parent node.
I presume the only way to add a relationship is using hook_views_data_alter, but I'm not quite sure if it's going to work inside a preprocessor function (I'm creating a View for a certain node type) and what's the proper way of using it. The related field will be a Nodequeue instance (Nodequeue module is integrated with Views using relationships), its name will be contained in that parent node's field.
Thanks in advance!
Answer: I did eventually discover simple solution, so perhaps it comes in handy for anyone else later. views_data_alter, of course, is not meant to apply an existing relationship, but rather to create a new one. To apply an existing relationship programmatically - Nodequeque in my case - you need to call in add_item function of view class:
<code>$view->add_item($view->current_display, 'relationship', 'node', 'nodequeue_rel', array('names'=>array('myqueue'=>'myqueue'), 'required'=>1, 'limit'=>1))
</code>
where an array is a set of options like: the name(s) of queue(s) and whether any nodes excluded from chosen queque(s) should be added (1 - bool - implies that only nodes inside the chosen queque will be added).


Kendo Charts : How to create a Heat Map?

Question: Is there a way to create a Heat Map like FusionCharts, but with Kendo UI ?
Here is what I need : http://www.fusioncharts.com/charts/heat-map-charts/
I didn't find a way yet, and it seems that the Kendo team is still on the subjetct (since 2011). But if you found a solution, I'm interested !
Thanks !
Answer: I found a solution, but it's a workaround.

I used the TreeMap chart, putting every rows value to 1 so they get all the same size.
I used the kendoTooltip() method to add a tooltip to every rows
I used the Chroma library to handle the colors, using it in the DataBound function.

The problem is that it can't be exported to PDF.


After adding the Google Drive v2 APIs to android project, error Multiple dex files define Lcom/google/api/client/http/HttpContent;

Question: I've tried looking all over the place but I cannot figure out why this error is coming up after all I do is add the Google Drive API from the Google Plugin via Eclipse (Juno). When I clean the project the error doesn't appear. It is only when I go to run the Android application. I have been trying to follow the steps available at https://developers.google.com/drive/quickstart-android
just to get the API and have also added the .jar/build path for Play Services.
This is the exact code that appears:
[2012-12-18 00:49:57 - Dex Loader] Unable to execute dex: Multiple dex files define Lcom/google/api/client/http/HttpContent;
[2012-12-18 00:49:57 - Intro] Conversion to Dalvik format failed: Unable to execute dex: Multiple dex files define Lcom/google/api/client/http/HttpContent;

I think this is related to duplicate dependencies to some level but I don't know which ones I should be keeping or deleting. Furthermore, I have already tried deleting the bin folder before adding the APIs and restarting, and it is not in the build path either. Below is a screen shot of the two libraries.
http://d.pr/i/tYvs
Any suggestions would be most appreciated!
Answer: You most likely have to jars that include the same classes (possibly different versions). Check the contents of the libs/ folder and remove any duplicates. Or just start from scratch or a known working sample.
Comment: I just tried deleting all the duplicates and it still came up with this error. The app itself is already fully functional on other services and I am just trying to add a the Google Drive API library. Is there a better solution than pulling everything directly from the plug in?
Comment: The Google Drive plugin is likely not designed to work with Android. For Android (ADT), you need to have all jars under `libs/` and it will even point out the duplicates. Take a not of the jars and copy them under `libs/`.


Connecting to mysql from c# gives me null exception

Question: I have this code:
 con.Open();
 cmd = new MySqlCommand(String.Format("SELECT concat(name,'|',lastname) FROM {0} WHERE ID= ?Parname;", ConfigSettings.ReadSetting("my_data")), con);
 cmd.Parameters.Add("?Parname", MySqlDbType.VarChar).Value = id_value;
 var tokens = ((String)cmd.ExecuteScalar()).Split('|');
 name = tokens[0];
 lastname = tokens[1];

This is working perfectly when I enter id value and when user is actually in database. But I got null exception when there is no such a user inside the database. I need to make this to write me a unknown user if he is not in the database.
Comment: Wait, you want to get information from the database when the information doesn't exist??  That doesn't make any sense.  You get a null reference exception because (presumably) the call to `ExecuteScalar` returns null because the row you are looking for doesn't exist in the database, which from your description is exactly what you're expecting.
Answer: If there's no user with the given id, the return value of ExecuteScalar is DBNull.Value:
var result = cmd.ExecuteScalar();
if (result != DBNull.Value)
{
    var tokens = ((String)result).Split('|');
    name = tokens[0];
    lastname = tokens[1];
}
else
{
    name = "unknown";
    lastname = "user";  // or whatever
}

Comment: Thank you this code is working. I needed to change `DBNull.Value` to a `null` to work.


Can't get access to http://localhost:80 on running apache server

Question: On running apache server in ubuntu 14.04 I get "This webpage is not available" in browser or "curl: (7) Failed to connect to localhost port 80: Connection refused" using $ curl localhost. Besides I can connect to 127. * . * . *  (e.g. 127.0.0.2) - doesn't work only 127.0.0.1
/etc/hosts
 127.0.0.1  localhost
 127.0.1.1  al-ubuntu
 # The following lines are desirable for IPv6 capable hosts
 ::1     ip6-localhost ip6-loopback
 fe00::0 ip6-localnet
 ff00::0 ip6-mcastprefix
 ff02::1 ip6-allnodes
 ff02::2 ip6-allrouters

ports.conf
Listen 80

<IfModule ssl_module>
   Listen 443
</IfModule>

<IfModule mod_gnutls.c>
  Listen 443
</IfModule>

When I change port e.g. Listen 82 then I can connect to localhost:82 or 127.0.0.1:82
There are no any processes using port 80, except apache2:
$sudo netstat -tulpn | grep 80
=> tcp6       0     0 :::80      :::*         LISTEN      7127/apache2
There are three files in /var/log/apache2/:
access.log, error.log and other_vhosts_access.log

When restarting apache2: $ tail -f error.log
 [Thu Feb 19 16:03:19.570066 2015] [mpm_prefork:notice] [pid 1285] AH00169:
 caught SIGTERM, shutting down
 [Thu Feb 19 16:03:20.673519 2015] [mpm_prefork:notice] [pid 3454] AH00163:
 Apache/2.4.7 (Ubuntu) PHP/5.5.9-1ubuntu4.6 configured -- resuming normal
 operations
 [Thu Feb 19 16:03:20.674355 2015] [core:notice] [pid 3454] AH00094: Command line: '/usr/sbin/apache2'

When connecting to localhost in all log files - nothing.
I installed apache on other ubuntu14.04 system and all works.
What cause blocking port 80, do you know in what the problem is?
Comment: Can you tail the Apache error log when you restart it and when you try connecting and it doesn't work?  tail -f /var/log/apache2/error.log
Comment: ratsbane, I added this information to the question.
Comment: did you have firewall on server ? you should check selinux and os firewall (iptables) status
Answer: I had the same problem.
In my apache's httpd.conf file, I had
Listen 22.214.171.124:8000

then I changed it to:
Listen 8000

and it worked both with localhost and with the ip address.
Answer: This question related to https://serverfault.com/questions/670575/failed-to-connect-to-127-0-0-1-port-80.
No any process blocking port 80. Problem related to firewall NAT rules which are redirecting connections to 80 port to another disabled port. It fixed with removing these rules.
Comment: Not really. In my case the firewall is not even enabled
Comment: Edited: for those who are using "iptables", make sure to run `iptables -L` to see if there is any rule available. Services like `iptables`, `firewalld`, `ufw` while not running - their rules may still enforce.


Debian virt/res/shr and cpu time limiting

Question: Servers have multiple users running multiple programs, some of which don't seem to behave and will eat up RAM like there is no tomorrow, for example:
  PID USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND
30091 xxxx 20   0 2194m 1.4g 1.4g S   21  9.0   0:56.03 aaaaa
30212 xxxx 20   0 1460m 1.1g 1.1g D    5  6.9   0:44.12 aaaaa

We have filesystem quota setup, otherwise nothing else that I know of. I'd like to be able to limit VIRT RES SHR (perhaps just limiting 1 will limit the other 2?). Is this possible?
As well I would like to limit cputime before command is terminated (actually the command is called by another script, I assume the father script won't be terminated?).
I've had a look at limits.conf and PAM stuff, but not sure what is the best way, and how to test.
Comment: Also, it has to be outside of limits.conf or whatever, as the users have non-interactive logins/scripts. I tested some things in limits.conf but they don't work due to this.
Answer: You want setrlimit(RLIMIT_AS, ...).  From the manpage (setrlimit(2)):

RLIMIT_AS
The maximum size of the process's virtual memory (address space) in bytes.  This limit affects calls to brk(2), mmap(2) and mremap(2),  which fail with the error ENOMEM upon exceeding this limit.  Also automatic stack expansion will fail (and generate a SIGSEGV that kills the process if no alternate stack has been made available via sigaltstack(2)).  Since the  value is a long, on machines with a 32-bit long either this limit is at most 2 GiB, or this resource is unlimited.
Comment: cool I will try that.
Comment: uhm how do I actually use that? it seems to be in C code? I needed something for limits.conf or similar?


Problema ao gerar gráfico em javascript usando Spring

Question: Estou implementando graficos em uma aplicação web que estou desenvolvendo em Spring. Já fiz minha API, está trazendo o Json com todas as informaçoes do meu objeto Carrinho, porem o gráfico não está sendo gerado na pagina html. Alguem pode me ajudar a resolver este problema? Ele não apresenta nenhum erro no console.
Pagina html, onde o usuário escolhe o mes que ele quer ver o gráfico.

Meu serviço.
@RequestMapping(value = "/vendas", method = RequestMethod.GET)
public ResponseEntity<?> vendas(Long id, int valor) throws ParseException {
    Usuario user = userService.findByEmail(SecurityContextHolder.getContext().getAuthentication().getName());
    List<Carrinho> carrinhos = carrinhoService.findByRelatorioVenda(user.getId(), valor);
    if (carrinhos.isEmpty()) {
        return new ResponseEntity(new CustomErrorType("400"), HttpStatus.NOT_FOUND);
    }
    System.out.println(carrinhos);
    return new ResponseEntity<List<Carrinho>>(carrinhos, HttpStatus.OK);
}

Meu html:

Estatística anual

Resposta da API:
Comment: O que você quer mostrar no gráfico? tem varias informações sendo retornadas no serviço, e vc está colocando tudo no gráfico `"dataProvider" : data`
Comment: quero pegar somente os items dataEntrega e localEntrega
Comment: Eu entendi que vc quer a qntidade de ovos por bairro certo?
Comment: Quantos graficos vc tem na mesma tela? Pode ser que esteja assossiando multiplos graficos na mesma variavel. uma forma simples, seria vc pegar o resultado da sua request (data/dataProvider) e colar ele em alguma demo do proprio AmCharts e ver se sua estrutura esta certa. O funcionamento do AmChart eh muito simples, e a maior parte das vezes o problema esta na estrutura dos dados, ou alguma configuracao do grafico que esta utilizando.
Answer: O serviço aparentemente está ok. Logo, de acordo com a pergunta, avaliei o front e gostaria de recomendar algumas correções.

Vc não disponibilizou o css e caso não saiba é necessário colocar as dimenções na div, pq sem elas o gráfico nao aparece
#chartdiv1 {
  width: 100%;
  height: 500px;
}
Relacionando o gráfico para representar ovos por bairro, vc deve colocar o dataProvider. Na pergunta vc colocou o retorno do serviço diretamente e ficou dificil de entender.

var dataProvider = [
  {
    'bairro': 'centro',
    'qtdovos': 5
  },
  {
    'bairro': 'lapa',
    'qtdovos': 10
  },
  {
    'bairro': 'Copacabana',
    'qtdovos': 16
  }
];

var chart = AmCharts.makeChart("chartdiv1", {
    "theme" : "light",
    "type" : "serial",
    "startDuration" : 2,
    "dataProvider" : dataProvider,
    "valueAxes" : [ {
     "axisAlpha": 0,
      "position" : "left",
      "title" : "quantidade"
    }],
    "graphs" : [ {
      "balloonText" : "[[category]]: [[value]]",
      "fillColorsField" : "color",
      "fillAlphas" : 1,
      "lineAlpha" : 0.1,
      "type" : "column",
      "valueField" : "qtdovos"
    } ],
    "depth3D" : 20,
    "angle" : 30,
    "chartCursor" : {
      "categoryBalloonEnabled" : false,
      "cursorAlpha" : 0,
      "zoomable" : false
    },
    "categoryField" : "bairro",
    "categoryAxis" : {
      "gridPosition" : "start",
      "labelRotation" : 0
    },
    "titles" : [{
      "text" : "Quantidade de ovos por bairro"
    }],
    "export" : {
      "enabled" : true,
      "menu" : []
    }
});
#chartdiv1 {
  width: 100%;
  height: 500px;
}

.amcharts-export-menu-top-right {
  top: 10px;
  right: 0;
}

<link rel="stylesheet" href="https://www.amcharts.com/lib/3/plugins/export/export.css" type="text/css" media="all" />

Caso queira outras informações no gráfico altere a categoryField e o ValueField com a key do json do serviço.


Why do batters sometimes chase balls well outside the strike zone?

Question: Here, I'm not talking about balls that barely miss the strike zone, being barely outside the plate or below the knees. More like pitches that go into the dirt, or six inches wide of the plate.
What makes batters sometimes chase such pitches? Do they really believe that they can hit them? Or has the pitcher fooled them into believing that they will be called strikes even when they miss by a wide margin?
Comment: It really depends on the batter, and so many other circumstances. If the hitter is on a hitting streak, they probably feel more comfortable making contact with more poorly thrown balls. Or, if you're [Vladimir Guerrero](http://en.wikipedia.org/wiki/Vladimir_Guerrero#Batting_style), you'll just swing at pitches in the dirt because you tend to hit home runs off of them....
Answer: First off, the strike zone is a mystical thing sometimes. While there are specific guidelines, some umpires change it a little based on the height or size of the batter. Most of the time, batters swing at these pitches because from the pitchers windup, they thing it will be a strike. They follow the ball usually as it passes the ear of the pitcher (left for a southpaw and right for a righty) Some pitches such as a slider, fake the batter out by appearing to come down the plate, but fall lower than anticipated, hence the name. A change up or off speed pitch do the same to a batter from their view. They believe that they will cross the plate in the strike zone, therefore they take a whack at it but often whiff if they don't realize the style of pitch. Most good batters can tell when an off speed pitch is coming down the pike, and plan for it, holding off or taking a swing. Hope this helps to clear things up.
Answer: I think the biggest reason no one has touched upon, besides the obvious difficulty in judging a pitch to be far out of the strike zone or not is the hit and run play.
If there is a runner on base and this play is called the batter will (and should) swing at any pitch unless it is egregiously hard to hit. (Sometimes they still swing to throw off the catcher and make throwing out the runner a little more difficult).
The whole point of a hit and run is that the man on base will be taking off as soon as the pitcher goes and will prevent a double play if the batter hits a routine ground ball (hopefully). If the batter manages a hit the runner might even be able to score from first or second on a hit which he would normally not. If the batter doesn't make contact then the runner could be thrown out, technically caught stealing.
Answer: On average, it takes about 4 tenths of a second for a ball to cross the plate after it leaves the pitcher's hand.  In that time, the batter needs to determine if the pitch is going to be hittable, where the pitch is going to cross the plate and then get their bat around in the time and place to hit it where they want to hit it.  With such a smaller window available to make multiple decisions and react, it's only understandable that they'd make the wrong decision and over commit to swing at a terrible pitch.


Push new registry keys via group policy

Question: Recently I have added registry keys in active directory and I need to push them via group policy instead of going to each PC to apply the new ones.
How can I push new registry keys (not modify existing ones) via group policy?
Note: I'm using Windows Server 2003 64 bit and my clients are running Windows XP Professional.
Answer: There is no built-in feature in Windows Server 2003 GPOs to configure custom Registry keys.
You can either use a startup/logon script to import a .REG file, or create a custom administrative template which will act on the keys you need to modify.
Comment: Massimo could you please read down what I faced the problem! and how can I create a custom administrative template?Thanks
Answer: I solved but I didn't understand how it works!.I have windows 7 pro and I have installed administrative tools of 2008 in group policy management I created new policy so inside group policy management of windows 2008 there are new features for registry Computer Configuration --> Preferences --> Windows setting --> Registry from there you can push new policies but don't ask how I can use this feature and my windows server is 2003! if any one can explain to me?
Comment: You're using something called Group Policy Preferences (GPP) which is an extension to regular Group Policy. Your target computers will only receive the settings if they have the GPP update installed. http://www.microsoft.com/download/en/details.aspx?id=24449
Answer: Add this to your netlogon folder then create a logon gpo to run the batch. Change the registry key and location and name of file to whatever you call them.
<code>REG QUERY hkcu\software\microsoft\windows\currentversion\run /v restart_sticky_notes
IF %errorlevel%==0 GOTO skip_reg_inport
regedit.exe /s \\server\registry_folder\regfile.reg
:skip_reg_inport
</code>
Comment: So I have to write another question to explain where netlogon share folder disappeared.Thanks alot for your support and i will come back later
Comment: Well it seems i have another problem why i didn't see netlogon? in this case what is have to do? thanks for your help
Comment: The netlogon folder is on any of your domain controllers default share. If you're missing that, that's a whole other issue and would be best addressed in another question. You basicly want to drop your script and your .reg file into a shared folder so all of your workstations can access it. Then make sure to point to those locations in your GPO logon script, and the regedit import.
Answer: What I would do (Personal Experience only) is the following:
Export the registry settings.
Log On / Log Off user settings for each user. Under the logon node we use a regsomething.exe which calls the registry file with a silent switch in front.
Use a famous button called show files, and then drop the editreg.reg fil into sysvol.
Voila.
Good luck have fun!
Comment: Thanks Maclovin but I had weird message after I put the key inside show files of user configuration it ask the user for apply the key and if the user press yes message said cannot (import......error accessing the registry) it's normal because they have user rights and users not authorized to change something. It's possible to make silent applying?
Comment: But the way i didn't understand what you said about regsomething.exe?

Push new registry keys via group policy


How to pre-select a selct box in Ninja Forms from a query string

Question: I am trying to pre select a value within a select field in my contact from on the contact page from another page by passing a query string ?request=call-back. I am using Ninja Forms and the values that I have in my select field are: email-us, call-back
I have tried the following:
add_filter( 'ninja_forms_render_default_value', 'my_ninja_forms_pre_populate', 10, 3 );
function my_ninja_forms_pre_populate( $default_value, $field_type, $field_settings ){
    if( 'request' == $field_settings[ 'key' ] ){
        $default_value = $_GET['request'];
    }
    return $default_value;
}

I would like the select field to have call-back already selected.
Answer: I didnt need to use the filter that I was attempting. I changed the key value under administration within the ninja form builder and I made sure that none of the values were pre selected.
Answer: This drove me mad... but finally I've got a solution:
// register custom get parameter (to use it with get_query_var() for safety reasons)
function add_get_val() {
    global $wp;
    $wp->add_query_var('request');
}

add_action('init', 'add_get_val');

add_filter('ninja_forms_localize_field_listselect', function ($field) {
    if (get_query_var('request')) {
        $request = get_query_var('request');
        $optionExists = FALSE;

        // check if field exists
        foreach ($field['settings']['options'] as $option) {
            if ($option['value'] === $request) {
                $optionExists = TRUE;
                break;
            }
        }

        if ($optionExists) {
            foreach ($field['settings']['options'] as $key => $option) {
                // deselect all fields
                $field['settings']['options'][$key]['selected'] = 0;

                // select parameter
                if ($option['value'] === $request) {
                    $field['settings']['options'][$key]['selected'] = 1;
                }
            }
        }
    }

    return $field;
});


Right clicking suddenly unbearably slow in VS 2010

Question: I have been using VS2010 without any issues, always on the same application.  Suddenly within the last my solution has become unbearably slow when right clicking.  When doing other projects, it is fine.  The only thing I can think of that I changed was disabling the SQL Server debugging.
It happens if I right click anywhere within the code editor.  Everything freezes for about a minute and a half, then the right click menu shows up.   If I try again right away, the same thing happens.
Intellisense seems to work fine. It is only the right click.
The project is fairly big, but it has been working fine.  I am working on a 2 month old top of the line MacBook Pro (running Windows 7 64 bit in Boot Camp).  I did do the patch Tuesday big batch of Microsoft patches in the last 24 hours...
Can anyone suggest where to look?
Answer: A delay that long is almost always associated with network time-outs.  Use the trouble-shooting strategy demonstrated by Mark Russinovich in this blog post.
Comment: OK - I take it back - I think your suggestion was right.

I was thinking about what network time outs, and the freeze reminded me of SQL server browsing and not finding a server.  My dev version of SQL is stopped when booted, so I tried starting the service.  Sure enough, right click is back to normal...  Crazy thing is, no where in the project is this SQL Server instance being used.  I have done a winmerge on the solution with a backup - and can find ZERO references to the local dev SQL server instance.

Seems crazy - but thanks! Now to find out how to avoid having to start SQL service
Comment: Thanks @HansPassant you nailed it. I used Process Monitor to detect that Visual Studio 2012 was attempting to connect to an external TFS server every time I right clicked. Since I had to be on VPN to access that TFS server, it was timing out. I went to Tools -> Options -> Source Control -> Plugin-in Selection and set it back to none and now I have my speedy right click back. THANKS!
Comment: thanks for the suggestion.  I tried the config file change suggested at this link with no effect.
 I restored a full backup from several days ago, and it is running fine.  Comparing the files, there are very, very few differences (besides quite a bit of code - but nothing that should be able to lock up the system when right clicking).
I may have to restore the backup and try to merge the code changes - but I would prefer to identify the cause of this.
Comment: Good, you found it.  View + Server Explorer.
Answer: Windows 7, x64, 12GB memory, very slow right clicks:
The following steps fixed the problem for me.  Right click is now instantaneous.  Your Mileage may vary:
I deleted the following directory:
%AppData%Local\Microsoft\VisualStudio\10.0
and reinstalled these three packages from the Visual Studio 2010 Ultimate DVD
Microsoft SQL Server 2008 R2 Data-Tier Application Framework with this command:
\WCU\DAC\DACFramework_enu.msi
Microsoft SQL Server 2008 R2 Data-Tier Application Project:
\WCU\DAC\DACProjectSystemSetup_enu.msi
Microsoft SQL Server 2008 R2 Transact-SQL Language Service:
\WCU\DAC\TSqlLanguageService_enu.msi


Using Proxy Protocol with AWS ELBs and IIS 8

Question: I'm trying to move my SignalR application, hosted in AWS behind an ELB on IIS8, to use websockets.
After following the steps recommended by AWS (change listeners on the ELB to TCP, enable proxy protocol - http://docs.aws.amazon.com/ElasticLoadBalancing/latest/DeveloperGuide/enable-proxy-protocol.html) I'm unable to find a way of getting IIS to understand the proxy protocol information, and get bad requests instead.
Has anyone been successful in getting websockets through an AWS ELB and IIS working?
Comment: Did you ever find anything? We're running into the same issue and can't seem to find anything to make IIS recognize the proxy protocol.
Comment: For anyone wanting to still do this, it seems like the new Application Load Balancer supports websockets - https://aws.amazon.com/elasticloadbalancing/applicationloadbalancer/
Answer: IIS currently does not support Proxy Protocol. With AWS do as Dave suggests, and take a look at using ALB, as this has Web Socket support, so before the connection upgrades you will have X-Forwarded-For headers.


How to not receive the GNU notification every first time I run screen

Question: I have been an avid user of the "screen" command for a long time now and suddenly I seem to have a problem getting it to work.
Every first time I start screen in a new terminal session I get this message:
Screen version 4.00.03 (FAU) 23-Oct-06

Copyright (c) 1993-2002 Juergen Weigert, Michael Schroeder
Copyright (c) 1987 Oliver Laumann

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any
later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
License for more details.

You should have received a copy of the GNU General Public License along with this program (see the file COPYING); if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
 02111-1307, USA.

Send bugreports, fixes, enhancements, t-shirts, money, beer & pizza to email@example.com

as I use the screen command in a shell script (background) it does not work anymore.
Can anyone tell my how to either acknowledge this message so not to see it anymore or how to disable it?
I've been searching for an answer but have not found it.
Thanks!
Comment: Is there some reason why you can't just use `screen -q` ?
Comment: Not really but when combined with detached mode e.g. `screen -q -dmS tunnel ssh sometunnel` it does not work?!
Comment: the `-d` option will suppress printing of error messages but the copyright notice is not actually an error...
Answer: In the end it was screen -q <rest of command here>


MLE for binomial random variable

Question: You repeatedly toss a weighted coin 100 times. You know that the probability of getting heads, $p,$ is either 0.1 or 0.01 (the probability is the same across all tosses), but you don't know which. What is the decision boundary in terms of the number of times out of 100 that you get heads for the MLE of the parameter $p?$
My friend gave me this problem, but I feel like it's not well defined. Isn't the MLE here just going to be the number of heads divided by $100?$ Or am I missing something fundamental here?
Answer: You are now told that it is either $0.1$ or $0.01$. Even if you get exactly $50$ head, we know that $0.5$ is not the solution. That is rather than optimizing over $p \in [0,1]$, we should only maximize over $p \in \{0.1, 0.01\}$.
Here is how to approach the solution:
If $p = 0.1$, what is the likelihood that you observe $n$ heads. What about when $p=0.01$? Now compare which likelihood is higher.
Comment: In general, the likelihood that we observe $n$ heads is $\binom{100}{n}p^{n}(1-p)^{100-n}.$ So we're trying to solve $\binom{100}{n} 0.1^n 0.9^{100-n} = \binom{100}{n} 0.01^n 0.99^{100-n},$ which gives us $n \approx 4.$ Is this correct?
Comment: yes, that is the boundary, try to be more specific, what happens if it is $4$? what is your conclusion.
Comment: The conclusion is that at $p= 0.1$ and $0.01,$ the probabilities of getting $4$ heads are equal.
Comment: actually if you compute the probabilities, you will notice that they are different.
Comment: Yeah, you're right. It's at $n=3.97474$ for which we have $0.1^n 0.9^{100-n} = 0.01^n 0.99^{100-n},$ but this not integral. So how do I interpret this?
Comment: Any $n$ values that are bigger than $3.97474$ would have us conclude that $p=0.1$ is a better estimate. Try work work with inequlities, solve for when does one likelihood is bigger than the other.
Comment: Also what likelihood are we talking about here? Given that $p=0.1,$ what is the probability that we get $4$ heads or given that we get $4$ heads, what is the probability that $p=0.1?$ I've been doing the first one so far, but I'm wondering why we aren't doing the second.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/128805/discussion-between-siong-thye-goh-and-kid-brains).

MLE for binomial random variable


Flash: Align text verticaly

Question: is possible to align text in dynamic text control vertically to the middle? In flash CS3. Thanks
Answer: No, you will have to do it programmatically:
<code>var textField:TextField = new TextField();
textField.autoSize = TextFieldAutoSize.LEFT;
// ... some code here ...

var fullHeight:int = 100;
textField.y = (fullHeight - textField.height)*.5;
</code>

Flash: Align text verticaly