Do I need an effects loop in a bass amp?

Question: I understand how an amplifier effects loop works and why it's useful. It's a good place for modulation and timing effects. But is it essential?
I primarily play electric bass in rock and blues styles. I'm thinking about getting some basic effects pedals and upgrading my cheap practice amp to something with more features and character. Are there any essential bass effects that mandate an effects loop? Is it a feature that I'm likely to want right away, or is it something I can easily put off to a later upgrade? Does genre matter?
Answer: In general people use the effects loop to insert certain effects after the preamp stage but before the power amp stage in their amplifier.  The preamp stage is where the EQ is applied and this stage colors the sound the most. The preamp is also where you get some of the overdrive when you turn up the gain.  The power amp is usually more transparent and mostly just amplifies the signal coming from the preamp enough so it can push the speaker.
There are many types of pedals, and some work better before the preamp (these go in between your guitar and the amp's input) and other pedals work better after the preamp (these go in the effects loop). Distortion/gain pedals will almost always go before the preamp, whereas time-based effects like delay and reverb are usually in the effects loop if there is one available. Modulation pedals like chorus or flanger  can go anywhere, but do some experimenting to figure out what sounds best in your setup. Some people prefer modulation pedals to go before their distortion pedals, so in that case they would all go into the front of the amp. If you want the modulation pedals to go after distortion, you can do it either into the amp's input or in the effects loop, each with different results.
These are just guidelines but you should try different combinations and orders of pedals to see what you like best. Basically, any effects that you want to be "colored" by the preamp can go into the input, while effects that work best on a cleaner signal can go in the effects loop.
All that being said, for me I don't really worry about effects loops on bass amps. It's useful when playing guitar to be able to split the signals and really tweak the effects, but on bass I'm only ever using a couple pedals at a time so they usually work just as well in front of the amp. I also don't use the amp's built in distortion/overdrive on bass amps, I generally just play with a fuzz pedal and maybe some delay and/or chorus and they work out just fine in front of the amp. In fact I don't even use effects loops much for guitar either, I usually like to run everything into the front of the amp. Everyone has a different opinions on effects loops, like I said I rarely use them but some people can't live without them. Neither way is better- effects loop or not- it's just a personal preference. If you are still experimenting with effects and finding out what you like, I wouldn't worry too much about the effects loop. You can get a lot of variety out of a couple pedals into the front of the amp.
Edit (a bit more on bass effects in general):
When I play bass I don't like using a lot of effects because the bass has a pretty important role to play in the low frequency realm and effects often either cut the lows or just muddy up the sound. I do have a Big Muff fuzz pedal and I like it with bass, but it cuts out a lot of the low end of the signal so it's not something I would use for a whole song- maybe just for the chorus or a bass solo. I rarely use any pedals other than fuzz/distortion on bass, but if I had to pick a couple I would probably say a delay pedal could be useful as well as one modulation pedal- probably either a chorus or phaser. Distortion + chorus can make a great sound or use a phaser/flanger for some movement. Distortion + delay is another great combo for solos. If you don't have any pedals yet just start with a good fuzz or distortion pedal and see how you like it. When it comes to bass, effects aren't for everyone.
Comment: Thanks. I understand what the effects loop is for, I just have no idea whether I should care about it as an intermediate bassist, or whether it's a feature I can safely ignore until much further down the road (and stick with a cheaper amp for now). A good answer might discuss the importance of modulation and timing effects for bass, and how much they really need to go in the loop.
Comment: Done. Short answer: you don't need the loop for bass. In my opinion you don't really even need pedals, but they can be fun.
Comment: Based on the answers to my [question about bass effects](http://music.stackexchange.com/questions/25175/basic-effects-for-bass), this answer sounds spot on. Most folks seem to rely on pre-amp effects and avoid timing effects. A few folks like subtle chorus but it sounds like nothing that needs to go in the effects loop. Thanks for your help!


Shell script for using dos2unix on directories and sub directories for KornShell

Question: dos2unix takes filename as an argument. I need to make it generic so that it can take either a file or directories and then search recursively in directories and convert all files in the tree structure from dos to Unix. I am using KornShell (ksh).
Please help
Thanks.
Comment: Use find command: `find path  -type f -exec dos2unix {} \;`
Comment: It is not working for sub directories and also if main directory has sub directories and some files in it. Eg: If i have a directory abc and it has directories temp temp1 and files t1.txt t2.txt.then this command does not cover all sub directories
Comment: it works in `bash` atleast. did you give main directory in the place of `path`
Comment: try `-maxdepth` option. Read `man 1 find`.
Comment: Thanks John. I am attaching script for your reference.Please see this is not working :(
Comment: #!/bin/ksh var=$1 for i in `cat $var` do if [ -d "$i" ]; then cd $i find . -name *.* -maxdepth -exec dos2unix {} \; else echo "Processing $i file..." dos2unix -437 $i fi done
Comment: `#!/bin/ksh
if [ "$#" -eq 1 ]; then
   find "$1" -type f -exec dos2unix {} \;
fi`
Answer: Use find:
find file-path -type f -exec dos2unix {} \;

Comment: How can I exclude hidden files (starting with ., e.g. .git/)
Answer: I tried Prince John's answer on SunOS 5.10 with a KornShell, and it didn't work.
Apparently, because the dos2unix command was missing the output file, so it only printed to the stdout.
This modification to his answer worked for me.
find . -type f -exec dos2unix {} {} \;

Comment: Dos2unix is not part of the Unix standard. Their are many different implementations. People should always consult the man page first.
Comment: True.
This is the man page shown in my system:
http://docs.oracle.com/cd/E19253-01/816-5165/dos2unix-1/index.html


What is the semantics of '%' in Makefile?

Question: Googling doesn't help much in understand how the % variable is being used in the Makefile snippet below.
_OBJ = a.o b.o c.o
OBJ = $(patsubst %,$(OBJDIR)/%,$(_OBJ))

$(OBJDIR)/%.o: $(SRCDIR)/%.c $(INC)
    $(CC) -c -o $@ $< $(CFLAGS)

Can anybody please help me out? Does it mean that if there are five .c files present under $(SRCDIR), that many *.o rules are being populated behind the scene?
Answer: That is an "implicit rule".  The % makes the word $(OBJDIR)/%.o a pattern.  It tells make that if it's trying to build a target and the name of the target matches that pattern (where the % can substitute for one or more characters--any characters), AND that a file that matches the pattern $(SRCDIR)/%.c (where the % here has the same value as in the target) either already exists or can be built, then make can use this recipe to build that target.
So, if make wants to build a file foo/bar.o and the variable OBJDIR has the value foo, then this pattern foo/%.o will match that file with the % matching bar (this is called the stem in the GNU make documentation).
Then if SRCDIR has the value blah and make can find (or create) a file named blah/bar.c, then this implicit rule can be used to build the target foo/bar.o by running this recipe ($(CC) -c -o $@ $< $(CFLAGS)).
Comment: Perfect, makes complete sense coupled with the example.


Numeric-defined varliable becomes as NaN while trying to print json array

Question: I'm trying to use the following code in order to split Json array into 3-columns Bootstrap rows
I'm trying that by increasing a numeric variable to 3, adding a new row div and set it back to 1.
actually, the variable return as "NaN" at the first attemt to increase it
please your help, or any other idea to splir json to 3-col rows.
the code:

Thanks
Comment: remove the `var` inside your second `if`
Comment: You declare coli three times, just use the global one.
Comment: Variables defined with `var` are hoisted. Please refer: http://stackoverflow.com/questions/7506844/javascript-function-scoping-and-hoisting for more clarity.
Answer: try replace
if (coli==3) {
    html += '
';
    var coli=1;
    console.log( "1!" );
}

with
if (coli==3) {
    html += '
';
    coli=1;
    console.log( "1!" );
}

You are declaring your variable coli new in the if-statement. That is what you should not do.
Comment: Your'e right!
Did it while trying to fix it. Just removed the "var" and it starts working. also I had to set 1 as the initial variable and 0 and the resetting  at the and of the loop.


Natural isomorphisms of the forgetful functor

Question: Let $U: \mathbf{Groups} \rightarrow \mathbf{Sets}$ be the forgetful functor. Must every natural transformation $\eta: U \rightarrow U$ be a natural isomorphism?
Comment: Nice question! Does it come from a textbook? if yes, which one?
Answer: Since $U$ is represented by $(\mathbb{Z},+)$, we have (by Yoneda) $\hom(U,U) \cong U(\mathbb{Z},+)=\mathbb{Z}$. If $z$ is an integer, the corresponding natural transformation $U \to U$ is given by $U(G) \to U(G),~g \mapsto g^z$ for groups $G$. From this it can be checked that actually we have an isomorphism of monoids $(\hom(U,U),\circ) \cong (\mathbb{Z},*)$. Since the only invertible elements of $(\mathbb{Z},*)$ are $\pm 1$, there are lots of natural transformations which are no isomorphisms, for example $g \mapsto g^2$.
Comment: @magma Martin describes the isomorphism $\mathbb Z \to \hom_{[\mathbf{Groups},\mathbf{Sets}]}(U,U)$ as the morphism mapping $z \in \mathbb Z$ to the natural transformation $\eta \colon U \to U$ defined at point $G \in \mathbf{Groups}$ as $\eta_G \colon g \mapsto g^z$.
Comment: sorry if this is a silly question, but I am a bit groggy right now, but what is g and what is g^z? are you describing the components of natural transformation $\eta (z)$ ?
Comment: Thank you @Pece I have seen the corresponding edit


Why does a Logistic Regression with 'ElasticNet' penalty overfit?

Question: I have the problem that my logistic regression model overfits. even though I use the combined L1 and L2 penalty ('elastic net').
I have a data set with 496 features and 186 samples and want to predict a binary target. For this purpose, I thought of a logistic regression (because of binary classification) and regularization, specifically elastic net, as it enables the model to drop features completely (because of the L1 penalty), which is very important given my feature-sample-ratio (which is definitely not ideal, but as part of a course on digital science, my goal is a theoretically correct implementation of this kind of algorithm and not necessarily the best algorithm).
After tuning the hyper-parameters using cross-validation, the accuracy of my model was 1 for my training data but only 0.53 for my testing data. I kind of thought that using penalties and cross-validation would preserve me from overfitting so badly, but I am very new to machine learning, so maybe I made some mistakes, which you could hopefully highlight.
I used the following packages and functions:
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegressionCV
from sklearn.model_selection import train_test_split
import pandas as pd
import scripts.functions as fn # my own functions sheet
import numpy as np

I got my data:
# Setup
## Get data incl. target
data = fn.get_data()
data.dropna(inplace = True)

X = data.drop(labels=["target"], axis=1)
X = X.to_numpy()
X_scaled = StandardScaler().fit_transform(X)

Y = data["target"].to_numpy()

# Split data into training and validation sets
x_train, x_test, y_train, y_test = train_test_split(X_scaled, Y, test_size=0.2, random_state=35)

I initialized the hyper-parameters and the model:
# set hyper parameters
l1_ratios = np.arange(0, 1, 0.01)
cs = [1e-5, 1e-4, 1e-3, 1e-2, 1e-1, 1e0, 1e1, 1e2, 1e3, 1e4]

model = LogisticRegressionCV(cv=5, penalty='elasticnet', solver='saga',
                             l1_ratios=l1_ratios, Cs=cs, max_iter=5000,
                             n_jobs=-1, refit=True)

Then I fit my training data and retrieve the selected best values of C and L1-Ratio and the accuracy for the training data:
model.fit(x_train, y_train)

acc_train = model.score(x_train, y_train)

print(f"The accuracy of the model for the training data is {round(acc_train, 3)}")
Out:
    The accuracy of the model for the training data is 1.0

print(f"The hyper-parameter C is: {model.C_[0]}.\nThe hyper-parameter L1-Ratio is: {model.l1_ratio_[0]}")
Out:
    The hyper-parameter C is: 0.1.
    The hyper-parameter L1-Ratio is: 0.07

Subsequently I wanted to validate the model using the 'independent' test data:
acc_val = model.score(x_test, y_test)

print(f"The accuracy of the model for the test data is {round(acc_val, 3)}")
Out:
    The accuracy of the model for the validation data is 0.526

And now I am lost. To my understanding, using a model with some kind of penalty and then using cross-validation to tune this penalty are both steps to prevent overfitting. It seems like I would need a stronger penalty that the accuracies for my training and testing data converge, but this should be the result of the cross-validation, right?
I assume that the problem is the data I have, meaning the proportionally large number of features for these few samples. But if there are other mistakes regarding my general proceeding, I'd be very thankful for any advice!
P.S.: Unfortunately, I cannot share the data I use, and using different data would probably not reproduce the same problem. So please focus on my procedure.
Comment: Some questions/comments: (1) Shrinkage is shrinkage. Allowing L1 shrinkage may help interpretability, but there is no reason to assume it would work better than L2 only on high-dimensional data. (2) What is the proportion of 1s and 0s in your binary target? Why are you optimizing accuracy? (3) Do you get similar numbers with a different seed? A single run of 5-fold cross-validation is less than what is typically recommended. (4) Scaling your data before splitting into train/test is leaking information from the test set.
Comment: Regarding (2), you may want to have a look [here](https://stats.stackexchange.com/q/312780/176202)
Comment: (1) Are 496 features considered "high-dimensional"? (2) 94 times 1 (50.5%) and 92 time 0 (49.5%). I'm new to machine learning and thought it is the way to go for. I think I change to the log-loss, but I did not understand everything from the posts about accuracy at first sight. (3) I tested a different seed (=1) and 10-fold cv instead of 5-fold. The accuracy (sry, did not change it for that run) was 81% for the training data and 45% for the test-data. Interestingly, the L1-ratio was now .97 (instead of .07). (4) Changed it. - Thanks for the answer!
Comment: That ignores the key issues I described.  This requires a lot of background study.
Answer: Your sample size is not within a factor of 10 of being adequate to meet your goals.  The list of "selected" variables will essentially be a random draw.  See here.  In general, the chance of elastic net of finding the "right" variables is essentially zero (and is worse for lasso).  As discussed here the minimum sample size needed just to estimate the logistic model's intercept parameter is $n=96$.  The minimum sample size needed to fit one pre-specified binary feature in a logistic model is $n=184$.
Were the target to be a continuous variable with little measurement error, things would not be quite as bleak.
Comment: I was afraid of this kind of issue. Thanks for the feedback and the references! Nevertheless, as my goal is the theoretical correct implementation, I tried the model with the neg. log-loss and now got for very similar values for the training and the test data (-0.6931 and -0.6935, respectively). Also, the weight of the penalty is quite high (C=0.001), which was not the case for most of my previous computations. But I am not sure how to interpret the log-losses; I read that either values close to 0 or 1 are good, but I did not find something regarding negative values.
Comment: Nothing like that will be interpretable or reliable with such an incredibly low sample size.  I recommend starting with data reduction (unsupervised learning) that is masked to $Y$, as exemplified [here](https://hbiostat.org/rmsc/impred.html).  Sparse principal components is one promising technique.  Also make absolutely sure that the target is truly all-or-nothing binary.  Otherwise a continuous or ordinal analysis should be undertaken, which helps with the effective sample size (but not enough in your case).


Redirect to login (my-account) before checkout and return to checkout after login - Woocommerce

Question: I want to redirect non logged in users to login before checkout and return them back to checkout after login/registered
Based on WooCommerce login redirect based on cart answer code, here is my code that redirects the user to the My Account page if not logged in.
add_action('template_redirect', 'woocommerce_custom_redirections');
function woocommerce_custom_redirections() {

    if ( !is_user_logged_in() && is_checkout() )
        wp_redirect( get_permalink( get_option('woocommerce_myaccount_page_id') ) );
}

I need an extra argument to redirect them back based on the previous page they come from (checkout page) after the user logged in/registered.
In case someone logged in from directly from my-account not based on checkout page they login normally to my account page and don't get redirected to checkout even if the cart not empty.
Comment: `session_start()` on the checkout page `global $wp; $_SESSION["checkout_url"] =  home_url( $wp->request )` then you can retrieve that when redirecting after login is sucessful.
Comment: Try using local storage, to save last url, before the redirect and check it for a relevant value after they;ve logged in.
Comment: Do you have any example how to do it, I don't know alot about php. Any help would be appreciated
Answer: Maybe too late, but this is what you need:

add_action('template_redirect','check_if_logged_in');
function check_if_logged_in()
{
    $pageid = get_option( 'woocommerce_checkout_page_id' );
   if(!is_user_logged_in() && is_page($pageid))
    {
        $url = add_query_arg(
            'redirect_to',
            get_permalink($pagid),
            site_url('/my-account/') // your my acount url
        );
        wp_redirect($url);
        exit;
    }
}


Gibbs sampler -transformation of conditional posterior

Question: If my conditional posterior $\pi(\sigma^{-2}|\mathbf{y
},\mu)\sim Gamma(a,b)$, how can  I get the conditional posterior $\pi(\sigma^{2}|\mathbf{y
},\mu)$ with a transformation? The reason I ask is that the question asked to find the latter posterior but gave the prior $\pi(\sigma^{-2})$. I would really appreciated your help
Comment: Do you know about the inverse Gamma family of distributions?
Comment: Ive had a look. I tried it but the teacher said that we didn't need any other packages to add in R (i.e don't need to download InvGamma). I am guessing $\frac{1}{gamma(a,b)}$ wouldn't work?
Comment: What is it you're trying to obtain, exactly? The pdf? the pdf of the inverse is simple algebra. I'm guessing that you should know how to obtain the [pdf of a transformed r.v.](https://onlinecourses.science.psu.edu/stat414/node/157) in terms of the pdf of the original variable (as a function of the inverse-tranformed new variable) and the Jacobian.
Answer: If  $\sigma^{-2}\vert \textbf{y}$, $\mu$ is Gamma($a,b$) then $\sigma^2\vert \mathbb{y}, \mu$ will be inverse-Gamma($a,b$).
The way to get this answer is to apply the change of variables formula so that $\tau^2 = \sigma^{-2}$ and we change the measure to be a measure on $\tau^2$.


WSOD in homepage

Question: I am getting WSOD just in homepage and the hardest part is it is not giving any clue of what is the error. Tried to check the error log but there is no error. Tried also to add this in the index.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);

But the above code didn't help. Viewing the source code in the browser gives me...

The weird thing is when I restarted memcached the problem go away. But this happen regularly like when I restarted Memcache after 3 days problem return so I need to restart the Memcache and other caching.
Additional details of the site:

Homepage is mostly Views
I'm using Memcache and Boost
Context
Comment: What changed just prior to the onset of WSODs?  A new module installed, enabled or disabled?  Do you perform regular database and code backups and if so can you revert?  Are all your modules current?  Try the command example.com/update.php in the URL.  IF something is not properly synchronized between your database and code, that command should help synchronize things.
Comment: Hi Ashlar, I always run update.php via drush updb. I suspect my problem is related to this post https://drupal.org/node/496198#comment-1720400
Comment: Reading that post, I'm relieved to see it is another simple DrupaL problem! :)
Answer: Try adding this to your settings.php file (not index.php). After you see what error message you have we might be able to help you better. Usually WSOD are caused by a PHP fatal error.
error_reporting(-1);
$conf['error_level'] = 2;
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

Source: Show all errors while developing

WSOD in homepage


How do you avoid falling into the same patterns every time you improvise?

Question: I think every player that tries to improvise gets to a point where he starts playing things out of memory without focusing too much on the ideas in his head. It happens to me all the time. I just hate it when I play long sequences of sixteenth notes without even knowing what they are. Sure they sound ok because they are in the key, but they're starting to take over my playing. What can I do to avoid this kind of playing? How can I keep my improvisation spontaneous?
I think these are good solutions, but are they?

Learn new instruments (so that I rely less on muscle memory, and more on my ears).
Write/Transcribe music without my instrument (computer software, or just pen and paper).
Avoid playing fast.
Comment: Related: http://music.stackexchange.com/questions/2060/i-need-help-getting-out-of-my-scalar-rut
Comment: I play guitar mostly, but also when playing keyboards, I suffer from the same issues.
Answer: The first question would be: What instrument are you playing?
As a bassist that's where my answer will be coming from.
I have a few ways to change up what I'm improvising:

Backing tracks: this is the big one that helped me the most. By getting as many different tracks as possible to play along with I saw a dramatic improvement. If you have computer software you can make them yourself, but I bought a load of good ones off the internet. You can really hear how things fit together and find new ways of interacting with the rest of the musicians.
New styles/tempos: by not sticking to one style you'll find greater variety of ideas.
Going through songs/other musicians styles: what makes their music unique and how can I use that/develop it into my own new ideas?
New techniques: I found I could take advantage of a couple of new ideas to change up how I play. For my instrument adding bits of slap bass, palm muting, harmonics or others. This may not be plausible based on your instrument
Forcing myself to use different scales/modes: since I've learnt mode theory I've got a much better appreciation of how keys fit together. Also knowing which notes of a scale/mode to hit/emphasize helps alot.

And the big one:

Playing in a group - you'll constantly get new things thrown at you. Be it a group of people on the same instrument who have different approaches or working as part of an ensemble you'll nonetheless find new ideas that you can try and add to your playing.

I'd definitely say the last idea is good, as long fast sections are good, but get stale. I do have a normal guitar I play, but mostly for consolidating theory as opposed to genuine practise.
Mostly it's just a case of sitting down with your instrument and just playing as much as possible. Try some new genres if possible. Using myself as an example I mostly play rock/indie rock with my band, but I've gotten into jazz alot lately and it's given me loads of new ideas. I've got one eye on a bit of blues too just to beomce more well-rounded as a musician.
Mostly though, it depends what instrument you're playing.
Comment: Just as a P.S. There's nothing wrong with having a set of standard licks as a fallback - I have a few that I can always use if I get a little stuck - but it's mostly a case of knowing the theory as well as possible and learning how it applies to you and your instrument. The more genres and varied your background, the more you can throw in that will wow your audience/fangirls.
Comment: Ah ok, just seen you play guitar. So my advice would be to study new genres and look at musicians you look up to. I have no idea if it's your prefered music, but Ret Hot Chili Peppers do amazing improv jams that give me great ideas. Contrast that with bassists like Miller and Wooten, Arctic Monkeys and already you're getting a range of influences. These all apply to me mostly. I also look at bits of metal, funk, blues just for new ideas. Bass is interesting as I mostly play harmony with odd fills, but solos are where it gets interesting. What genres are you into?
Comment: Also reading your other comment (not enough rep to comment there) slowing down is a great thing to do, even if it feels painfully slow. If you're interested in playing in your head then ear training exercises like intervals will let you 'hear' what you'll play before you actually play it. That will also come from practising with the instrument.
Comment: As a background I played cello originally and moved to bass ("School of Rock" style...), but have also played flute, keyboard and guitar. I'd love to learn drums. The more you know the more you can apply to your music, and if you apprecaite what everyone else is trying to do you can interact much better with the rest of the ensemble. If you're interested in bass there's a great site called scottsbasslessons.com that I use alot. He has some great stuff about improv and creating lines that I bet would be handy on guitar too. Mostly Jazz orientated, but useful for any musician in my opinion.
Comment: That's true, by learning new styles of music, some your of old licks and patterns just don't apply anymore and you're forced to think of everything you're doing on the instrument.
Comment: I also play bass; I started playing bass when my friends were seeking a bassist and couldn't find one. I'm so glad learned playing bass because it made me so much better at rhythm. And now my timing is much better on keyboards and guitar. I also want to learn the trumpet just because learning new instruments make you rethink about everything you know about music, and I encourage everyone to do so.
Comment: I'm into blues and funk. I do listen to jazz (big band, jazzfunk, swing) and bossa nova but haven't gotten into those. I'm a little more motivated now to start playing those style.
Answer: I think one thing that hasn't been mentioned is the idea of how you practice things like scales or melodic concepts.  If you run scales all day you can shred through a scale or changes in a linear fashion and sound impressive but there isn't a lot of melodic content.  Similarly people come up with riffs or figures that fall into their hands or voice nicely and ten to practice that, which makes it occur even more frequently.  As a bass player I am constantly trying to avoid the same patterns/lines as they can easily accompany lots of different songs with the same or similar chord progressions.  Here are a few ways to break habits and find new ideas:

Practicing scales with rhythmic patterns: Usually people start with a steady pulse and increase the tempo as they practice scales, which is great practice for technique but can lead to monorhythmic ideas.  Try breaking up the rhythms in as many ways as possible starting small.  Try playing a quarter note then two eighth notes, one note per rhythm.  Then try two eighths and one quarter.  Then you can evolve that to the point where your rhythmic patterns are a whole measure long, then two or as long as you want.
Practicing scales with intervals: There are many ways to do this... Try in thirds (in C: C,E,D,F,E,G,F,A,G,B,A,C,B,D,C and back down C,A,B,G,A,F,G,E,F,D,E,C,D,B,C) You can also try ascending and descending (in C: C,E,F,D,E,G,A,F...) Or the opposite (E,C,D,F,G,E...).  This can be done with all of the intervals on all scales.
Combining 1 and 2: Try playing rhythmic patterns with an intervalic approach.

As you work through these patterns you will eventually find that they become more melodic and musical and less mathematic or rule bound.  Once you have practiced these new patterns they can fall in your hands easier, much like running the scale linearly, and you can combine the different patterns to create melodic ideas with less focus on how to play them.  Also, the practice will instill more of the theory.  Practicing the intervals will help you learn what a third sounds like as well as the other intervals.
There are endless ways you can practice that will lead to new ideas with easier access.  Here are a few more with less detail.

Note Permutations: Take a set of notes and play them in each permutation (3 notes: 1,2,3 - 1,3,2 - 2,1,3 - 2,3,1 - 3,1,2 - 3,2,1 - 6 total permutations)
Melodic Approach: Practice writing/playing longer melodies.  Some of my favorite players impress me with their melodic ideas as much or more than their virtuosic abilities (Jon Scofield comes to mind).
Melodic Development: Each piece of the melody, or the whole thing, can be used to fuel your improvisation (listening to the theme and development sections of classical pieces is great too).

All of this practice can be great and there are always more ways to do so but all of the other answers are just as important.  You have to listen to more music.  You have to learn to play more music.  You have to play with other people. Learning from the masters and practicing your ass off will not only help you come up with more unique and impressive lines but it will help you find your own voice on your instrument, which is always the most powerful tool.
Comment: This is all brilliant advice. Playing through scales in slightly different orders/rhythms/tempos will give you a great awareness of intervals and how they fit together. Without looking to play the same lick over and over again you can still use bits of scales to change up what you're doing - just playing little elements of it. My word of advice for scales is to use a metronome (I think my fellow bassist would agree), as timing is critical. Practise playing on the beat as well as pushing and pulling it to see what you can come up with.
Comment: Absolutely, metronome is god.
Answer: I have my own approach to this problem that's served me well over the years.  The basic formula is : Pick your cliche, and Ban it.
there's a balance at play hear, because repitition in music is one of the things that can objectively make it sound great.   The human mind likes when it can pick out a pattern, and the balancing act is to make your phrases souand familiar to each other while continually developing them.  The reason I say is just so you're cautious not to over-randomise your playing.
1. Write down every over used technique you're doing.
This can be anything from a scale position you rely on, A key you always play in, a scale you always use, always ending phrases on a perticular degree/note like the Root.  Always bending, always using a set pattern or rhythm. You get the idea
2. Pick one BAN IT from your playing for a set amount of time.
I compose, and had a bad habit of always composing in C Major because it has no sharps/flats to worry about, so I banned it for a month and as a result.  Once that was done I found G and F were getting really easy, so I cut them out too until I became comfortable in more keys.
If this is too easy, and you're just relying on another crutch, ban that one too.  The idea here is to get comfortable with new tricks, so that your old ones aren't alone.
3. Pick, or engineer situations where you had to use the original technique.  And find alternative ways to solve the problem.
Let's assume that your over used technique is the minor pentatonic scale.  Here you take a minor chord progression that lends itself to minor pentatonic, and start using some other scales.  Perhaps Dorian, Harmonic Minor, Natural Minor etc.
4. After the Ban on the old technique is over, go back to the situation you used in step 3
First, just have a play around with the situation, see what technique you drift towards, and notice how you now have a choice of at least 2 different approaches to what you're playing over.  try focusing on the old technique, then the new, then do some switching or combination work.  You'll find that because you HAD to find another way to play, it now comes naturally not to rely on the original crutch.
Hope that helps, I am aware at how messy my language was there!
Comment: I love your solution but it sure needs a lot of determination.
Comment: Start by taking them one at a time.  If you recognise that you're always relying on something it will be easy to spot and stop :)  It's much harder when you have a varied bag of tricks and your problems are a level up.
Answer: This happens to everyone, but the key is to listen to, and play along with as many different kinds of music as you can.
Sounds obvious, sure, but you get the benefit of the common riffs or patterns that other people have. Angus Young has a few very common licks. So does Joe Satriani or Slash etc. Get familiar with their licks and you will find new ones in your muscle memory.
Just play and listen. As much as you possibly can.
Answer: Though I still get stuck in a rut on occasion and the answer sounds cliche...
Play what you feel or what you hear in your head.  Getting started with playing what I hear in my head took me years, but the few times I manage to pull it off were WOW moments.
Comment: I totally agree, that's what I'm looking to answer. How to always play what's in my head and not stray away? No matter how hard I focus, I cannot manage to keep my focus long enough. There's these impulses I get to let my finger move on their own!
Comment: @Anthony, practice singing what you hear in your head.  Then practice playing exactly what you're singing.
Answer: Listen to your mistakes
When your fingers don't quite do what you intended, it is a mistake; but it's not necessarily wrong. Sometimes it sounds good.
Especially for live improvisation, you need to be able keep going, despite any flubs or missed notes. But getting back on track can involve getting back to the track. If you do it right, nobody knows you made a mistake and the mistake can be rechristened a variation.
Comment: The old jazz saw of, "If you play it twice, then it isn't a mistake."
Answer: Improvisation is the cornerstone of my play on harp, but if I'm tired or unfocused I'll start going to those get-me-over licks. It's like, I'm out of ideas. Fortunately I've had bandmates who kept me accountable.
In my old Americana band the mandolin picker and I would push each other hard. We'd tell each other, if you're playing that weak stuff, I'll ape you. I'll throw that lick right back at you. So when I hear one of his stock licks I'll wait until I take the next lead, look at him, and play that lick back. Or if I'm really feeling froggy I'll play it backwards at him.
Of course the vocalist would start cracking up when we did that. Ahh, band chemistry.
Comment: Not a bad idea at all. The only issue is I mostly practice alone :(. Maybe I'll try this next type I jam with my buddy. That way you also get to tell how much you and your partners know each-other musically. Hope we don't get into an argument (an improvisational one). Plays my lick in reverse, (oh no you didn't!!) then I play one of his minor licks in dorian... things could get pretty nasty. I'm not sure I'm willing to take the risk.
Answer: Experiment by yourself with different melodic and rhythmic patterns. Do it at slow tempo, so you are not tempted to let muscle memory take over. When you find interesting patterns, try them out at higher speed. After a while, you will have increased your "riff repertoire", and you can easier improvise around a broader specter of musical patterns.
Answer: Learn how to reharmonize songs.
Comment: Would you mind expounding on this short answer?
Comment: Sure. When you reharmonize the song, you open up different possibilities for improvisation, because you will be improvising over different chords.
Answer: You might want to have a look at this free Coursera course on Jazz improvisation.
There's plenty of useful information about the relationships between melody, chords, scales, etc... with an emphasis on how to use them together for improvising/soloing.
Answer: Improvisation means falling into the same patterns. If you want to be original, try composing. Even then, you might fail. People fail at being fresh and original when composing notes: when they have all the time in the world to adjust every note, and revise as much as they want before they reveal the final product to the world!
Improvisation consists of small variations on canned phrases, period. If you deviate from the "rut" too far, you will blow it; your live experiment will not mesh with the music.
What you can do from time to time is to reinvigorate your repertoire of phrases by introducing new ones.  How you introduce new ones is by composing them, not in real time, not while you are performing. Piece it together, taking as much time as you need. When you hit upon some interesting pattern, rehearse it. Once you have it down, transpose it throughout a scale (say, diatonically or whatever system that applies) and begin improvising with it: sandwich it between your usual phrases somehow: improvise while cutting between your "auto pilot" existing material and the new stuff you just invented.
Stick with it for some weeks, months. Don't introduce too much new stuff, too often.
One way to discover new things is to delve into fingerings that practitioners of your instrument tend to stay away from (due to difficulty). For instance, if you're a guitarist, you probably know that most guitarists (in jazz, pop, rock) improvise in various diatonic or pentatonic "boxes" that fit more or less into four frets across the neck.  These boxes, to a large extent, produce some of the cliches we often hear.  You can escape from the box by expanding into difficult stretch fingerings, like stretch pentatonic. Or scale patterns that are diagonal, involving slides between positions. Another thing many players do is proceed stepwise, and from one string to the other. Avoid that by using large intervals and skipping strings.
What naive non-musicians think comes from the musician's brain oftentimes just comes from the fingers. The repetitiveness caused by noodling fingers can be attacked from the perspective of noodling fingers just by changing the noodling patterns, even without regard for music: your original new stuff doesn't have to come from the brain any more than the old stuff did and nobody is the wiser.
Lastly, one way to get new material to creep into your playing is to play other people's material: play composed music, or crib someone else's improvisation.
Answer: A technique my mom taught me in composition is to take a less common time signature (like 5/4) and write some pieces (piano) in that time signature. The idea is to see how different rhythms affect phrasing and harmony. I'd done this and also tried things like taking a stock rhythmic pattern that I over use and displace it relative to the underlying pulse.


Proving $f=0$ if $f({1\over k})=0$ $\forall k\in \Bbb{N}$ .

Question: Let $f\in C^{\infty}[-1,1]$ and let $M$ be a constant such that $|f^{(j)}(x)|\le M$ $\forall j\in \Bbb{Z}_{+}$ and $x\in [-1,1]$. Prove that if $f({1\over k})=0$ $\forall k\in \Bbb{N}$ then $f=0$.
I don't know what to do. I guess it has something to do with Taylor expansion and the remainder corollaries but I don't know it well enough to understand how to apply it in here. I would appreciate your help.
Comment: Perhaps, see [this](http://math.stackexchange.com/questions/818227/proving-that-for-a-smooth-function-if-f-frac-1-k-0-forall-k-in-mathbb-n-t).
Comment: The notation $C^\infty [-1,1]$ just means that $f$ has derivatives of all orders? Or does it mean that $f$ is real analytic? The latter property I would write $C^\omega$ or something, not $C^\infty$. (I ask because you mention Taylor expansion.) Addition: Oh, do you have a theorem that can be used to prove that $f$ is analytic from the bounds you have on its derivatives there?
Comment: Am I correct in thinking you want to prove $f(x) = 0$ for all $x$?
Comment: I guess. That is how the question was originally written...
Comment: The thing is, I don't know what analytic is :<
But I will check right now
Comment: In functions I mean
Comment: I saw it, it ends up with the solver saying the function is analytic. I also checked the link she\he left but didn't understand how the fact that $f\equiv 0$ follows.
Answer: $\textbf{Hint:}$ first prove that $0 = f(0) = f^{'}(0) = ... $ it can be seen by continuity of $f , f ^{'} , ... $ then use $\textbf{Taylor aproximation theorem}$ so we have :
$$R(h) = f(x + h) - P(h)$$
where
$$P(h) = f(x) + f^{'}(x)h + ... + \frac{f^{r}(x)}{r!}h^{r}$$
and
$$R(h) = \frac{f^{r+1}(\theta)}{(r+1)!}h^{r+1}$$
take $x = 0 $ and $|h|<1$ so we have $P(h) = 0$ and $ R(h) = f(h)$ since $f^{r}(x)$ is bounded and r is arbitrary we can use the fact $\lim{r \to \infty}R(h) = 0$ because $|h| < 1$   so :
$$f(h) =0 $$
for $h \in (-1,1)$ and since $f$ is a continuous $f(1) = f(-1) = 0$


Preventing Data Leakage in Time Series Forecasting with Feature Engineering

Question: In a previous question (linked here), I sought guidance on forecasting thousands of time series. Based on the suggestion to treat it as a regression problem, I used the LightGBM model with extensive feature engineering.
Feature engineering involved:

Date features extraction (e.g., month, year, day_of_year) using Pandas Date time Component.
Lag features with various lag periods.

lag_list = [1, 2, 3, 4, 5, 7, 9, 10, 14, 30, 60, 90]
forecasting_goal = 'Hours'
for lag in lag_list:
   df['l' + str(lag)] = df.groupby(["TeamID", "TaskID"])[forecasting_goal].transform(lambda x: x.shift(lag))

Rolling features with different window types and sizes.

window_types = ['triang', 'parzen', 'nuttall', 'hann', 'cosine', 'barthann']
window_sizes= [5, 7, 14, 30]
lag_list= [1, 2, 3, 4, 5, 7]
forecasting_goal = 'Hours'
    for lag in lag_list:
        for size in window_sizes:
                df['l' + str(lag) + '_rme' + str(size)] = df.groupby(["TeamID", "TaskID"])[forecasting_goal]\
                    .transform(lambda x: x.shift(lag).rolling(window=size).mean())

                df['l' + str(lag) + '_std' + str(size)] = df.groupby(["TeamID", "TaskID"])[forecasting_goal]\
                    .transform(lambda x: x.shift(lag).rolling(window=size).std())

                df['l' + str(lag) + '_rmx' + str(size)] = df.groupby(["TeamID", "TaskID"])[forecasting_goal]\
                    .transform(lambda x: x.shift(lag).rolling(window=size).max())

                df['l' + str(lag) + '_rmn' + str(size)] = df.groupby(["TeamID", "TaskID"])[forecasting_goal]\
                    .transform(lambda x: x.shift(lag).rolling(window=size).min())

            for typ in window_types:
                df['l' + str(lag) + '_rme' + str(size) + '_' + typ] = df.groupby(["TeamID", "TaskID"])[forecasting_goal]\
                    .transform(lambda x: x.shift(lag).rolling(window=size, win_type=typ).mean())

Exponential weighted moving average features.

alphas= [0.3, 0.5, 0.7, 0.8, 0.9]
lag_list= [1, 2, 3, 4, 5, 7]
forecasting_goal= 'Hours'
for lag in lag_list:
        for alpha in alphas:
            df['l' + str(lag) + '_ewma_' + 'alp' + str(alpha).replace(".", "")] = df.groupby(["TeamID", "TaskID"])[forecasting_goal]\
                .transform(lambda x: x.shift(lag).ewm(alpha=alpha).mean())

Expanding mean features.

forecasting_goal = 'Hours'
expand_list= [1, 3, 7]
lag_list= [1, 2, 3, 4, 5, 7]

for exp_mean in expand_list:
    for lag in lag_list:
        df['l' + str(lag) + '_exp' + str(exp_mean)] = df.groupby(["TeamID", "TaskID"])[forecasting_goal]\
                .transform(lambda x: x.shift(lag).expanding(min_periods=exp_mean).mean())

Periodic features like Sin and Cos waves.

The model performed well until I discovered potential data leakage in the testing set. I realized that using actual hours from the testing set to calculate rolling features might cause leakage because, in real-world scenarios, future actual hours are unknown.

I'm seeking advice on how to address this issue, especially when forecasting multiple months ahead.
How can I prevent data leakage and ensure accurate time series forecasting in such a scenario?
Answer: Firstly, it is optional that this is not a leakage - depends on your production environment:
If "in production" you need to predict only 1 step ahead- you're all good. You use all the history, including the previous day or so, and predict the next. which is fine.
On the other hand, if "in production" you would like to predict months ahead - you indeed have a leakage.
The way you should handle it is by modeling the task as predicting the following X values.
Some models can do that (depends on the data of course).
Secondly,
lightGBM is a great model, but it has some disadvantages when dealing with time series forecasting, versus other models created for these kinds of tasks.
I'd start by considering an easier task than predicting numeric values months ahead. It's a tough problem, if possible at all.
For any farther questions, feel free to comment and I'd try my best to assist.


C# Select Node from XML by Attribute

Question: I need to be able to get the currency exchange rate from EUR => CHF for each day of a month. Therefor i got an XML Link from the gov.
The Link with the XML is this one.
Here's a snippet of the XML:
<devise code="eur">
  <land_de>Europäische Währungsunion</land_de>
  <land_fr>Union monétaire européenne</land_fr>
  <land_it>Unione Monetaria Europea</land_it>
  <land_en>Euro Member</land_en>
  <waehrung>1 EUR</waehrung>
  <kurs>1.05222</kurs>
</devise>
<devise code="gbp">
  <land_de>Grossbritannien</land_de>
  <land_fr>Grande-Bretagne</land_fr>
  <land_it>Gran Bretagna</land_it>
  <land_en>United Kingdom</land_en>
  <waehrung>1 GBP</waehrung>
  <kurs>1.48298</kurs>
</devise>

I need to get the value "1.05222" from the EUR node (which is the currency exchangerate).
I tried the following code, but it doesn't work, the result is always empty.
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(url);

string kurs="";

XmlNodeList xnList = xmlDoc.SelectNodes("/wechselkurse/devise[@code='eur']");
foreach (XmlNode xn in xnList)
{
   kurs = xn["kurs"].InnerText;
}

Comment: @CharlesMager: guess my memory was rusty.
Answer: I wouldn't use the old XmlDocument API.  Here's how you might do it using the cleaner LINQ to XML API:
XNamespace ns = "http://www.afd.admin.ch/publicdb/newdb/mwst_kurse";

var doc = XDocument.Load("http://www.afd.admin.ch/publicdb/newdb/mwst_kurse/wechselkurse.php?d=20150701");

var eur = doc.Descendants(ns + "devise")
    .Where(e => (string)e.Attribute("code") == "eur")
    .Select(e => (decimal)e.Element(ns + "kurs"))
    .Single();

Here's a working demo: https://dotnetfiddle.net/Iz6NHO
You can also use XPath (though the query methods are usually preferable due to the static typing).  The only issue with your query is you need to account for the namespace:
var nsm = new XmlNamespaceManager(new NameTable());

nsm.AddNamespace("k", "http://www.afd.admin.ch/publicdb/newdb/mwst_kurse");

var eur = (decimal)doc.XPathSelectElement("/k:wechselkurse/k:devise[@code='eur']/k:kurs", nsm);

C# Select Node from XML by Attribute


Choosing "Target Entropy" for Soft-Actor-Critic (SAC) algorithm

Question: I am quite familiar with Soft-Actor-Critic (SAC) and its many applications in continuous control RL environments. However, when implementing this algorithm in a practical setting, one thing that still eludes me is how the authors choose the "target entropy"  hyperparameter (denoted $\bar{\mathcal{H}}$) which is used to automatically tune the entropy temperature parameter $\alpha$ during training. Classically, they choose this target entropy to be $\bar{\mathcal{H}}=-\dim\lvert\mathcal{A}\rvert$ where $\mathcal{A}$ is the action space, but I don't know why the authors chose this value. Does anyone have some intuition as to where this choice came from/when other choices might be appropriate? I have looked around at numerous SAC related papers to see if the effect of this target entropy is measured, but so far my efforts have been unsuccessful.
Answer: I can't answer on behalf of the authors, but it makes sense to me that they would choose a default value $\propto \text{dim}(\mathcal{A})$. If they instead chose it at some fixed (i.e. not dependent on action dimensionality) constant, then problems with larger action dimensionalities would have to spread the same budget of randomness over the different action dimensionalities. For very large action spaces this might result in effectively deterministic behaviour. By choosing $\bar{\mathcal{H}} \propto \text{dim}(\mathcal{A})$, they are making sure that if you double the action dimensionality then you also double the amount of "total" randomness allowed by the policy, where "total" randomness is differential entropy (if you are confused why they have chosen a negative constant of proportionality, remember that differential entropy can be negative, and that differential entropies add across dimensions for diagonal stochastic policies; I think it just happens to be the case that for most mujoco tasks, it's effective to have relatively low target entropies. This might not hold for non-mujoco tasks.)
Comment: I guess the exact scaling would depend on the nature of the correlation across action dimensions. However, I think it should be a sub-linear scaling for non-diagonal Gaussian policies: on the extreme end, imagine a policy where only 1 action dimension is ever chosen randomly, regardless of the dimensionality, and the others are just copies of that random sample. As you scale up the dimensionality in that setting, you aren't actually increasing the "total randomness" possible in the policy, so the budget should be independent of the action space dimensionality.
Comment: Thank you for your answer! One follow up that I had was that I understand that differential entropy adds across dimensions IF our policy is diagonal stochastic; however, if this assumption is not met, would this `randomness budget' need to scale at $\Omega(n)$, i.e., something potentially greater than linear?
Comment: How to understand the negative sign. If you double the action space, the target entropy gets smaller because of the negative sign. Doesn't it conflicts to "Double the amount of total randomness allowed by the policy'?
Comment: I have a side question. When auto-tuning the temperature, should it be clipped? If so, in what range would be appropriate?
Comment: Is there a reason why this hasn't been marked as correct?
Comment: Sorry about that!


return being called twice in ios app

Question: I'm trying to implement a very basic login screen in my iOS app with username and password textfields.
I looked up how to have the view automatically focus on the passsword textfield after the user taps "next" upon entering a username.  However, for some reason, it appears that the return is being detected twice after the user enters their username.  Instead of keeping the keyboard on screen and focusing on the password textField, the keyboard disappears and neither textField is in focus.
What am I doing wrong?
LoginViewController.m:
<code>@implementation LoginViewController

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        [self.navigationController setNavigationBarHidden:YES];
        username = [[NSString alloc]init];
        keychainItem = [[KeychainItemWrapper alloc]initWithIdentifier:@"Login" accessGroup:nil];
    }

    // Check if user presses next from the username textfield -> automatically go to password
    - (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
        if (theTextField == self.txtPassword) {
            // try logging in
            NSLog(@"trying to proceed to submit form");

        } else if (theTextField == self.txtUsername) {
            // automatically go to the password field
            NSLog(@"trying to proceed to password field");
            [self.txtPassword becomeFirstResponder];
        }
        return YES;
    }
</code>
When I look at my logs, the following two logs appear after the user clicks "next" from the username field
<code>2014-08-27 00:11:48.594 BiP[3049:60b] trying to proceed to password field
2014-08-27 00:11:48.640 BiP[3049:60b] trying to proceed to submit form
</code>
Comment: You should probably be returning NO unless you want the return key character in your login/password.
Comment: did u write anything in the method `- (void)textFieldDidBeginEditing:`?
Comment: And u also need to check whther ur mouse is working properly, I had a same type of issue, that my mouse's single click gave double click on simulator.
Comment: @nazik I don't have this method implemented. I'm also testing on a physical device, not using my mouse.
Comment: @CrimsonChris WOW changing it to return NO did the trick!
Comment: @scientiffic That's because when you return YES it sends the return key to the field that has just become the first responder, which calls textFieldShouldReturn again on the next field.
Comment: @scientiffic You should consider putting resignFirstResponder in the submit part. This will dismiss the keyboard when the user gets to the end of your workflow.
Comment: got it, thanks for the help!  confusing to me that other examples always have the return set to YES.
Answer: Try this:
<code>- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
        if (theTextField == self.txtPassword) {
            // try logging in
            NSLog(@"trying to proceed to submit form");
            return YES;

        } else if (theTextField == self.txtUsername) {
            // automatically go to the password field
            NSLog(@"trying to proceed to password field");
            [self.txtPassword becomeFirstResponder];
            return NO;
        }
        return YES;
    }
</code>
Hope this helps.. :)

return being called twice in ios app


Como refazer este layout?

Question: Estou estudando por uma apostila da caelum e temos que refazer este site da Mirror Fashion. Mas fiz tudo como recomendado, cheguei até a copiar o código, mas não consigo fazer esta parte:

Quando tento aparece todo quebrado como a seguir:

Código html

Novidades

129,00 reais.

60,00 reais.

70,89 reais.

126,78 reais.

267 reais.

23,00 reais.

Mais Vendidos

15,00 reais.

67,80 reais.

9,50 reais.

22,90 reais

350 reais.

456,90 reais.

Código css
.painel{
    margin: 10px 0;
    padding: 10px;
    width: 445px;
}
.novidades{
    float: left;
}
.mais-vendidos{
    float: right;

}
.painel li{
    display: inline-block;
    vertical-align: top;
    width: 140px;
    margin: 2px;
    padding-bottom: 10px;
}
.painel h2{
    font-size: 24px;
    font-weight: bold;
    text-transform: uppercase;
    margin-bottom: 10px;
}

.painel a{
    color: #333;
    font-size: 14px;
    text-align: center;
    text-decoration: none;
}
.novidades{
        background-color: #F5DCDC;
}

Answer: O uso do float é considerado ultrapassado atualmente. Recomendo o uso do flex-box quando o seu objetivo é alinhar items, pois ele é mais preciso que o float.

 NOVIDADES

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 MAIS VENDIDOS

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

 Exemplo 1 - R$ 25,00

No exemplo acima, a propriedade display: flex foi usado na div pai, além do uso do flex-flow: row nowrap, permitido, assim, colocar as div's filhas uma no lado da outra e de forma centralizada (margin-left: 15%).
  Para haver o alinhamento das imagens conforme o exemplo do site citado, ambas as div's filhas tem a propriedade display: flex, para possibilitar o uso do wrap (quebra de linha), e, para haver 3 imagens uma no lado da outra, a largura de cada figure foi configurado para 30%. Caso deseje responsividade, sugiro o uso de media queries ou do bootstrap.

Como refazer este layout?


Is there a signed zero Integer in Java?

Question: I've learned that floating point number s have a signed zero in java. But I'm afraid Integer has not:
new Integer("0").equals(new Integer("-0")) // true

vs.
new Double("0").equals(new Double("-0")) // false

How could I store a sign with my zero Integer value?
Answer: You cannot store a sign with Java integer primitive type.
Negative zero is an artifact of IEEE-754 representation, which stores a sign in a separate bit. Integers, on the other hand, are stored in two's complement representation, which has a unique representation for zero.
Comment: Thank you for illuminating :-) for the sake of completeness I'll leave another link here: https://en.wikipedia.org/wiki/Two's_complement

Is there a signed zero Integer in Java?


Variable in html.tpl.php

Question: This seemingly simple task proved more difficult than I imagined.. I'm trying to get a variable from themename_preprocess_html to my html.tpl.php.
The code I have in my template.php file:
<?php
function themename_preprocess_html(&$variables) {
  $variables['test'] = "Hello world!";
}

And in my html.tpl.php file I have:
<?php print($test); ?>

Unfortunately, the variable isn't displayed in the page. It says:
Notice: Undefined variable: test in include()

I'm trying to do this so I can use node fields to determine variables in my stylesheet.
Is there any way I can print all available variables in my html.tpl.php?
Comment: Have you cleared the cache since adding the preprocess function?
Comment: Did you replace 'themename' above with your actual theme name?
Comment: `get_defined_vars()` is what you're looking for for the debugging by the way
Comment: Thanks for the fast reply! But yes, did that.
Comment: Haha, yes, did that. Is it case sensitive though? If my name is "ThemeName" does "themename_preprocess_html" work?
Comment: Thanks, the get_defined_vars displays a lot of variables, but nothing containing the "Hello World!" value.
Comment: The way you did it should work, so there has to be some other reason it is not working. Double check all the standard stuff, like is it uploaded, clear the cache a few more times, is there a spelling mistake, is the themename correct, etc.
Comment: Thanks for the help, I'll doublecheck everything I can think of.
Comment: Had my template.php file in my templates folder.. Guess the greenness should be showing by now.. Thanks a lot for your suggestions!
Answer: Try using get_defined_vars() to get the list of all the variables on a page.

get_defined_vars — Returns an array of all defined variables

Source - http://php.net/manual/en/function.get-defined-vars.php

Variable in html.tpl.php


detecting an ip behind proxy

Question: For testing purposes, I am using my machines ip provided by the isp as the address to connect to the server from  my phone(my machine/pc is the server). Since ipaddresses are unique in the internet, I should be able to access it.
But what if my pc is behind a proxy? First of all will my ipaddress be visisble to the internet? Will the proxy server forward the packets to my machine? The proxy requires Authentication. I also have a username and password for the proxy.
Answer: If a machine is behind a proxy, all requests to services that go through the proxy are "anonymized", at least as far as IP address goes. Reply traffic comes back to the proxy, which then forwards the response to the machine the made the original request.

Since ipaddresses are unique in the internet, I should be able to
access it.

Negative, ghostrider. There are several issues here. First is that all IP addresses are not unique. See RFC1918. With regards to non-RFC1918 addresses (and with the exception of some multicast IPs, etc.), then yes, they should be globally-unique. That said, I've seen some pretty bone-headed moves by companies just assuming they can just pick arbitrary netblocks to use, but that's beside the point.
Even with globally-unique addresses, though, you have routers and firewalls to deal with. It's perfectly conceivable (and quite common) for an organization to have a huge block of "public" IP addresses locked up behind a corporate firewall. In this situation, requests from these IPs might be routed directly or the might be routed through a NAT or proxy. You never know.
Comment: okay.. I thought two machines connected to the internet cannot have the same ip address at all. but I saw this link http://stackoverflow.com/questions/2689728/identify-machines-behind-a-router-uniquely-based-on-ipaddress and there are actually two machines having the same ipaddress. So what will happen if I use one of those machines as the server and access the it using its ipaddress from my phone?
Comment: I went through the rfc. I understood that two machines can never have the same ip if they are connected to the internet directly. but can two machines behind two different routers connected to the internet have the same ip address. I understood that it is possible with a proxy because you said with proxy the reply is only sent to the proxy's ipaddress. But what about routers. When you connect to a server via a router, the reply comes back to the originating pc's ipaddress and not to the router's address although eventually the router forwards it to the pc, right?
Comment: As mentioned in my answer, it completely depends on how the router is configured. Some will route requests directly, some will NAT requests, and some will force traffic through a proxy.
Comment: In your answer you mentioned that a proxy maintains anonymity, i.e. the server reply's to the proxy thinking that it is the client. how does the proxy server forward the reply  to the computer that originally made the request?
Comment: Is it possible that proxy and nat be both present? Because my machine is connected to the internet via proxy. But when I went to http://whatismyip.com , There was a different address than that of the proxy server ip. So does the traffic first go to a proxy server then to then to the nat router?
Comment: @Ashwin - yes, either of these are possible, though it's more probable that the proxy would live on the "private" side of the NAT.

detecting an ip behind proxy


I have all negatives in (some) of my folds in cross validation. Seeking best way to calculate AUC using R in this scenario?

Question: Problem
The title explains my problem. I cannot calculate AUC as things currently stand because some of my data sets have only negatives. I have three possible solutions and I need input from more experienced statisticians. I am still a learner and my research has not revealed to me an appropriate methodology to address this issue.
Further Details
I am doing k fold cross validation in R where k = 1. I have 12 independent data sets (which recorded the same observations). Therefore, I will have a fold that looks like this which will give me problems:
training: 1,2,3,5,6,7,8,9,10,11,12 testing: 4
I've got some R code to calculate the AUC. Given the above, I use the training for my trainingDataSet. The testingDataSet is comprised of data set 4.
model<-glm(a ~ b + c + d, family = binomial(link = 'logit'), data = trainingDataSet)

p <- predict(model, newdata=testingDataSet, type="response")

pr <- prediction(p, testingDataSet$a)

The error it gives is as follows:
Error in prediction(p, testingDataSet$a) :
  Number of classes is not equal to 2.
ROCR currently supports only evaluation of binary classification tasks.

This is because my testingData only has negative numbers. I'll provide the following R code to show you. Please see:
testingDataSet$a.
> unique(testingDataSet$a)
[1] 0

Perhaps a more robust way to show you is to show you the entire training set variable we are trying to predict for:
> testingDataSet$a
 [1] 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

Thus, we have a training set that is comprised of all negatives. I have another fold that is similar.
Question
I have three solutions that I believe can solve the issues I am facing. Clearly, the last two proposed solutions I think are very poor solutions, but some I have read in data science forums and included them here to be thorough. That said, I feel they are very ill advised.

Throw out k cross validation for k = 1 and k = 2. I have two datasets that have all negatives. I need testing and training validations that have both negatives and positives. I can then choose k = 3 and k = 4 for instance.
Remove the datasets that have all negative results. (Bad idea)
Compute AUC as 5.0 when given a data set with all negative results. (Bad idea)

This is the first time I have encountered this problem. I deeply appreciate your mentorship and assistance to a learner and what is considered best practice in this scenario. I think I have found it above, but definitely open to further suggestions or more formal statistical methodology here that I am not aware of. Thank you for your time and for reading this question.
Answer: A couple things...
AUC (generally) provides a measure of prediction accuracy when comparing a continuous prediction (say, probability between 0 and 1) to a binary response (true 0 or 1), which I assume is what you have going on here. The closer to 1 and 0 that your model predicts for true 1s and 0s, respectively, the higher the AUC. A random model results in AUC = 0.5 (not 5.0).
Generally we would refer to "k" as the number of folds in your validation (so you can't really validate with k=1). You actually seem to have k=14, and you're witholding 1 fold at a time (which is typical).
More information on your actual data would be useful. As is, I can only speak in generalities.
The problem...
AUC works by comparing (at a full breadth of thresholds) the false positive (FP) rate with the true positive (TP) rate. If your threshold is 0, all predictions will = 1, all true 1s will be TPs, but all true 0s will be FPs. With a threshold of 1, all predictions will = 0, and the opposite outcome will occur.
In order to calculate this balance of TP and FP, AUC requires at least one of each true binary value (0 or 1), otherwise it has no data on one of the two: FP or TP. So you can't run the test with only a single unique value of truth. So you need to figure out a different way of defining your folds. But how do you do that?
Without any decent information on exactly what you're measuring, it's impossible to say for sure. One thing is certain: you need the folds to be independent. In other words, you can't just randomly assign your data into folds and expect an unbiased validation. Issues of data structure and autocorrelation will make this validation overly-optimistic (you'll think your model is better than it is). You call your folds "independent", but if you have underlying structure in your predictors, you model may still be overfit, which will also bias your validations.
The solution...
One simple strategy would be to group folds together, ensuring that you have at least one (preferably more) of each true response (0 and 1) in each fold. The closer to equal prevalence you have (equal 0s and 1s), the more reliable the AUC will be (I believe, but check on that).
There is no hard-and-fast rule about how many folds you should use (i.e. the ideal value of k). Hastie et al (2009) and Kohavi (1995) have discussed this. Ideally, you want folds 1) to be [as] independent [as possible], 2) to contain enough data to make reasonable validations, and 3) to not force the model to extrapolate (i.e. in predictor space) when predicting to the withheld data (unless you specifically want to test this).
When grouping folds together, to maintain as much independence as possible, you'll want the most similar folds to be grouped together. This will maximise the independence between the training and testing data (see Roberts et al 2016). By this, I don't mean the most similar data values. I mean the most similar in quality (e.g. similar location, same experimental units, similar time, etc.). It's impossible to say specifically, as you've given no information on your data.
Without a better understanding of your actual analysis, that's about all the help I can offer.
Hastie, T. et al. 2009. "The Elements of Statistical Learning: Data Mining, Inference, and Prediction." Springer Verlag.
Kohavi, R. 1995. "A study of cross-validation and bootstrap for accuracy estimation and model selection." The Fourteenth International Joint Conference on Artifical Intelligence. Morgan Kaufmann Publishers Inc. San Francisco, CA, USA, pp. 1137-1143.
Roberts, D. R., V. Bahn, S. Ciuti, M. S. Boyce, J. Elith, G. Guillera-Arroita, S. Hauenstein, J. J. Lahoz-Monfort, B. Schröder, W. Thuiller, D. I. Warton, B. A. Wintle, F. Hartig, and C. F. Dormann. 2017 "Cross-validation strategies for data with temporal, spatial, hierarchical, or phylogenetic structure." Ecography, in press.


Grails file download not working

Question: I am trying to write a controller to download a file.
My domain class looks like this:
class File {

String fileName
Byte[] fileBytes
Long fileSize
String fileType
String fileDescription
...
...
}

My controller looks like this:
def downloadFile = {
    def file = File.findById(params.id)
    if (file != null)
    {
        response.setContentType(file.fileType)
        response.setHeader("Content-disposition", "attachment;filename=\"${file.fileName}\"")
        response.outputStream << file.fileBytes
        return
     }

}
There's no error but this doesn't work. Can anyone help me figure out what's wrong?
Thanks!
Answer: I wrote some snippet on it long time back.
http://lalitagarw.blogspot.com/2014/03/grails-forcing-file-download.html
This could help you.
However, try adding
response.outputStream << file.fileBytes
webRequest.renderView = false

and no need for return.
Answer: Add a flush at the end instead of the return:
response.outputStream.flush()

Grails file download not working


Does uniform convergence of a sequence of functions imply uniform continuity of its limit?

Question: Assume that $f_n$ converges to $f$ uniformly on $C$ and that each $f_n$ is uniformly continuous on $C$. Prove that $f$ is uniformly continuous on $C$.
Answer: Hint Use this inequality
$$|f(x)-f(y)|\leq|f(x)-f_n(x)|+|f_n(x)-f_n(y)|+|f_n(y)-f(y)|$$
and with the hypothesis of uniform convergence and uniform continity we can make the three terms on the RHS as small as we want.


Fail to configure Windows Server 2008 R2 updates

Question: I have installed Windows Server 2008 R2 on a VM workstation 9.0 machine. then i have enabled the windows updates which installed around 120 updates . but when i shut down the VM to configure the new updates it raised an error that it can not configure the updates and it revert them back.
So can anyone advice what the problem might be. Baring in mind that i have created an old VM on the same station and i used the same windows server ISO image and the updates were installed without any problems.
thanks in advance for any help.
BR
Answer: if you visit windows update history, you should see the error code for the failed updates. Try googling around for the error code and see if you can come up with something.
Also, the updates may fail when many concurrent updates that require restart are installed at once and sometimes the .NET framework updates were to blame.
If you still have problems, maybe something got wrong during the installation and the updater might be corrupt, do a system file check using the following console command:
<code>sfc /scannow
</code>
Also snapshots are a good idea before every major OS modification such as system patches :)
Hope I helped you at least a little.
Comment: the check mentioned that there are no errors, but still the VM can not configure the windows updates


How to change html using React event listeners?

Question: I was trying to make a select appear whenever the value of the variable isDisabled is set to false, however no change to the html is made, I have tried to change the html dynamically in several ways this was the last and least messy attempt, but no it worked anyway. What I expect is that whenever I select some type of person (PF or PJ) the respective select box appears.
export default function App() {
  let isDisabled = true;
  let isDisabledPF = true;
  function showOptions(value) {
    if (value === 'PF') {
      isDisabled = false;
      isDisabledPF = false;
    } else if (value === 'PJ') {
      isDisabled = false;
      isDisabledPF = true;
    } else {
      isDisabled = true;
    }
  }
  return (

      <form action="">

Selecione a opção que melhor te define:

              <select defaultValue={null}
                onChange={(e) => { showOptions(e.target.value) }}>
                <option value="none"></option>
                <option value="PF">Pessoa Física</option>
                <option value="PJ">Pessoa Jurídica</option>
              </select>

          {(isDisabled) ? <></> : (isDisabledPF) ? (
            <>
              <select>
                <option value="none"></option>
                <option value="fotografo">Fotógrafo</option>
              </select>
            </>
          ) : (
            <>
              <select>
                <option value="none"></option>
                <option value="turismo">Agência de Turismo</option>
              </select>
            </>
          )}
          <button type='submit'>
            Enviar
          </button>

      </form>

  )
}

Answer: What you're missing is a critical and fundamental concept in React... state.
Don't use a normal variable, use a state value:
const [isDisabled, setIsDisabled] = useState(true);
const [isDisabledPF, setIsDisabledPF] = useState(true);

Then you can update state in your function by calling the set* functions above, for example:
if (value === 'PF') {
  setIsDisabled(false);
  setIsDisabledPF(false);
}
// etc.

Updating state will trigger the component to re-render, and the new render will have the new state values to produce the updated result.
Otherwise, while your current code does successfully update the values of your variables, what it doesn't do is trigger React to re-render anything.
Comment: I thought the same thing happened with normal variables, that's why I had even forgotten about states. It worked, but i can only marked as answered after 6 minutes. Thank you.


The project was not built

Question: I am unable to resolve the error below.
"The project was not built since its build path is incomplete. Cannot find the class file for android.content.Context. Fix the build path then try building this project"
I imported the existing project into eclipse and the above error message was shown. I checked the other solution in this site but no solution worked.
Comment: select project, goto project > clean project & select build after clean
Comment: click on top of tab project and select option clean and build
Answer: Go to Windows --> preferences --> Android then check out for version of your workspace and Android SDK you are using. Add external jar files for the correct version of android platform
For instance you are using 2.2 then minimum sdk is 8, then you have to add android 8 platform jar file.
Also check your SDK path just in case where you have located it may be in case you using Windows 7 and you may have put your sdk folder in program file(x 86) for 32 bit.
Comment: Ok just try this few steps:
1. Right Click on the project --> Build Path --> Configure Build Path...
2. In the 'Source' tab, Select the project eg. 'myProject/src' --> Click OK.
3. Right Click on the project --> Android Tools --> Fix Project Properties
Comment: when I right click on the project there is no option of android tools
Comment: hahaha,,, Okes,, Click on windows --> preferences if you cannot see Android that means you need to first get ADT plugin get it installed.
Comment: when i click on windows --> preferences then there is android option but when i right click on the project there is on option of android tools
Comment: just let me know on which OS version your machine is i.e. 32 bit or 64 bit.
Change everything to ur OS version, then firstly uninstalling JDK and eclipse and re-installing to your OS bit version of them and Restart machine.
Eclipse is crappy at times due to its different taste for different kind of development.
Comment: mine is 64 bit version
Comment: i would suggest you to download latest ADT bundle of 64 bit and update it using SDK manager. Your issue seems to be rare due to compatibility among s/w you are using.
Answer: Go to build path -> configure build bath.Click on android in left menu bar.choose any android vendor present over there.Click apply and ok.So that , all android related stuff get build.

The project was not built


Azure AD B2C Token Issue

Question: As an enterprise, we would like to use Azure AD B2C and we have internal and external users.
Azure AD helps us manage our Azure users, corporate users and we can even add users with x@.onmicrosoft.com emails.
When we wanted to use Azure AD B2C for our consumers. So we have 2 choices to add our users which is a local user and an external user (Facebook, Google, etc)
If the local user belongs to our corporate it is ok to create the user using the Azure AD B2C portal.
But when we try to create the Azure AD B2C users who have another kind of emails, we need to use our own app which is consuming the Graph API. (that is the Azure portal restriction)
The issue is we are having a hard time getting the users values after the login is they are local users with Gmail or x emails.
We are using MSAL to get the related information instead of ADAL.
We have enabled the scopes and also enabled the API Access but this is the errors we are getting.

Error 1:
acquiring the popup:
AADB2C90055: The scope 'openid email openid profile' provided in request must specify a resource, such as 'https://example.com/calendar.read'.
Correlation ID: 86d6ff41-1cef-4ba1-9b26-2aa281c92ccd
Timestamp: 2017-09-15 10:22:20Z
Error 2:
invalid_request Error during login:
AADB2C90117: The scope 'user_impersonation' provided in the request is not supported.
Correlation ID: 785c6487-cd7f-4750-a769-deb477cb4ba4
Timestamp: 2017-09-15 10:32:39Z
:invalid_request
Error 3:
Error acquiring the popup:
AADB2C90055: The scope 'email openid profile' provided in request must specify a resource, such as 'https://example.com/calendar.read'.
Correlation ID: bd714482-8534-473e-94bc-0a4c56da686d
Timestamp: 2017-09-15 10:36:15Z
:invalid_request
Answer: Error1 and Error3
There is no need to provide scope openid profile offline_access when we using MSAL library to interact with Azure AD B2C. The SDK will add there scope automatically. We only need to provider the custom scope we defined for the web API app register on Azure AD B2C blade.
Error2
The scope user_impersonation is an custom scope defined by the app by default. We should contain the app id URI(https://{myB2CTenant}.onmicrosoft.com/b2capp2) before it like below:
string[] SCOPES = { "https://{myB2CTenant}.onmicrosoft.com/b2capp2/note_read", "https://{myB2CTenant}.onmicrosoft.com/b2capp2/user_impersonation" };

And AFAIK, the Azure AD B2C doesn't support delegate the user to access the Azure ad Graph at present. We need to register an app via Azure Active Directory->App registrations(not in Azure AD B2C blade) and access the Microsoft or Azure AD Graph via the client credentials flow. Here is a helpful link calling the Graph API in Azure AD B2C:
Azure AD B2C: Use the Graph API
If you want the Azure AD B2C app also support delegating user to calling the Microsoft Graph, you may submit the feedback from here.
Comment: We are using MSAL.js and when it tries to refresh the token it automatically adds openid profile to the scopes which then returns an error from azure AADB2C90055: The scope 'openid profile' provided in request must specify a resource. How do we get around this?
Comment: Same es Magrans, trying with Msal 0.1.5 and stills happens
Comment: Yeah same issue, regarding refreshing the token. Seems to happen when it has been more than 1 hour @Magrangs
Any idea?
Answer: For me that error meaned, that I am trying to aquire a accesToken when not having a valid idToken.
So make sure you have a valid idToken before calling acquireTokenSilent().
Comment: Also, check if the scope is set to the API permission not the app permission.

Azure AD B2C Token Issue


Alterar posição de annotation em google chart

Question: A ideia é fazer com que o texto do annotation do tipo line fique sobre a coluna.
Já tentei criar uma outra annotation para a mesma coluna, mas não obtive sucesso.
JS:
    google.charts.load("current", {
    packages: ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
    var data = new google.visualization.DataTable();
    data.addColumn('string', 'x');
    data.addColumn({type: 'string', role: 'annotation'});
    data.addColumn('number', 'Faixas');
    data.addColumn({type: 'string', role: 'annotation'});
                data.addRow(["até 4", null, 0, '0']);
                    data.addRow(["4.5", null, 0, '0']);
                    data.addRow(["5", null, 0, '0']);
                    data.addRow(["5.5", null, 0, '0']);
                    data.addRow(["6", null, 0, '0']);
                    data.addRow(["6.5", null, 0, '0']);
                    data.addRow(["7", null, 1, '1']);
                    data.addRow(["7.5", null, 2, '2']);
                    data.addRow(["8", 'Você', 5, '5']);
                    data.addRow(["8.5", null, 6, '6']);
                    data.addRow(["9", null, 2, '2']);
                    data.addRow(["9.5", null, 0, '0']);
                    data.addRow(["10", null, 3, '3']);

    var view = new google.visualization.DataView(data);
    var chart = new google.visualization.ColumnChart(document.getElementById("grafico"));
    chart.draw(view, {
        legend: {position: 'bottom'},
        curveType: 'function',
        vAxis: {
            maxValue: 10,
            format: 0
        },
        annotation: {
            1: {
                style: 'line'
            }
        }
    });
    $(document).ready(function () {
        $(window).resize(function () {
            drawChart();
        });
    });
}

HTML:

RESULTADO ESPERADO:
Answer: Você colocou a annotation na coluna errada. Substitua:
data.addColumn('string', 'x');
data.addColumn({type: 'string', role: 'annotation'});
data.addColumn('number', 'Faixas');
data.addColumn({type: 'string', role: 'annotation'});

por :
data.addColumn('string', 'x');
data.addColumn('number', 'Faixas');
data.addColumn({type: 'string', role: 'annotation'});

E nas linhas você monta da seguinte forma:
data.addRow(["valor eixo X", 0, 'annotation']);

Na primeira posição é o que vai estar no eixo x, a segunda o valor no eixo y e a terceira a annotation. Veja:

google.charts.load("current", {
  packages: ['corechart']
});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {
  var data = new google.visualization.DataTable();
  data.addColumn('string', 'x');
  data.addColumn('number', 'Faixas');
  data.addColumn({type: 'string', role: 'annotation'});

  data.addRow(["até 4", 0, '0']);
  data.addRow(["4.5", 0, '0']);
  data.addRow(["5", 0, '0']);
  data.addRow(["5.5", 0, '0']);
  data.addRow(["6", 0, '0']);
  data.addRow(["6.5", 0, '0']);
  data.addRow(["7", 1, '1']);
  data.addRow(["7.5", 2, '2']);
  data.addRow(["8", 5, 'Você']);
  data.addRow(["8.5", 6, '6']);
  data.addRow(["9", 2, '2']);
  data.addRow(["9.5", 0, '0']);
  data.addRow(["10", 3, '3']);

  var view = new google.visualization.DataView(data);
  var chart = new google.visualization.ColumnChart(document.getElementById("grafico"));
  chart.draw(view, {
    legend: {
      position: 'bottom'
    },
    curveType: 'function',
    vAxis: {
      maxValue: 10,
      format: 0
    },
    annotation: {
      1: {
        style: 'line'
      }
    }
  });
  $(document).ready(function() {
    $(window).resize(function() {
      drawChart();
    });
  });
}

Comment: Talvez minha explicação tenha ficado confusa. A minha ideia é que, na coluna em que aparecerá o texto "você", também apareça o annotation com a quantidade. Ou seja, duas anotações pra mesma coluna, uma string e uma linha - e não sei se isso é possível -.
Comment: @ThiagoBarros, eu não sei se isso é possível só com as funções do google charts. Talvez se você sobrescrever o SVG funcione. Você pode tentar trocar as annotations de lugar, veja: https://jsfiddle.net/7m7gbbsb/1/
Só um detalhe, quando você usa  `style: 'line'` nas annotations é para deixá-la na vertical.
Answer: Preciso de ajuda, no meu caso, quando incluo, as barras do gráfico some, ficando apenas os rotulos.
//Criando as colunas dentro do array
$table['cols'] = array(
array('label' => 'Data_Pedido', 'type' => 'string'),
array('label' => 'Qtde', 'type' => 'number','role' => 'annotation')
);
//echo $table;
//Preenchendo as linhas do array auxiliar "$row" com os dados do banco
while($row = mysqli_fetch_assoc($result)) {
$temp = array();
$temp[] = array('v' => (string) $row['Data_Pedido']);
$temp[] = array('v' => (int) $row['Qtde']);
$rows[] = array('c' => $temp);
}
Comment: Você usou a área de respostas para fazer uma pergunta. Em vez disso, é melhor criar uma nova pergunta. Para fazer isso, basta clicar no link [Faça uma pergunta](http://pt.stackoverflow.com/questions/ask), que fica no canto superior direito do site.
Comment: Isto não responde realmente à pergunta. Se você tiver uma pergunta diferente, pode fazê-la clicando em [Fazer pergunta](https://pt.stackoverflow.com/questions/ask). Você também pode [adicionar uma gratificação](https://pt.stackoverflow.com/help/privileges/set-bounties) para chamar mais atenção a esta pergunta quando tiver [pontos de reputação](https://pt.stackoverflow.com/help/whats-reputation) suficientes. - [Da Revisão](/review/late-answers/396439)


MongoDB Aggregate $project

Question: I store our web server logs in MongoDB and the schema looks similar to as follows:
[
  {
    "_id" : 12345,
    "url" : "http://www.mydomain.com/xyz/abc.html",
    ....
  },
  ....
]

I am trying to use the $project operator to reshape this schema a little bit before I start passing my collection through an aggregation pipeline.  Basically, I need to add a new field called "type" that will later be used to perform group-by.  The logic for the new field is pretty simple.
if "url" contains "pattern_A" then set "type" = "sales lead";
else if "url" contains "pattern_B" then set "type" = "existing client";
...

I'm thinking it would have to be something like this:
db.weblog.aggregate(
  {
    $project : {
      type : { /* how to implement the logic??? */ }
    }
  }
);

I know how to do this using map-reduce (by setting the "keyf" attribute to a custom JS function that implements the above logic) but am now trying to use the new aggregation framework to do this. I tried to implement the logic using the expression operators but so far couldn't get it to work. Any help/suggestion would be greatly appreciated!
Answer: I am sharing my "solution" in case others encounter the same needs like mine.
After researching for a couple of weeks, as @asya-kamsky suggested in one of his comments, I've decided to add a computed field to my original MongoDB schema. It's not ideal because whenever the logic for the computed field changes I would have to do bulk updates to update all documents in my collection but it was either that or rewrite my code to use MapReduce. I chose the former for now. In looking at MongoDB Jira board, it would appear that many people have asked for more diverse operators to be added for the $project operator and I certainly hope that the MongoDB dev team gets around to adding them sooner than later
Operator for splitting string based on a separator.
New projection operator $elemMatch
Allow $slice operator in $project
add a $inOrder operator to $project
Answer: You need to use combination of several operators and expressions.
first, the $cond operator in $project lets you implement if then else logic.
$cond : takes an array of three elements, first a boolean expression, second and third are values to use for the field value - if boolean expression is true then it uses second element for value, if not then third element.
you can nest these so that third element is itself a $cond expression to get if-then-else-if-then-etc.
string manipulation is a little awkward but you do have $substr available.
If you post some examples of what exactly you tried, I may be able to spot why it didn't work.
Comment: Thanks for your reply. Your suggestion was the very first thing I attempted and quickly hit a dead-end when I realized I couldn't check for the existence of a string pattern using the supported string operators. I need something like indexOf() in order to look for certain patterns in the url.
Comment: where can the substring occur in the "url"?  Is it something that's feasible to store at the time you initially write the document?
Comment: I am having a similar situation. I have two fields A and B and their existence in the document is mutually exclusive. I have to group by A when A exists and group by B when B exists, but it looks like you can't have $cond in a $project..I tried writing $project in two ways:
 {$project: {MyKey: {$cond: [{$exists: ["$A", true]}, "$A", "$B"]}}}
and
{$project: {MyKey: {$cond: [{"A": {$exists:true}}, "$A", "$B"]}}}

But I keep getting the error: {
        "errmsg" : "exception: invalid operator '$exists'",
        "code" : 15999,
        "ok" : 0
} ...Perhaps it's just an annoying syntax thing :(
Comment: @AafreenSheikh what you describe is doable - you probably want to start another question with your problem rather than trying to explain in comments.
Comment: @AsyaKamsky Asked here: http://stackoverflow.com/questions/14213636/conditional-grouping-with-exists-inside-cond

MongoDB Aggregate $project


how to implement the line in coordinates with js

Question: i want to use javascript to implements the effect
previously i use highcharts.js,but it have no the effect,some other framework is use point,i think is too hard to use it.
the point is dynamic,the line is drawn from the last point to the first point, what front framework can complete the assignment?
i just want to add data to use it.
Answer: Amchart is Best...


How to change the z-index of chartjs annotations label?

Question: Label is not overlapping the chart edge
Does anyone know if there is a way to set an z-index to make the label appears over the edge of the chart?
I am using the annotation plugin: https://github.com/chartjs/chartjs-plugin-annotation
Answer: Yes you can set the annotation's clip property to false to ensure it appears outside of chart (see docs here):
<code>const config = {
  type: 'bar',
  data,
  options: {
    layout: {
      padding: {
        top: 16
      }
    },
    scale: {
      y: {
        beginAtZero: true,
        max: 100,
        min: 0
      }
    },
    plugins: {
      annotation: {
        clip: false,
        common: {
          drawTime: 'afterDraw'
        },
        annotations: {
          annotation1,
          annotation2
        }
      }
    }
  }
};
</code>
Answer: You can set drawTime on "beforeDraw".
Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-ask).
Comment: please improvise your comments by giving code snippets


Find usages of ITypeElement, or IDeclaredElement with Resharper SDK

Question: I'm trying to create a custom navigate to plugin with the Resharper SDK plugin. I have managed to get the IDeclaredElement or ITypeElement when I stand on my type doing
var referenceName = dataContext.GetSelectedTreeNode<IReferenceName>();
var declaration = referenceName?.Reference.Resolve()?.DeclaredElement as ITypeElement;
if (declaration != null)
{
    //TODO: Find all usages here and check if my type is used as single argument to a method (Visitor pattern)
}

The SDK docs are really sparse and I dont find anything on the subject. Thanks
Answer: After some trial and error i Found a working solution. IFinder.FindAllReferences
var foundMethods = declaration
    .GetPsiServices()
    .Finder
    .FindAllReferences(declaration)
    .Select(r => ((r.GetTreeNode().Parent as IUserTypeUsage)?
        .Parent as IRegularParameterDeclaration)?
        .Parent as IFormalParameterList)
    .Where(list => list != null && list.ParameterDeclarations.Count == 1)
    .Select(m => m.Parent as IMethodDeclaration)
    .Where(m => m != null)
    .ToList();

Full code here


Is it possible to base64 decode part of a base64 encoded message

Question: I am working on a project where I am getting parts of base64 encoded data, but not the whole thing.  Is it possible to figure out what that part of the base64 encoded data was?
For example.  Say I base64 encode hello world
It becomes aGVsbG8gd29ybGQ=
But say I am only able to capture sbG8gd29y
Which base4 decodes to ݽ
I am familiar with how base64 encoding process works and I cannot think of a way to figure out what part of a base64 encoded message is without adding data randomly to the chunk on the front and back and comparing with dictionary words, but the problem is I am not even 100% sure that the data I am working with includes dictionary words.
Thanks
Comment: use mod 4 to specify the correct string length in Base64
Answer: I just spent a little time using an online conveter (http://www.convertstring.com/EncodeDecode/Base64Decode)
If you take your captured section you can run it through the converter and see that its an invalid length for a base64 encoded string.
For a captured section to have a valid length you will need to add some extra characters (0-3 depending on the length of the section). A valid base64 string has a length that is exactly devisible by 4.
Pick a character ('a' for example) and then run through the posibilities of adding the correct amount of characters to the section, front and back. With your added characters the string will be decodable and one of the decoded values will be more readable, that will be the one that has the partially decoded data.
E.G:
   sbG8gd29yaaa
and
   aaasbG8gd29y

decodes to:
   ����ݽɦ�
and
   i��lo wor

You can make a rudimentary programatic test for readability by counting the number of 'normal' characters within the string (a-z for example). You will need to make up your own mind what is 'normal', it will depend on the expected language of the data and the context (is it known to be numeric only for example).