Problema com caracteres especiais laravel

Question: Estou começando a aprender sobre o Laravel 5 e estou com um problema, todo texto que escrevo com caracteres especiais é convertido para '�'.
Já tentei todo tipo de configuração no charset desde ISO-8859-1 até UTF-8.
Tem alguma forma de configurar isso no laravel para não ter que escrever tudo com &; ?
Comment: Parece ser um erro no seu editor e não no Laravel. Certifique-se de que a header `Content-Type` possui `charset=UTF8`
Comment: No sei editor de texto, verifique a codificação do ficheiro. Por exemplo, no notepadd++ tem que ter algo deste género: Codificação -> Codificar em UTF-8 sem BOD
Answer: Não cheguei a utilizar o Laravel, mas a maioria dos frameworks possuem uma configuração de charset (vale lembrar também que o recomendável é o seu banco estar no mesmo charset).
Este link talvez possa resolver o seu problema
Comment: Tentei essa solução mas aparentemente é algum tipo de erro no laravel que acontece apos o parse na view... Não obtive exito :/
Comment: Eu já tive um problema parecido pois o charset do arquivo no sublime estava diferente, apenas mudei para utf-8 e voltou a funcionar, talvez seja uma solução.
Comment: tentei isso tbm mas o charset do sublime ja esta utf-8 :/
Answer: Provavelmente o problema está no encode do Blade(Sistema de Template do Laravel), vai no arquivo app/Providers/AppServiceProvider.php e deixa o método boot dessa forma =
public function boot()
{
    parent::boot();
    \Blade::setEchoFormat('e(utf8_encode(%s))');
}

Answer: Resolvi incluindo a tag
<link href="//fonts.googleapis.com/css?family=Lato:100" rel="stylesheet" type="text/css">

no meu head do master page do blade.
Comment: Acredito que você vez outra coisa para isso. Como a inclusão de uma fonte pode resolver esse problema?
Comment: Eu removi o metacharset UTF-8 e inclui a fonte. Mas obrigado pelo voto negativo.


Cross Platform database encryption in Shared Project Xamarin

Question: I am using Xamarin to develop iOS and Android application. I have created one shared project which is common for both platforms.
As I am using database its common and put in shared project. I need to encrypt database file.
Project structure is like Tasky.
I have replaced SQLite.cs file from this GitHub link as suggested by Xamarin.
No SQL- cipher component I can use as its paid one.
Note: Other way round instead is encrypting DB file by AES of C#.
But, I need a good approach.
Any suggestions are welcome.
Answer: SQLCipher is also available as free community edition. A little more work to compile the C code yourself but nothing too bad. I had to do it for one of my earlier projects even though I had the commercial license as some of the features (data types) were missing.
For example here, you could get the SQLCipher native library:
https://github.com/sqlcipher/android-database-sqlcipher
SQLite source code (includes XCode project as well): https://github.com/sqlcipher/sqlcipher
Comment: But, conversion of c source itself be another long life project.
Comment: Conversion? No, just compile it for Android and iOS. Of course if one doesn't have much C experience compiling can be a taunting task by itself. See my update for a link to a GitHub project for Android. It should give you the native C libraries. There is also an iOS version if you search for it.
Answer: You can create the xamarin android binding project by importing sqlcipher aar file and resulting DLL can be used for the db encryption.
Checkout the complete example code here implemented using open-source sqlcipher community edition.


How to alter commerce order view access?

Question: When viewing an order, I want to do checks per order, whether the user may view that order or not.
function my_commerce_entity_info_alter(&$entity_info) {
  $entity_info['commerce_order']['access callback'] = '_my_commerce_commerce_order_access';
}

function _my_commerce_commerce_order_access($op, $entity = NULL, $account = NULL) {
  return $entity->id == 99; // just for example
}

The above did not work.
I didnt find anything like entity_access_alter or similar.
What do I do wrong?
Answer: You should be using hook_commerce_entity_access_condition_ENTITY_TYPE_alter() for commerce orders.
You receive the following parameters:

$conditions: The OR conditions group used for the view access query.
$context: An array of contextual information including:

account: the account whose access to view the entity is being checked
entity_type: the type of entity in the query
base_table: the name of the table for the entity type

So it becomes:
hook_commerce_entity_access_condition_commerce_order_alter(&$conditions, $context) {
  // If we are not allowed to view the order, leave.
  if (!user_access('some_permission', $context['account'])) {
    return;
  }

  $orders = array(99);

  // add a condition
  $conditions->condition(db_and()
    ->condition($context['base_table'] . '.order_id', $orders, 'IN')
  );
}

Comment: the problem is i need to filter on a value that is serialized in the data column
Comment: How bad is it? Should you scan all orders, or only those of a certain user or status or anything else? You could use a secondary query inside this hook to obtain some entities and put their serialized values in the array. But scanning over all orders might take significant time...


Change multiple files

Question: The following command is correctly changing the contents of 2 files.
sed -i 's/abc/xyz/g' xaa1 xab1

But what I need to do is to change several such files dynamically and I do not know the file names. I want to write a command that will read all the files from current directory starting with xa* and sed should change the file contents.
Comment: You mean `sed -i 's/abc/xyz/g' xa*` ?
Comment: The answers here don't suffice. See https://unix.stackexchange.com/questions/112023/how-can-i-replace-a-string-in-a-files?newreg=63655f028ac04f11bbf861c7bba8db9f
Comment: I did @PaulR solution and it worked, but what I don't understand is all these complicated other answers! What is missing from your solution?
Comment: @SoheilRahsaz sometimes when there is too much files the shell will complain about the argument list length as demonstrated by the top answer
Comment: Here's another answer on updating many files at once: https://unix.stackexchange.com/questions/29268/how-to-search-and-replace-text-in-all-php-files-in-a-directory-and-its-subdirec
Comment: `sed` can take multiple files. All these complicated answers are just concerning the command length limit.
Answer: I'm surprised nobody has mentioned the -exec argument to find, which is intended for this type of use-case, although it will start a process for each matching file name:
find . -type f -name 'xa*' -exec sed -i 's/asd/dsg/g' {} \;

Alternatively, one could use xargs, which will invoke fewer processes:
find . -type f -name 'xa*' | xargs sed -i 's/asd/dsg/g'

Or more simply use the + exec variant instead of ; in find to allow find to provide more than one file per subprocess call:
find . -type f -name 'xa*' -exec sed -i 's/asd/dsg/g' {} +

Comment: I had to modify the command in this answer like so: `find ./ -type f -name 'xa*' -exec sed -i '' 's/asd/dsg/g' {} \;` that's the location for the find command `./` and a pair of single quotes after `-i` for OSX.
Comment: The `-exec` option of find along with `{} +` is sufficient to solve the problem as stated, and should be fine for most requirements. But `xargs` is a better choice in general because it also allows parallel processing with the `-p` option. When your glob expansion is large enough to overflow your command line length, you are likely to also benefit from a speedup over a sequential run.
Comment: The find command works as it is supplied by ealfonso, `./` is equal to `.` and after `-i` has only the backupsuffix parameter.
Comment: I don't know why none of these options work for me as I have used them successfully on *nix machines. I'm in terminal on a Mac though now...
Answer: Better yet:
for i in xa*; do
    sed -i 's/asd/dfg/g' $i
done

because nobody knows how many files are there, and it's easy to break command line limits.
Here's what happens when there are too many files:
# grep -c aaa *
-bash: /bin/grep: Argument list too long
# for i in *; do grep -c aaa $i; done
0
... (output skipped)
#

Comment: If there are that many files, you'll break the command line limit in the `for` command. To protect yourself from that, you'd have to use `find ... | xargs ...`
Comment: In the sed command, you need to use `"$i"` instead of `$i` to avoid word splitting on filenames with spaces.  Otherwise this is very nice.
Comment: Regarding the list, I believe the difference is that `for` is part of the language syntax, not even just a builtin.  For `sed -i 's/old/new' *`, the expansion of `*` must ALL be passed as an arglist to sed, and I'm fairly sure this has to happen before the `sed` process can even be started.  Using the `for` loop, the full arglist (the expansion of `*`) never gets passed as a command, only stored in the shell memory and iterated through.  I don't have any reference for this at all though, it just seems probable that is the difference.  (I'd love to hear from someone more knowledgeable...)
Comment: see the updated answer. if you need more info, please, ask an official question, so people could help you.
Comment: I don't know the implementation, but the "xa*" pattern does have to get expanded at some point. Does the shell do the expansion differently for `for` than it does for `echo` or `grep`?
Comment: @glenn jackman: i've just tried `for i in `find .`; do echo $i; done` with 600k files, and it works, could you please elaborate, what is the limit for the `for` command and how can i break it?
Comment: maybe I'm wrong. What happens if you `echo [pattern_that_expands_to_600k_files]`?
Comment: the whole point of using `for` is to be able to **iterate** through the list of files and never have to deal with 600k files at the same time, `$i` is always a single file name. please, correct me if i'm wrong, but as far as i know, there's no limit imposed on the `for` statement.
Comment: of course it does the expansion differently, that's why i said it's better to use `for` statement to avoid breaking command line length limitations in case of having too many files.
Answer: You could use grep and sed together. This allows you to search subdirectories recursively.
Linux: grep -r -l <old> * | xargs sed -i 's/<old>/<new>/g'
OS X: grep -r -l <old> * | xargs sed -i '' 's/<old>/<new>/g'

For grep:
    -r recursively searches subdirectories
    -l prints file names that contain matches
For sed:
    -i extension (Note: An argument needs to be provided on OS X)

Comment: Bonus of this method for me was I could slip in a `grep -v` to avoid git folders `grep -rl  . | grep -v \.git | xargs sed -i 's///g'`
Comment: best solution for a mac!
Comment: This also works great on windows with shells like cmder, where find cannot easily be used.
Answer: Those commands won't work in the default sed that comes with Mac OS X.
From man 1 sed:
-i extension
             Edit files in-place, saving backups with the specified
             extension.  If a zero-length extension is given, no backup
             will be saved.  It is not recommended to give a zero-length
             extension when in-place editing files, as you risk corruption
             or partial content in situations where disk space is exhausted, etc.

Tried
sed -i '.bak' 's/old/new/g' logfile*

and
for i in logfile*; do sed -i '.bak' 's/old/new/g' $i; done

Both work fine.
Comment: @sumek Here's an example terminal session on OS X that shows sed replacing all occurrences: [GitHub Gist](https://gist.github.com/funroll/5504098)
Comment: I  used this to replace two different lines in all my website config files with a one-liner below.
    sed -i.bak "s/supercache_proxy_config/proxy_includes\/supercache_config/g; s/basic_proxy_config/proxy_include\/basic_proxy_config/g" sites-available/*
Don't forget to delete the *.bak files when you are done for file system hygiene sake.
Answer: @PaulR posted this as a comment, but people should view it as an answer (and this answer works best for my needs):
sed -i 's/abc/xyz/g' xa*

This will work for a moderate amount of files, probably on the order of tens, but probably not on the order of millions.
Comment: Assume you have forward-slashes in your replacements. Another example with filepaths `sed -i 's|auth-user-pass nordvpn.txt|auth-user-pass /etc/openvpn/nordvpn.txt|g' *.ovpn`.
Answer: Another more versatile way is to use find:
sed -i 's/asd/dsg/g' $(find . -type f -name 'xa*')

Comment: That is simply not true. In your command above, the $(find . ...) gets expanded into a single command, which could be very long if there are many matching files. If it is too long (for example in my system the limit is around 2097152 characters) you might get an error: "Argument list too long" and the command will fail. Please google this error to get some background on this.
Comment: the output of that find command gets expanded, so this doesn't address the issue. Instead you should use -exec
Comment: it works as long as the number of files doesn't push into command line limits.
Comment: @erjoalgo this works because the sed command can handle multiple input files. Expansion of the find command is exactly was is needed to make it work.
Comment: That limit is dependent only on the memory resources available to the machine and it's exactly the same as the limit for exec.
Comment: OK, I guess I've just never expanded a search that long before.
Answer: I'm using find for similar task. It is quite simple: you have to pass it as an argument for sed like this:
sed -i 's/EXPRESSION/REPLACEMENT/g' `find -name "FILE.REGEX"`
This way you don't have to write complex loops, and it is simple to see, which files you are going to change, just run find before you run sed.
Comment: This is exactly the same as [@dkinzer's answer](https://stackoverflow.com/a/27849922/2948889).
Answer: u can make
'xxxx'  text u search and will replace it with 'yyyy'
grep -Rn '**xxxx**' /path | awk -F: '{print $1}' | xargs sed -i 's/**xxxx**/**yyyy**/'

Answer: There's some good answers above. I thought I'd throw in one more that is succinct and parallelizable, using GNU parallel, which I often prefer to xargs:
parallel sed -i 's/abc/xyz/g' {} ::: xa*

Combine this with the -j N option to run N jobs in parallel.
Answer: The Silver Searcher Solution
I'm adding another option for those people who don't know about the amazing tool called The Silver Searcher (command line tool is ag).
Note: You can use grep and other tools to do the same thing here, but The Silver Searcher is fantastic :)
TLDR
ag -l 'abc' | xargs sed -i 's/abc/xyz/g'

Install The Silver Searcher
sudo apt install silversearcher-ag                # Debian / Ubuntu
sudo pacman -S the_silver_searcher                # Arch / EndeavourOS
sudo yum install epel-release the_silver_searcher # RHEL / CentOS

Demo Files
Paste the following into your terminal to create some demonstration files:
mkdir /tmp/food
cd /tmp/food
content="Everybody loves to abc this food!"
echo "$content" > ./milk
echo "$content" > ./bread
mkdir ./fastfood
echo "$content" > ./fastfood/pizza
echo "$content" > ./fastfood/burger
mkdir ./fruit
echo "$content" > ./fruit/apple
echo "$content" > ./fruit/apricot

Using 'ag'
The following ag command will recursively find all the files that contain the string 'abc'. It ignores the .git directory, .gitignore files, and other ignore files:
$ ag 'abc'
milk
1:Everybody loves to abc this food!

bread
1:Everybody loves to abc this food!

fastfood/burger
1:Everybody loves to abc this food!

fastfood/pizza
1:Everybody loves to abc this food!

fruit/apple
1:Everybody loves to abc this food!

fruit/apricot
1:Everybody loves to abc this food!

To just list the files that contain the string 'abc', use the -l switch:
$ ag -l 'abc'
bread
fastfood/burger
fastfood/pizza
fruit/apricot
milk
fruit/apple

Changing Multiple Files
Finally, using xargs and sed, we can replace the 'abc' string with another string:
ag -l 'abc' | xargs sed -i 's/abc/eat/g'

In the above command, ag is listing all the files that contain the string 'abc'. The xargs command is splitting the file names and piping them individually into the sed command.
Answer: If you are able to run a script, here is what I did for a similar situation:
Using a dictionary/hashMap (associative array) and variables for the sed command, we can loop through the array to replace several strings. Including a wildcard in the name_pattern will allow to replace in-place in files with a pattern (this could be something like name_pattern='File*.txt' ) in a specific directory (source_dir).
All the changes are written in the logfile in the destin_dir
#!/bin/bash
source_dir=source_path
destin_dir=destin_path
logfile='sedOutput.txt'
name_pattern='File.txt'

echo "--Begin $(date)--" | tee -a $destin_dir/$logfile
echo "Source_DIR=$source_dir destin_DIR=$destin_dir "

declare -A pairs=(
    ['WHAT1']='FOR1'
    ['OTHER_string_to replace']='string replaced'
)

for i in "${!pairs[@]}"; do
    j=${pairs[$i]}
    echo "[$i]=$j"
    replace_what=$i
    replace_for=$j
    echo " "
    echo "Replace: $replace_what for: $replace_for"
    find $source_dir -name $name_pattern | xargs sed -i "s/$replace_what/$replace_for/g"
    find $source_dir -name $name_pattern | xargs -I{} grep -n "$replace_for" {} /dev/null | tee -a $destin_dir/$logfile
done

echo " "
echo "----End $(date)---" | tee -a $destin_dir/$logfile

First, the pairs array is declared, each pair is a replacement string, then WHAT1 will be replaced for FOR1 and OTHER_string_to replace will be replaced for string replaced in the file File.txt. In the loop the array is read, the first member of the pair is retrieved as replace_what=$i and the second as replace_for=$j. The find command searches in the directory the filename (that may contain a wildcard) and the sed -i command replaces in the same file(s) what was previously defined. Finally I added a grep redirected to the logfile to log the changes made in the file(s).
This worked for me in GNU Bash 4.3 sed 4.2.2 and based upon VasyaNovikov's answer for  Loop over tuples in bash.

Change multiple files


Instance methods and thread-safety of instance variables

Question: I would like to known if each instance of a class has its own copy of the methods in that class?
Lets say, I have following class MyClass:
public MyClass {

    private String s1;

    private String s2;

    private String method1(String s1){
    ...
    }

    private String method2(String s2){
    ...
    }
}

So if two differents users make an instance of MyClass like:
MyClass instanceOfUser1 = new MyClass();
MyClass instanceOfUser2 = new MyClass();

Does know each user have in his thread a copy of the methods of MyClass? If yes, the instance variables are then thread-safe, as long as only the instance methods manipulate them, right?
I am asking this question because I often read that instance variables are not thread-safe. And I can not see why it should be like that, when each user gets an instance by calling the new operator?
Comment: You're really confused. Thread-safety is about state. And state is about fields, not methods. The thread-safety of your class depends entirely on how the fields s1 and s2 are used by the methods. Not having their body makes the question impossible to answer.
Comment: *I am asking this question because I often read that instance variables are not thread-safe.* Since your question was tagged as java-ee (not sure why), you can see a real example of having non-static variables that are prone to thread-safety problems in Servlets, as explained here: [How do servlets work? Instantiation, session variables and multithreading](http://stackoverflow.com/q/3106452/1065197), read the article-like answer and the bottom section: **Threadsafety**. Note that you must understand how the component behaves to really know if its fields are prone to multithread issues.
Comment: Are you asking about each thread having its own instance of `MyClass` or one instance of `MyClass` with different methods for each thread?
Comment: No instance variables are inherently thread safe.  If two threads can modify a reference to the same object, then you need to implement some sort of synchronization
Comment: Making MyClass immutable would mean this question does not arise, of course.
Comment: @joel how to know if my mobect can be modified by two or more threads?
Answer: Each object gets its own copy of the class's instance variables - it's static variables that are shared between all instances of a class.  The reason that instance variables are not necessarily thread-safe is that they might be simultaneously modified by multiple threads calling unsynchronized instance methods.
class Example {
    private int instanceVariable = 0;

    public void increment() {
        instanceVariable++;
    }
}

Now if two different threads call increment at the same then you've got a data race - instanceVariable might increment by 1 or 2 at the end of the two methods returning.  You could eliminate this data race by adding the synchronized keyword to increment, or using an AtomicInteger instead of an int, etc, but the point is that just because each object gets its own copy of the class's instance variables does not necessarily mean that the variables are accessed in a thread-safe manner - this depends on the class's methods.  (The exception is final immutable variables, which can't be accessed in a thread-unsafe manner, short of something goofy like a serialization hack.)
Comment: Wait, so you're saying the `instanceVariable` field is not safe from conflicting reads/writes if a completely new instance is used in each thread? This *is* the scenario the OP is talking about, no?
Comment: @AsadSaeeduddin Obviously, every new instance is a brand new space allocated on the heap just for that object. Thread-safety is about how you access a single object which comes down to how that object's members are accessed - are they static or instance variables, if later, how is the invoked method guaranteeing thread-safety. In other words, how do you guarantee this - "completely new instance is used in each thread"?
Answer: Issues with multi-threading arise primarily with static variables and instances of a class being accessed at the same time.
You shouldn't worry about methods in the class but more about the fields (meaning scoped at the class level).  If multiple references to an instance of a class exist, different execution paths may attempt to access the instance at the same time, causing unintended consequences such as race conditions.
A class is basically a blueprint for making an instance of an object.  When the object is instantiated it receives a spot in memory that is accessed by a reference.  If more than one thread has a handle to this reference it can cause occurrences where the instance is accessed simultaneously, this will cause fields to be manipulated by both threads.
Answer: 'Instance Variables are not thread safe' - this statement depends on the context.
It is true, if for example you are talking about Servlets. It is because, Servlets create only one instance and multiple threads access it. So in that case Instance Variables are not thread safe.
In the above simplified case, if you are creating new instance for each thread, then your instance variables are thread safe.
Hope this answers your question
Answer: A method is nothing but a set of instructions. Whichever thread calls the method, get a copy of those instructions. After that the execution begins. The method may use local variables which are method and thread-scoped, or it may use shared resources, like static resources, shared objects or other resources, which are visible across threads.
Answer: Each instance has its own set of instance variables. How would you detect whether every instance had a distinct "copy" of the methods? Wouldn't the difference be visible only by examining the state of the instance variables?
In fact, no, there is only one copy of the method, meaning the set of instructions executed when the method is invoked. But, when executing, an instance method can refer to the instance on which it's being invoked with the reserved identifier this. The this identifier refers to the current instance. If you don't qualify an instance variable (or method) with something else, this is implied.
For example,
final class Example {

  private boolean flag;

  public void setFlag(boolean value) {
    this.flag = value;
  }

  public void setAnotherFlag(Example friend) {
    friend.flag = this.flag;
  }

}

There's only one copy of the bytes that make up the VM instructions for the setFlag() and setAnotherFlag() methods. But when they are invoked, this is set to the instance upon which the invocation occurred. Because this is implied for an unqualified variable, you could delete all the references to this in the example, and it would still function exactly the same.
However, if a variable is qualified, like friend.flag above, the variables of another instance can be referenced. This is how you can get into trouble in a multi-threaded program. But, as long as an object doesn't "escape" from one thread to be visible to others, there's nothing to worry about.
Answer: There are many situations in which an instance may be accessible from multiple classes. For example, if your instance is a static variable in another class, then all threads would share that instance, and you can get into big trouble that way. That's just the first way that pops into my mind...


Android create Listener onLongClick for listview

Question: in my application i have one activity with some fragments. one of this fragments i have list view and i want to create Listener to listening onLongClick on Listview items from activity, for example if end-user press long click on listview items into Fragment i must be show Toast in activity
for this action i'm create interface Listener such as:
public interface IOnLongClickReceiveSmsMaster {

    public void onLogin(Integer position);
}

in Activity i'm create BroadcastReceiver as :
method:
IntentFilter filter = new IntentFilter(M.ACTION_BROADCAST_LONGCLICK_LISTVIEW);
registerReceiver(NotifyLongClickOnItems, filter);

Broadcast function:
   private final BroadcastReceiver NotifyLongClickOnItems = new BroadcastReceiver() {
   @Override
   public void onReceive(Context ctxt, Intent i) {
        Toast.makeText(MainView.this, "LongClick", Toast.LENGTH_SHORT).show();
      }

now into Fragment i must be set defined interface to LongClick :
    private static IOnLongClickReceiveSmsMaster mOnLongClickReceiveSmsMaster;
    public View onCreateView( ... ){
    listview= (ListView) view.findViewById(R.id.listView);
    listview.setOnLongListener(new IOnLongClickReceiveSmsMaster() {

        @Override
        public void onLogin(Integer position) {

        }

    });
   };
   .
   .
   .
   }

public static void setOnLongListener(IOnLongClickReceiveSmsMaster l) {
    mOnLongClickReceiveSmsMaster = l;
}

unfortutaley my code is not correct and i get this error:
The method setOnLongListener(new IOnLongClickReceiveSmsMaster(){}) is undefined for the type ListView

i think my analysis for have this ability is not correct, please help me to resolve that
Comment: check this https://developer.android.com/reference/android/widget/AdapterView.html#setOnItemLongClickListener%28android.widget.AdapterView.OnItemLongClickListener%29
Answer: It would be a lot easier if you just used AdapterView.OnItemLongClickListener. This is how:
getListView().setOnItemLongClickListener(new OnItemLongClickListener(){
    public boolean onItemLongClick(    AdapterView<?> arg0,    View v,    int position,    long id){
        /* Do whatever you want here, e.g. go to next Activity etc. */
        return false;
    }
};

To notify your Activity, create an interface inside your Fragment class
public interface LongClickNotifier{
    public void notifyOnLongClick(int position, View v);
}

and have your Activity implement this interface
public class MainActivity extends Activity implements LongClickNotifier{

    ...
    ...

     @Override
     public void notifyOnLongClick(int position, View v){

         /* Do whatever you want here with "position" and "v". */
     }
}

Now in your Fragment,
getListView().setOnItemLongClickListener(new OnItemLongClickListener(){
    public boolean onItemLongClick(    AdapterView<?> arg0,    View v,    int position,    long id){
        ((LongClickNotifier)getActivity()).notifyOnLongClick(position, v);
        return false;
    }
};

And there you go! No need to create a BroadcastReceiver or anything else!
Comment: add the opening brace `{` to your `Activity` class :)
Comment: listView in into Fragment and i want to create Listener for listen for that from activity
Comment: thanks, i get this error in activity `Syntax error on token "LongClickNotifier", { expected after this token`
Comment: OH work fine sir thanks :) after long click list view itemt content like single click on listview items, how to disable that?
Comment: i'm change false to true in `setOnItemLongClickListener` worke fine sir, very thanks
Answer: First you just take List view object.
ListView listView = (ListView)findViewById(R.id.yout_list_view_layout_id_here);

After that, just define a listener to list view.
 listView.setOnItemLongClickListener(new OnItemLongClickListener() {

        public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                int pos, long id) {
            Log.v("List view long clicked ","position : " + pos);
            return true;
        }
    });

Comment: listView in into Fragment and i want to create Listener for listen for that from activity
Comment: You want to show toast. It can be shown in fragment also. Either you implement listener in fragment and  you can pass activity context into fragment and use that context to do any operation.


Radon- Nikodym Theorem For von Neumann algebras

Question: Sakai's Radon Nikodym Theorem for von Neumann algebra goes as follows:

Let $\phi$ and $\psi$ be normal forms on a $von$ $Neumann$ $algebra$ $M$ such that $\phi$ $\leq$ $\psi$. Then $\exists$ $a$ $\in$ $M$ uniquely determined by the following conditions:

$0$ $\leq$ $a$ $\leq 1$
$s(a)$ $\leq$ $s(\psi)$
$\phi=L_aR_a\psi$

The proof of this version of the theorem can be found in Stratila-Zsido  starting on Page 125 whose pdf version is available online via Google Search.
I want to show that this is equivalent to the Radon Nikodym Theorem that one encounters in Measure Theory when $M = L^{\infty}(X,A,\mu)$ for some finite measure $\mu$ with the condition that the Radon Nikodym derivative is bounded by 1. Please help me with this.
In this context, I shall be grateful if someone can also explain to me ( with proof ) the analogous notions of $s(a)$ and $s(\psi)$ when $M = L^{\infty}(X,A,\mu)$ for some finite measure $\mu$. I guess that they are somehow related to the support of measures.
Some defintions of terms used above -

Normal forms are $\sigma$ - weakly continuous positive forms.
$\phi$ $\leq$ $\psi$ $\iff$ $\psi(x)$ - $\phi(x)$ $\geqslant$ $0$ $\forall$ $x$ $\geqslant$ $0$.
$s(a)$ = projection onto the closure of the range of  $a$.
$1$ - $s(\psi)$ = $sup$ { $p$ $\in$ $P_M$ : $\psi(p) = 0$ } where $P_M$
denotes the set of all projections in $M$.
$(R_a\psi)(x)$ = $\psi(xa)$ and $(L_a\psi)(x)$ = $\psi(ax)$ $\forall$ $x$          $\in$ $M$.

Thanks for any help.
Comment: A better way to use italics on this site is to enclose the word in `*` symbols, instead of using math mode (which looks strange and renders slowly). But are you sure you need to use italics as much as you do? When almost every other word is emphasized, it really loses its impact.
Comment: I guess you are quite right.Thanks for the suggestion.
Answer: Sakai's theorem does not imply Radon-Nikodym's theorem in its full generality. Because the $a$ Sakai's theorem gives is bounded, while in general the Radon-Nikodym derivative can be unbounded.
For instance if $\mu$ is Lebesgue measure on $[0,1]$, you can take
$$
\nu(E)=\sum_{n=1}^\infty 2^n\,\mu\left(E\cap\left(\frac1{2^n},\frac1{2^{n-1}}\right]\right).
$$
Then $\nu$ is absolutely continuous with respect to $\mu$, but the linear functional it produces on $L^\infty[0,1]$ is unbounded. In fact, the Radon-Nikodym derivative is the unbounded function
$$
h=\sum_{n=1}^\infty2^n\,1_{\left(\frac1{2^n},\frac1{2^{n-1}}\right]}.
$$
The converse also has problems: in general, not every state of $L^\infty(X)$ is given by integration against a measure (in the usual sense, at least).
Comment: I mean for the special case when the Radon - Nikodym derivative is bounded, does the assertion hold good? And can you please explain the concept of supports in L^(infinity)?


How to apply heteroscedasticity to multiple linear regression in R?

Question: I have trying to improve a multiple regression model (reducing RMSE further), and have found heteroscedasticity evidence for 2 variables. I have found 2 options for reducing heteroscedasticity in linear regression: first is to get square root Y (response variable), and second is to use box-cox transformation (as per https://www.r-bloggers.com/how-to-detect-heteroscedasticity-and-rectify-it/).
All examples I have found show single input variable solutions. I'm trying to figure out how this will play out in multiple linear regression analysis. In analysis of each of the 3 relationships (predictors and responses) individually,  only 2 show evidence of heteroscedasticity. How do I apply to only 2 out of 3? I am playing around eg square root of y to entire multiple regression.
In R, below, I've created a new column which is squareroot of output variable y (using caret library):
<code>  model2 <- train (ysqrt ~ x1 + x2 + x3, trainX, method = "lm", trControl = trainControl (method="cv", number=10))
</code>
This just doesn't seem right though.
Thanks in advance.
Answer: What about using White robust standard errors?
https://en.wikipedia.org/wiki/Heteroscedasticity-consistent_standard_errors
Take a look at this to apply this method with R:
Replicating Stata's "robust" option in R
Comment: Thanks, I gave this a go. It's the best info I've seen so far.
Comment: I'm glad info was useful for you. Sorry if I don't give in depth explanations. Sometimes it's hard for me to write in english.


C#: BigInteger to string with radix specified

Question: In both Java and Javascript, BigInteger have a function called toString(int radix) which returns the String representation of this BigInteger in the given radix.
I'm wondering is there any approach in C# (.NET) to do the job that java and javascript can do?
Comment: Note that if you only need base 16, it is possible to `.ToString("X")`. If you need base 2, 4 or 8 it is probably faster to "convert" from base16. For the other bases, you do as they teach in school, division and remainder. There is a `DivRem` method in `BigInteger`
Comment: and for "convert" I mean that there is a direct string replacement from base 16... base16 to base2 for example, 0->0000, 1->0001,...F->1111. Same for base16 to base8:-> 0->00, 7->07, 8->10, F->77
Comment: Does this answer your question? [BigInteger to Hex/Decimal/Octal/Binary strings?](https://stackoverflow.com/questions/14048476/biginteger-to-hex-decimal-octal-binary-strings)
Answer: You can easily implement an extension method for this, e.g.
  using System.Linq;
  using System.Numerics;

  ...

  public static partial class BigIntegerExtensions {
    // this have to be used for extend BigInteger
    public static String ToRadixString(this BigInteger value, int radix) {
      if (radix <= 1 || radix > 36)
        throw new ArgumentOutOfRangeException(nameof(radix));
      if (value == 0)
        return "0";

      bool negative = value < 0;

      if (negative)
        value = -value;

      StringBuilder sb = new StringBuilder();

      for (; value > 0; value /= radix) {
        int d = (int)(value % radix);

        sb.Append((char)(d < 10 ? '0' + d : 'A' - 10 + d));
      }

      return (negative ? "-" : "") + string.Concat(sb.ToString().Reverse());
    }
  }

And then use it:
 BigInteger x = 123456;

 // HIID
 Console.Write(x.ToRadixString(19));

Demo:
  BigInteger x = 123456;

  string demo = string.Join(Environment.NewLine, Enumerable
    .Range(2, 35)
    .Select(radix => $"{x} (radix = {radix,2}) = {x.ToRadixString(radix)}"));

  Console.Write(demo);

Outcome:
123456 (radix =  2) = 11110001001000000
123456 (radix =  3) = 20021100110
123456 (radix =  4) = 132021000
123456 (radix =  5) = 12422311
123456 (radix =  6) = 2351320
123456 (radix =  7) = 1022634
123456 (radix =  8) = 361100
123456 (radix =  9) = 207313
123456 (radix = 10) = 123456
123456 (radix = 11) = 84833
123456 (radix = 12) = 5B540
123456 (radix = 13) = 44268
123456 (radix = 14) = 32DC4
123456 (radix = 15) = 268A6
123456 (radix = 16) = 1E240
123456 (radix = 17) = 18232
123456 (radix = 18) = 1330C
123456 (radix = 19) = HIID
123456 (radix = 20) = F8CG
123456 (radix = 21) = D6JI
123456 (radix = 22) = BD1E
123456 (radix = 23) = A38F
123456 (radix = 24) = 8M80
123456 (radix = 25) = 7MD6
123456 (radix = 26) = 70G8
123456 (radix = 27) = 679C
123456 (radix = 28) = 5HD4
123456 (radix = 29) = 51N3
123456 (radix = 30) = 4H56
123456 (radix = 31) = 44EE
123456 (radix = 32) = 3OI0
123456 (radix = 33) = 3EC3
123456 (radix = 34) = 34R2
123456 (radix = 35) = 2URB
123456 (radix = 36) = 2N9C

Comment: Thank you so much for helping! This indeed solve my question :D


How to replace a member object by an other in c++

Question: I want to assign a specific struct to a member variable in c++, but my attempt fail. after some tests i recognized that after the assigment the variable dont hold the object passed, but rather implicitly calls the copy constructor and just copies the values to a new object. Isn't it possible to overwrite a  object variable in c++?
now the detailed situation:
I don't have much experience in c++, but have to write some c++ code due to the attempt to manually make a jni wrapper for an existing little c library. i am realizing it through proxy classes on the java side, which just hold the adresses of the c++ counterparts and redirect method calls. the library consist of a lot of structs, which i wrote java classes for. the assignment and access of the members is realized through getters and setters on the java side.
//C-lib code

struct A {
   int testVal;
   ...
}

struct B{
   struct A a;
   ...
}

I got two structs. while the first holds some unimportant code, the second sonsist of a member of the first struct.
//java proxy classes

public class A{
   private long ADRESS;

   public native int getTestVal();
   public native void setTestVal(int testVal);
   ...
}

public class B{
   private long ADRESS;

   public native A getA();
   public native void setA(A a);
   ...
}

the only variable in the java counterparts is the long holding the adress, the access to the inner struct in b is submited through the getter and setter methods. the code word native declares that the method is implemented in native code.
//java test class

public class Test{

   public static void main(String[] args){

      A a = new A();
      B b = new B();
      b.setA(a);
   }
}

I wrote a java test class to check whether the assigment succeeds.
//JNI interface method for setA

   JNIEXPORT void JNICALL ..._setA
    (JNIEnv *env, jobject java_b, jobject java_a){

        B *b = getBoundObject(env, java_b);
        A *a = getBoundObject(env, java_a);

        a->testVal = 999;
        b->a = *a;
        printf("\nBEFORE ASSIGNMENT %i | %i\n", a->testVal, b->a.testVal);

        b->a.testVal = 200;
        printf("\nAFTER ASSIGMENT  %i | %i\n", a->testVal, b->a.testVal);

}

the jni interface implements the layer between c library and java code. it is written in c++. the testVal variable represents a variable which i just used to check whether the objects are the same.
the output of the printf calls look like this:
#C-site: BEFORE ASSIGNMENT 999 | 999
#C-site: AFTER ASSIGMENT 999 | 200
isn't there a way to really assign the object to the variable rather than just copy the values? it is important because the objects are still used on the java side.
suggestions?
Answer: Seems to me that you need to use pointers. Any time you assign an object, the copy constructor is called to copy everything into the new object. If you use pointers, nothing new should be allocated.
Therefore your struct B should keep a pointer to A rather than the A object. Then your setA() parameter should be setA(A* a).
Comment: I also thought about doing this, but didn't because it would make it neccessary to directly modify the code inside the lib, what i wanted to avoid. But if that behavior is unchangeable, i should perhaps just delete the setter.
Comment: Oh, I actually just realized that your setter and getter functions are in Java. But yea, what you want is still pointers, because assigning an object to a variable is implicitly cloning the object. If you want the original object to be assigned to a new variable, you have to use pointers.


How to interpret this PCA biplot?

Question: I am approaching PCA analysis for the first time, and have difficulties on interpreting the results. This is my biplot (produced by Matlab's functions pca and biplot, red dots are PC scores, blue lines correspond to eigenvectors; data were not standardized; first two PCs account for the ~98% of the total variance of my original dataset):

My personal interpretation is that (if I get it right) all variables (b1 to b7) have positive values in the PC1 axis, while b5 and b7 are positive in PC2's and b1 to b4 are negative.
Since all the variables are positive in PC1, those which constrain the system the most are b5 and (then) b7 and b4 (in PC1 axis).
In PC2 axis, the two set of variables have opposite effects on the system (up to me guessing what's the intrinsic meaning of it).
Talking about the scores, they are well clustered, thus I think they all respond to the system quite uniformly, except some outsiders.
My problems:

Is there a connection between the blue vectors direction and the position of the scores? Meaning, do variable vectors which end close to some scores have something to do with those same scores?
If data are well clustered, how do I interpret the results of the PCA in terms of what variable has a major (or minor) influence on the system?
Comment: I used the 'pca' function in MATLAB 2014 (http://it.mathworks.com/help/stats/pca.html?refresh=true). I used raw data.
Comment: Sorry, I plot the coefficients calculated through the 'pca' function and those are the blue lines (vectors), and the 'scores' (which are the red dots), using the function 'biplot' of MATLAB (http://it.mathworks.com/help/stats/biplot.html)
Answer: Your interpretation is mostly correct. The first PC accounts for most of the variance, and the first eigenvector (principal axis) has all positive coordinates. It probably means that all variables are positively correlated between each other, and the first PC represents this "common factor". The second PC (looks like it has much smaller variance) contrasts b5 and b7 from everything else.

Is there a connection between the blue vectors direction and the position of the scores? Meaning, do variable vectors which end close to some scores have something to do with those same scores?

Here is one way to look at it. Imagine that you had a data point with original coordinates $(1,0,0,\ldots)$, i.e. only one variable is equal to $1$ and others to zero. Then this imaginary data point would have PC scores as the end-point of your b1 vector. The same goes for other vectors as well.
Having said that, as the original 6D space is projected on 2D, many different points can be projected to the same 2D point, so if one blue vector, e.g. b1 has an end-point near one particular red point, it does not necessarily mean that this data point had coordinates $(1,0,0,\ldots)$.
I should add that the above is true only for this particular normalization of a biplot, when blue lines correspond to eigenvectors, and the PC scores are not standardized.

If data are well clustered, how do I interpret the results of the PCA in terms of what variable has a major (or minor) influence on the system?

I don't really understand this question. I would not call these data "well clustered", it rather looks like a unimodal distribution. And all variables seem to be pretty similar in your case, positively correlated between each other and contributing similarly to PC1/PC2.

How to interpret this PCA biplot?


what is the sum of following permutation series $nP0 + nP1 + nP2 +\cdots+ nPn$?

Question: what is the sum of following permutation series $nP0 + nP1 + nP2+\cdots+ nPn$ ?
I know that
$nC0 + nC1 +\cdots + nCn = 2^n$, but not for permutation. Is there some standard result for this ?
Comment: what is the meaning/definition of $nPk$?
Comment: @Mercy: $n(n-1)(n-2)\cdots(n-k+1)$. The ordered combinations of $k$ elements from $n$ possibilities.
Comment: I don't think there is a closed form for that sum, but since
$n(n-1)\cdots(n-k+1)=n!/(n-k)!$ you can at least write it as $n!\sum_{k=0}^n1/k!$
Comment: @Mercy That is what I have written in my answer. $$\sum_{k=0}^{n} \dfrac1{k!} = \dfrac{e \Gamma(n+1,1)}{n!}$$
Answer: You can write this as
$$ S(n) = n! \left( {1 \over 0!} + {1 \over 1!} + \cdots + {1 \over n!} \right) $$
and now recall that $e = 1/0! + 1/1! + 1/2! + \cdots $. So in fact
$$ S(n) = n! \left( e - \left( {1 \over (n+1)!} + {1 \over (n+2)!} + \cdots \right) \right) $$
and we can rearrange this to give
$$ S(n) = n! \times e - \left( {1 \over (n+1)} + {1 \over (n+1)(n+2)} + \cdots \right). $$
Call the expression in parentheses $g(n)$ -- that is,
$$ g(n) = {1 \over (n+1)} + {1 \over (n+1)(n+2)} + {1 \over (n+1)(n+2)(n+3)} + \cdots $$.
Then clearly
$$ g(n) < {1 \over n} + {1 \over n^2} + {1 \over n^3} + \cdots $$
and by the usual formula for the sum of a geometric series,
$$ g(n) < {1/n \over 1-(1/n)} = {1 \over n-1}. $$
In particular if $n > 2$ we have $g(n) < 1$ and therefore $(n! \times e) - 1 < S(n) < n! \times e$.  But $S(n)$ is a sum of integers and is therefore an integer. So $S(n) = \lfloor n! \times e \rfloor$ -- that is, $S(n)$ is the greatest integer less than $n! \times e$. For example $4! \times e \approx 65.23$ and $S(4) = 65$.
This sequence is A000522 in the OEIS and the formula I gave here is given there without proof.
Also, the number of derangements of n elements is given by $n! (1/0! - 1/1! + 1/2! - \cdots \pm 1/n!)$ and can similarly be proven to be the integer closest to $n!/e$.
Answer: Let us call the sum $S(n)$. We have $S(1) = 1P0 + 1P1 = 1+1 = 2$.
For $n\gt 1$, we can factor out $n$ to get
$$\begin{align*}
S(n) &= nP0 + nP1 + nP2 + \cdots + nPn\\
&= 1+ n + n(n-1) + \cdots + n!\\
&= 1+ n\Bigl( 1+(n-1) + (n-1)(n-2) + \cdots + (n-1)!\Bigr)\\
&= 1+nS(n-1).
\end{align*}$$
Thus, the sequence begins:
$$\begin{align*}
S(1) &= 2\\
S(2) &= 1 + 2S(1) = 5\\
S(3) &= 1+ 3S(2) = 16\\
S(4) &= 1+4S(3) = 65\\
S(5) &= 1+5S(4) = 326\\
&\vdots
\end{align*}$$
This is sequence A00522 on the On-Line Encyclopedia of Integer Sequences. The entry contains numerous connections; e.g., $S(n)$ is the permanent of the $n\times n$ matrix with $2$s in the diagonal and $1$s elsewhere; it also gives the formula from Marvis's post:
$$S(n) = \exp(1)\Gamma(n+1,1)\text{ where }\Gamma(z,t)=\int_{x\geq t} \exp(-x)x^{z-1}\, dx$$
Comment: Also the exponential generating function for $S(n)$ has a nice form: $\sum_{n=0}^\infty \frac{t^n}{n!} S(n) = \sum_{n=0}^\infty \frac{t^n}{n!} \int_{1}^\infty x^n \mathrm{e}^{1-x} \mathrm{d} x = \int_1^\infty \mathrm{e}^{t x + 1 -x} \mathrm{d} x = \frac{\mathrm{e}^t}{1-t}$, valid for $t < 1$.
Answer: There is no "nice" closed form as such though it is related to the incomplete $\Gamma$ function.
$P(n,k) = \dfrac{n!}{(n-k)!}$. Hence, $$\sum_{k=0}^{n} P(n,k) = n! \left( \sum_{k=0}^{n} \dfrac1{(n-k)!} \right) = n! \left( \sum_{k=0}^{n} \dfrac1{k!} \right)$$
The above sum is related to the incomplete $\Gamma$ function, which is defined as $$\Gamma(n+1,x) = \int_x^{\infty} t^{n} e^{-t} dt = n! e^{-x} \sum_{k=0}^n \left(\dfrac{x^k}{k!} \right)$$ taking $n$ to be a positive integer. Setting $x=1$, we get that
$$\Gamma(n+1,1) = \dfrac{n!}e \left(\sum_{k=0}^n \dfrac1{k!} \right)$$
Hence, $$\sum_{k=0}^{n} P(n,k) = e \times \Gamma(n+1,1)$$


Test the significant differences between the coefficients obtained by logistic regression on two data sets.

Question: So I run logistic regressions of same dependent variables and independent variables on two sets of data $S_1$ and $S_2$. I obtained two sets of coefficients $\beta_1$ and $\beta_2$. Now I suspect that $\beta_1$ and $\beta_2$ should really be equal, since I don't think there are distinctive difference between $S_1$ and $S_2$.
My question is, how do I test the significant differences between the coefficients?
Thanks!
Comment: One thing to keep in mind: In logistic regression, the coefficients and variance are not separately identified. As a result, comparing estimates from separate models run on separate data is misleading. Greg Snow's answer below avoids this problem since everything is estimated in the same model.
Comment: But since in the two models we generally impose that the variance is the same, why can't we compare the results of the two models?
Answer: You can stack the 2 datasets on top of each other with an indicator variable for which dataset the data comes from.  Example (simplified):
<code>> d1
  y x
1 0 1
2 0 2
3 1 3
> d2
  y x
1 0 2
2 1 3
3 1 4
> d3
  y x g
1 0 1 0
2 0 2 0
3 1 3 0
4 0 2 1
5 1 3 1
6 1 4 1
</code>
Then fit a model with interactions with the grouping variable, i.e.
<code>logit(y) ~ b0 + b1*x + b2*g + b3*x*g
</code>
The test on b2 will measure the difference in the intercepts (compare to your seperate fits) and b3 will measure the difference in the slopes (compare again), so tests on b2 and b3 are the tests of interest.  If you have additional covariates then just include them as well with the interaction terms.
Comment: You can do a Wald-Z test on a specific coefficient in a logistic regression, but this tests each coefficient individually and if you really want to see if there is a difference between groups then you need to test them together (as @lejohn pointed out).  Also the z-test can suffer from the Hauk-Donner effect sometimes where a very large coefficient is not seen as significant because the variance is overestimated.  Better is to use a full/reduced model liklihood ratio test.
Comment: +1 for this answer. I would just like to add a nuance. Of course, b2 and b3 are the coefficients of interest here. However, you have to test if they are simultaneously equal to zero, and not separately.
Comment: Hi Greg. A follow-up question. How do I test if b2 and b3 are equal to zero? I know in linear regression there is t-stat, but not sure if there is such an equivalence in logistic regression. One way I know regarding feature selection is I can test if the deviance changed much after removing b2*g and b3*x*g from the logistic regression, but is there any more straightforward metrics like t-stat in logistic regression? Thanks!
Comment: Great answer! One question, wouldn't this approach suffer if one of the data sets were much smaller than the other? Say you had 10 rows in d1 and 100 rows in d2. If so, is there a way of compensate for the different sizes of the data sets?
Comment: @RasmusBååth, you get better power when the sample sizes are equal, but the validity and general properties of the test should not suffer from unequal sample sizes.  If there is a specific concern then you can simulate data and test out the proceedure to see how it behaves.


Bearing of a line or a point

Question: Rochelle is 25 miles due south of Rockford,and North Chicago is 65 miles  due east of Rockford.Find the bearing of North Chicago From Rochelle.
I used Pythagorean theorem in solving this because i thought that the only one that is asked  in the question is the distance from south to east in terms of hypotenuse.I got 69.64 miles as the answer but as i searched the word "bearing",it has something to do with the angle so i am confused now if what is the correct answer.Can you help me? Thanks
Comment: Try searching for the term "true bearing".
Answer: The bearing from one point to another is the direction of the line between those points.
Usually in problems like these, where the principal directions are north, east, south, and west, the convention is that the direction due north is a bearing of $0$ degrees,
due east is $90$ degrees, due south is $180$ degrees, and due west is $270$ degrees.
For example, in this problem the bearing from Rockford to Rochelle is $180$ degrees
and the bearing from Rockford to North Chicago is $90$ degrees.
You can compute other bearings by measuring the angle that the line between the points
makes with the coordinate axes. It can be helpful to draw a right triangle in which
one leg runs north-south and the other runs east-west.
Answer: One way to reckon : $\tan^{-1}\frac{65}{25} $ due West of Rochelle.

Bearing of a line or a point


getting uploaded file name at node title

Question: Users will upload files.  The user will tag the file with a project name and some keywords and an optional text comment.  I have made a content-type called 'image', that has filed for title, file, project, keywords and comments.
I want the tile of the node to be the name of the uploaded file.  The name of the filed is 'file' the field is of type File, the widget is of type File, and the filed name is field_file.  I have the token module and the "Automatic Nodetitles" module.  The token module gives me token "node:field_file_body", this is not the file name.
How do I set the title of the each "image" node to the name of the uploaded file?
Comment: If you looking at just nodes then http://drupal.org/project/auto_nodetitle is fine but if you are looking at the entity level to be used across all entity types then I would suggest http://drupal.org/project/auto_entitylabel which will most probably replace auto node title in the future.
Answer: I also battled with this; this is my solution:
Use the Automatic Nodetitles Module as described by the others, and in the Pattern for the title text box load up the filefield and extract the filename that way. Example:
<?php
//Load the file
$file = file_load($node->field_document['und'][0]['fid']);

// Filename
return $file->filename;
?>

Obviously you need to check the Evaluate PHP in pattern. checkbox at the bottom for this to work, and replace "field_document" with the name of your own file field.
Hope this helps somebody!
Answer: You could try this module: FileField Paths. From the description, it looks like it might provide you with the tokens you need.
Edit Here's the code where it adds the tokens if you're interested: see the repository. If that's not what you need, it's probably pretty close to what you need.
Edit 2 Looks like you'll have to create a module. Don't stress, it's not hard. This blog post shows you how to create a module which provides custom tokens for nodes. You can combine that with the repository link in my first edit to acheive the token you need. If you've never created a module before, it's simple. Follow the simple tutorial on Drupal.org. All you need is a folder in sites/all/modules with the files mymodule.module and mymodule.info where "mymodule" is your module name.
Comment: I have FileField Paths module. There is no token for file_name or file_info just file_body.  I am still learning how to modify drupal and am somewhat at a loss.
Comment: I just added more info. I guess the "files" tokens are only available to fields. You need to add the token you need to the "node" area.
Comment: Joe - Are you using Drupal 6 or 7 BTW? Yeah at any rate for this to work, you should be using CCK filefield upload for D6 and Fields file upload for D7. I don't think you need to create a module, see my answer below. I just tested Auto Nodetitles Module and sure enough the File was available as a token for Auto Nodetitles
Answer: In addition to what @Jonathan Rowny said, you could also use the Automatic Nodetitles Module and then use the Token of the uploaded file name as the auto node title. But you will also need the Token module installed / activated. I have used this method and it works great.
Added: screen capture from Auto Nodetitles that can use a token name of the file name.
Comment: Where is the file name token?  I look in the token lists for "Nodes" and all I can find is [node:field_file_body].  I have looked everywhere but not found anything with "file name".  I am using Drupal 7.
Comment: Whenever you use Token, you have "`Replacement Patterns`" contextual to where you are using tokens. See my screen capture I have added above.
Comment: Arghh.... I am missing something very basic.
Comment: Arghh.... I am missing something very basic.  I am using Drupal 7 I have a filed named "file" that is of type "File" that has a MySQL filed name of "field_file" and a widget of type "File".  I have modules "Token", "FileField Paths" and "Automaic NodeTitles".  My first screen lokks just like yours but I never get a "Replacement Patterns" area.  all I get is Name: File,  Token: [node:filed_file_body], Description: File field .  How do I amke Replacement Pattern appear?  I never get anything like your second screen.
Comment: Damn... How do I post an image to this site?
Comment: If I use Drupal 7 should I load CCK module (the only releases for CCK are Development releases for Drupal 7).  Will CCK give me the replacment tokens?
Comment: Joe you don't need CCK Module for Drupal 7, it's now built in as "Fields". It sounds like you are doing everything correctly. Are you sure you have all those modules enabled?
Comment: Yes, I carefully went over the modules and made sure all were enabled.  Where is the "replacement Patterns" found?  How do I post an image to this site so I can show what I see?  I am sure I am missing something very basic or else my combination of modules is screwing things up somehow.
Comment: You can edit your original question and click the image button to upload an image or post an image to a comment using a 3rd party image service.
Comment: OK, I think I know what the problem is.  I need to write a module (correct?).  I am looking for a token that does not exist in the node section until I write a module that puts it there (correct).  I was looking for a token in the page with the "automatic title generation" but there is non there of the file name, ... I have to write a module that will put the token there.  (correct?)
Comment: ah, it looks like there is an issue for this: http://drupal.org/node/691078?page=1 so it looks like, it's going to be hard to get this to work today but it looks promising that it will work.
Comment: ok... so this is a recognized bug in Tokens module.  I will skip the automatic titles, for now, and manually enter the node titles.  Any hint on when this issue will be fixed?  I am using Tokens 7.x-1.0-rc1 (I am OK with writing a module to fix the issue, but if the issue will be fixed in the next release of Tokens, I would much rather just wait.)
Comment: Well the issue was opened over a year ago but it seems like they are getting close. I've seen issues sometimes take a few years to get fixed, that's the pros / cons of open source, it's a community effort but sometimes things are a little slow to move. If you think you can write a module to fix it why not and then perhaps contribute back to drupa.org with a sandbox project.
Comment: I don't think the community would want my module that moves one field (file name), into the Nodes area.  I have written 2 trial modules and FAR from a master module coder.  The issue is marked as a "Major" bug in the Tokens module, so they will probably fix it "soon".  My boss is cool with me saying that the issue is a Drupal module bug.  I will just manually enter file names as titles for now.
Comment: ok i see what you are saying, seems like a good short term solution then.
Answer: I got it working with Automatic Nodetitles, Token, and Entity Token.  I used the following token:
[node:field-file:file]
As you described in the question, I have a field called file in my nodetype.  I believe the :file portion of the token was created by Entity Token.


How can I get module configuration for testing

Question: I write tests for a form in a custom module using Drupal\simpletest\WebTestBase. I want to test, if the module settings are displayed in the configuration form. But the problem is, that I can not get the saved settings:
$config = $this->config('mymodule.settings');
debug($config->get(), 'Configuration object'); // Returns an empty array

I have found, that the same problem is e.g. in the demo module described in an article  on Sitepoint, see: https://github.com/upchuk/d8-demo-modules/blob/master/demo/src/Tests/DemoTest.php#L59

E.g. $config->get('demo.email_address') returns always ''.

The tests seem to work well, but when I add debug($config->get()), then I also receive an empty array. It means, that all the test cases use empty variables and return false positive results.
I have also tried:
debug(\Drupal::config('mymodule.settings')->get()); // Empty array
debug(\Drupal::configFactory()->getEditable('mymodule.settings')->get()); // Empty array
debug(\Drupal::config('system.site')->get()); // Correct array with site settings

The module and the form are working correctly and all the settings are stored in the database.
Comment: Did you require your module as a dependency of the test in `static $modules =` array?
Comment: Yes: public static $modules = array('mymodule');
Comment: Also the demo module have the $modules property, see: https://github.com/upchuk/d8-demo-modules/blob/master/demo/src/Tests/DemoTest.php#L19
Answer: The tests do not care about the settings, which are saved in the database. They work with settings in config/import/mymodule.settings.yml
The file can look like this:
var1: 'Some text'
var2: 1
var3: http://example.org

More info: https://www.drupal.org/docs/8/creating-custom-modules/include-default-configuration-in-your-drupal-8-module


Jazz piano: chords and melody in right hand. How?

Question: Aiming for being capable of playing solo and in ensemble, a jazz pianist is exposed to the following:

Bass player is playing the root tones, hence the pianist can play rootless
When playing alone or improvising, both hands can handle harmony and and typically right hand melody. In the case of playing alone, base tone needs also to be covered.
While comping, the melody is covered by the soloist.

During my time learning piano I've basically in my solitude opened up jazz standards and learned them with compact voicings in my left and melody in my right. Straight forward. Now, moving towards more complex solo playing and playing in ensembles, I want and need to learn having voicings in my right hand, preferably combined with the melody. It's a bit of unlearning, and I find old habits hard to break. This is my quest, and I find it overwhelming to learn.
So I wonder:

What is the best approach for learning this? Voicings and melody combined in right hand.
How does one plan the layout? The chord/voicings can clash with the melody or the hand positioning and there are so extremely many combinations at each moment, such as when combining fingering and from what chord you're coming from to what you're going to, that I don't see how one consciously can decide between all those. This is significant with jazz piano/theory: this overwhelming amount of combinations. For instance, given twelve tones and all different intervals, you have a huge amount of combinations to navigate in order to understand various concepts. To me it seems one has to learn a set of combinations/sequences and then fall back to that subconscious routine/muscle memory.

In one way the answer is simple: "just expose yourself to it through your grinding and practice, until you get it", but I suspect that you people have as usual something clever to say!
Comment: I would like to point out that this question has partly a good answer related to mine: https://music.stackexchange.com/questions/58506/jazz-harmonization-in-the-right-hand-on-piano
Comment: Not sure I understood what the exact problem really is, but check out this two minute video that outlines the basic steps, how to move from "left hand chords, right hand melody" to more pianist-like playing https://www.youtube.com/watch?v=78-Ggxq6868
Comment: Yes, what that video demonstrates is what I want to achieve. I find it hard. One finger layout may match the first set of tones in a bar, but may not match the next ones, or it might not be suitable with from what finger layout one is coming from -- it's a chaotic mess and no matter what I find it hard to find layouts that works well. After playing say a couple of sets of tones into a bar it's tempting to go back and play it in a different way when knowing how it developed, but that's an approach that for obvious reasons is a no go, or require memorising.
Comment: I think the exact finger techniques and layouts will sort themselves out by lots of playing, or at least that's how it worked for me. One way to develop it is to focus on the rightmost fingers 4-5 or sometimes 3-5 playing a smooth uninterrupted legato melody, and adding chord tones at least on rhythmically relevant beats with fingers 1-2 or 1-3 if you can. Every now and then your melody fingers have to make a jump, and to keep the melody fluid and continuous you'll have to do some finger maneuvers, but I think you'll "invent" them if you play a lot and focus on keeping your lines continuous.
Answer: You don't seem to have done anything that jdjazz suggested in his answer three years ago. It was a very good answer. As Laurence Payne says, you need to study, or at least play through, lots of piano music.
You say you're playing jazz standards "with compact voicings in my left and melody in my right." So you only use one RH finger at a time? And all its spare fingers do nothing? Well why not stop playing these compact voicings all the time, uncompact them and give some of the notes to your RH? Sharing the notes of the chords between the hands is very elementary stuff for a piano-player.
BTW, have you been playing a lot of George Shearing?
Comment: Yeah, I guess I play with one finger at the time, the spares do nothing. Yupp, the plan is to uncompact. No, I haven't even heard of George Shearing. I agree jdjazz's answer was good, I will try to incorporate it over time.
Answer: Study piano music, from Mozart to contemporary.  You'll find a multitude of ways of playing bass, chords and melody all at once. That's what piano music DOES!
Ok, different rhythms, different chords.   But it's still the three basic elements - melody, bass and something in the middle.
Comment: I think its pretty clear from the question that OP knows this happens, and "study piano" is a correct but trivial answer. It looks like the question instead of negating the existence of "something in the middle" is asking how to approach the overwhelming amount of possibilities. There are theoretical approaches and progressive pedagogical steps to take which would be interesting to read.
Comment: @hirschme I've read Frans's question a few times and can't make out what he/she is looking for or needs except, as Laurence suggests, a much wider experience of music.
Comment: I would suggest listening to a good block chord player as well, such as Brubeck, for some ideas on getting both chords and melody into the right hand.
Answer: A small point: when comping, a way to avoid quite a bit of trouble is to choose voicings that do not overlap on the range of the melody line. Either both hands below (especially if there's no other bass line), or one above and one below, or even both above if the melody line is mid-range and there's a bass and maybe other mid-range stuff happening.
Another specific: unless your group wants that kind of thing, voicings that would otherwise be interesting but create minor seconds (or major seconds?) or non-meaningful tritone intervals with the melody line are maybe not a good idea. That is, some voicings that would be interesting for a solo piano are maybe not so good as accompaniment.
Also, unlike solo, where you more-or-less need to have something happening all the time, when comping you can play in a much lighter way, leaving lots of silence in your part. There doesn't have to be the same continuity. So you can imagine harmonic or melodic progressions (perhaps in other parts), and just "tag up" here and there, especially for rhythmic purposes.
And, the latter: in an ensemble, the piano part can be much more a rhythm instrument, with some tonal and harmonic sense, but with an important rhythmic role. For example, off-beat harmonic suggestions... This is quite different from playing lyrical solo pieces.


What are some best practices for debugging Qt signals and slots?

Question: Debugging signals and slots can be hard, because the debugger does not jump to the slots of a signal when it is emitted. What are some best practices for debugging Qt signals and slots?
In particular

How do I make sure connections are set up successfully?
When should I use signals and slots, when should I avoid them?
What are the most efficient debugging techniques from your experience?
Answer: There was a blog post written a while back called 20 ways to debug Qt signals and slots
It addresses I think #1 and #3 of your questions.
For #2, I don't think there is really a hard and fast reason to use or not use signals/slots, as they are a pretty core concept of the GUI framework. Signals are a perfect way to decouple the knowledge of one component to another, allowing you to design reusable widgets that simply declare state changes or notifications. It is also a very good way to communicate GUI changes from non-GUI thread loops, by emitting a signal that the main thread can see.
There might be times where what you really want instead of a signal/slot is to use events, such as when a parent widget should become the event filter for a number of child widgets. The children still do not need to know about the parent, and the parent gets a more direct event as opposed to a signal connection.
On the same topic of events, there are times where what you really want is a bubbling up of an event from child -> parent -> grandparent -> etc. Signals would make less sense here because they are not meant as a way to determine whether the proposed event should result in an action (they could be used this way obviously). Events allow you to check the current state, decide whether this widget should do anything, or otherwise bubble them up the chain for someone else to inspect.
There is a really fantastic answer about The Difference Between Signals/Slots and Events. Here is a good snippet:

You "handle" events
You "get notified of" signal emissions

What I like about that quote is that it describes the different need case. If you need to handle an action in a widget, then you probable want an event. If you want to be notified of things happening, then you probably want a signal.
Comment: The link you provided is rather underwhelming in terms of actual debugging techniques. The gist is basically: *"Avoid writing bugs, and here are 20 things that can go wrong"*. No mention of tools or techniques to actually debug issues. When you get a crash dump, you are confronted with an insanely deep callstack, lots of `qt_static_metacall` invocations, no easy way to decipher the emitted signal, and simply no way of knowing, where any particular signal-slot-connection was set up.
Answer: In addition to what have been said, here are additional tricks.
If you use QTest for your unit tests, then you can pass -vs argument to the executable and all signals will be shown in the console.
I looked at how QTest works, and it registers callbacks that is triggered when signal and slots are executed using QSignalDumper class. However, this API is not exported and might break any time. Here is how I was able to hook on all signals and slots on Linux with Qt 5.10 using GCC.
// QSignalSpyCallbackSet is defined in qt5/qtbase/src/corelib/kernel/qobject_p.h

struct QSignalSpyCallbackSet
{
    typedef void (*BeginCallback)(QObject *caller, int signal_or_method_index, void **argv);
    typedef void (*EndCallback)(QObject *caller, int signal_or_method_index);
    BeginCallback signal_begin_callback,
                    slot_begin_callback;
    EndCallback signal_end_callback,
                slot_end_callback;
};
typedef void (*register_spy_callbacks)(const QSignalSpyCallbackSet &callback_set);

static void showObject(QObject *caller, int signal_index, const QString &msg)
{
   const QMetaObject *metaObject = caller->metaObject();
   QMetaMethod member = metaObject->method(signal_index);
   qDebug() << msg << metaObject->className() << qPrintable(member.name());
}

static void onSignalBegin(QObject *caller, int signal_index, void **argv)
{
   showObject(caller, signal_index, "onSignalBegin");
}

static void onSlotBegin(QObject *caller, int signal_index, void **argv)
{
   showObject(caller, signal_index, "onSlotBegin");
}

int main(int argc, char *argv[])
{
   static QSignalSpyCallbackSet set = { onSignalBegin, onSlotBegin, 0, 0 };
   QLibrary qtcore("libQt5Core");
   register_spy_callbacks reg = (register_spy_callbacks)qtcore.resolve("_Z32qt_register_signal_spy_callbacksRK21QSignalSpyCallbackSet");

   if (reg) {
      reg(set);
   }
   ...
}

I believe that Qt should expose that API, because we could use it for so many things beyond debugging, such as monitoring the time spent in a slot, get statistics, etc.
Answer:
How do I make sure connections are set up successfully?

You will see warnings in the console output from your application for each failed connection.

When should I use signals and slots, when should I avoid them?

In my opinion, it's fine to use them any time you want to maintain separation of concerns in your class design. Your class can emit a signal that may or may not be answered by another class (or classes) completely unknown to your class. This keeps your coupling down.

What are the most efficient debugging techniques from your experience?

I can't really add anything more than what is said on this blog post. 20 ways to debug Qt signals and slots
Answer: Regarding #1, I'll just add another piece of information that I didn't see mentioned above or in the referenced blog post.
From the documentation on QObject::connect():

Creates a connection of the given type from the signal in the sender object to the method in the receiver object. Returns true if the connection succeeds; otherwise returns false.

I prefer asserting the return value of my connection to make sure the connection succeeded, especially because not all Qt programs will have console output. This also leads to more easily maintainable code, as it will catch changes made at a later date to either the signal or the slot, and force the programmer who made the changes to update the connections as well.
Comment: I realize this is an ancient post, but just in case it gets used recently.The documentation actually states that connect returns "handle" . I believe checking for validity  of the return - whatever it is - is more generic.
Comment: @JanHus The documentation I quoted was the Qt 4.8 version. In Qt5 a handle is returned, but even more importantly a new functor-based connection was added that allows for compile time checking, which is safer (see https://doc.qt.io/qt-5/signalsandslots-syntaxes.html).
Comment: I have been using QtDesigner GUI ( "edit slots/signals;" ) by moving the mouse around. It is limited and "builds" a funky GUI "string" .Since there is no code to check it probably does the older "connect" form  anyway. Nice feature but hardly user friendly.


Can Rules be used to disable the logo variable on some pages?

Question: I have a change in Drupal 6 that I would like to make quickly without doing another SVN roll (until I get a more permanent solution in place) and I would like to create a triggered rule that will null the $logo variable that is being sent to the theme before it gets there.
I know how to tell it to identify the page in question and control it based on role. However, I am having trouble figuring out what PHP code to use in the custom PHP code section. Partly because I just don't know what variables are available nor at what point in the code flow I am sitting in (which is important for this).
Does anyone have any ideas or suggestions?
Answer: I don't think that I'm on the wrong way (correct me if) but I think you should do a hook_preprocess_page(&$vars) in your theme's template.php and unset the $var['logo'] when you meet your condition.
I wouldn't do that with Rules, I don't even know if it's possible.


Is P(A . B') = P(A) . P(B')?

Question: Is this identity $ P(A. B^c) = P(A).P(B^c)$ correct?
My attempt to prove this is as follows:
$$ RHS = P(A). P(B^c) \\
= P(A) . (1 - P(B)) \\
=P(A) - P(A).P(B) \\
=P(A) - P(A \cap B)\\
=P(A \cap B^c) \\
=LHS
$$
Also, can this be extended as such:
$ P(A^c \cap B^c) = P(A^c) . P(B^c)$ ?
My attempt to prove:
$$ P((A \cup B)^c) = P(A^c). P(B^c) \\
= P((A^c \cap B) \cup (A^c \cap B^c)) \cup P((B^c \cap A) \cup (B^c \cap A^c)) \\
=P(A^c \cap B^c) \\
$$
Are these identities correct? I'd also appreciate any help on the proofs.
Comment: Yes, assuming that A and B are independent events. That's really really important. The fact that you haven't mentioned this at all makes me worry that you have deeply misunderstood something
Comment: No, the identity is not correct in general.  Recall that $\Pr(X\cap Y)=\Pr(X)\Pr(Y)$ is true **if and only if**  $X$ and $Y$ are independent events.
Comment: For $A$ and $B$ independent, yes, $\Pr(A\cap B^c)$ will equal $\Pr(A)\Pr(B^c)$ and it can be shown as you did.
Comment: As for your proof of the second half... that was highly unnecessary.  Just call $B^c$ something else... like $C$, from which you are asking if $\Pr(A^c\cap C)=\Pr(A^c)\Pr(C)$ which follows immediately from the earlier proof.
Comment: What are the premises (if any) regarding the events' independence?
Answer: Only valid for independent events. So itself the identity is wrong without explaination of independency of evenrs.

Is P(A . B') = P(A) . P(B')?


Finger positions to play power chords

Question: I really struggle to get my left hand's fingers in the right shape when I play a power chord.
On the picture below I try to put my first finger on the second fret and my third finger on the fourth fret :

You can see that it's very far from the "ideal" shape :

But I just can't move my fingers in that position. My third finger is too far from the fret and thus it doesn't sound very good.
Any advice or tips on how I could fix that ?
Comment: Your hand/wrist is in a position that's suitable for playing open chords such as C or Am, but bad for playing barre chords or power chords. In the "correct" example picture, the player's thumb is completely _behind_ the neck and probably pointing up. I've seen beginner guitarists do the same mistake - they first learn open chord shapes, and then they try to do barre chords with the same wrist shape, which is impossible as you've found out.
Comment: Moving your elbow away from your body will sort out the problem.
Comment: Use 3rd *and* 4th fingers on the higher fret..
Comment: +1 for the question! It was well prepared, with good pictures and everything. People upvote too little around here.
Comment: Hi, friend. I had the same question 3 years ago: https://music.stackexchange.com/questions/52788/i-cannot-spread-my-fingers-easily-am-i-anatomically-disadvantaged-for-playing-t Hope it helps. Don't give up. I did it and you can do it too!
Answer: I agree with Tim. In addition when you are playing guitar your thumb must be behind the neck.This relaxes muscles and allows you to reach upper strings more comfortably.
It might be diffcult at the beginningg but If you practice this way you will be more comfortable when playing other difficult chords/notes.
Also here are some examples
This one might help too
What you need is to strenghten your finger muscles. You can do this with more practice. I suggest this one It will strenghten your finger and elbow muscles so that you can put your fingers peripendicular to guitars keyboard which will eventually solve your problem. Do not get exhausted by practice. 20 minutes everyday will solve your problem eventually! This is a very common problem for beginngers.
Also I suggest you to follow a method book. Those tutorials on youtube are not graded well. (I only suggest Justin guitar on youtube that one is graded very well from beginning to advanced,I believe!) So to track your progress it is better to follow a method book.
Keep practicing!
Comment: I often find, particularly during soloing, that my thumb is actually on the same side of the neck as my fingers..! Good for certain vibrati. Or is it vibratoes. Or vibratos...
Comment: I wouldn't say that you _always_ have to play with the thumb behind the neck like a classical guitarist ... the OP's grip does have its uses. :) But good answer, +1
Comment: Yes you are right rock and country players use thumb to mute upper strings but I tried to be more general. Since he is a beginner and possibly will not do any muting :) Thanks for upvote.
Answer: Yes, I agree with what others have said above: the thumb is the culprit!!! Might try putting it near the center of the back of the neck, and in-between your two fingers, which should allow you to get that ring finger up to the fret, and stay on the fingertips too. And most importantly, like Nabla said: keep practicing! This will get that finger strength up to bottle-opener status.
Answer: A couple of ideas. On a well set-up guitar, you don't actually need to use your thumb at all - by using your whole arm (l.h.) to pull in, and your right arm to pull in, in the opposite direction (your body is the fulcrum), there's enough leverage and strength to take your thumb off. In fact, I'd say the majority of players squeeze too hard.
Using your thumb - the higher up the back of the neck it goes, the less pressure your fingers can exert on the strings. So move the thumb down, towards the floor, and place it lower than the half-way point, but also closer to the head of the guitar.
We're all built slightly differently, so you will have to experiment to findd an optimum position - which will change subtly depending on what chord shape you're using. And also how far up or down the neck you're playing.And where you wear your guitar. The lower it's slung, the more problems you'll have!
Answer: It seems to me that you left-hand thumb curls too heavily over the finger-board. Making it so that your finger curl too heavily inwards. Try keeping your left hand thumb reasonably parallel with the width of the finger-board, giving your fretting fingers more freedom to move like you want them to.
Whether you use 2nd, 3rd or pinky for the power-chord is largely a personal preference. What I would say is that using the less intelligent-fretting-fingers for the power chord is a really useful dexterity exercise. If you do use the dumber fingers you may find it easier to transition into John Frusciante octave strumming effect.

Finger positions to play power chords


Hide a particular table row using javascript inline

Question: I have the following html that I cannot modify. (It is being auto-generated)

      UserName
      Bob

      Password
      Fred

This would display:
UserName  Bob
Password  Fred

However, I can insert code inside the td area.  I would like to hide the parent row using javascript or css.
Example
For example, if I wanted to hide the second row I can insert javascript:

      UserName
      Bob

      Password
      Fred

And then it should just display
UserName  Bob

Notes

The function document.parentrow.hide(); does not work but it is just to show an example of what I am looking for. I would like a function
that hides the current row associated with that td.

I cannot add custom class or id to the tr tags since I have no control over that portion of the html.

I did take a look at the provided link How may I reference the script tag but it is just a general topic.  It does not have the answer to my question regarding table rows.  It does not relate to accessing rows neither.  The link is for accessing loaded javascript files.
Comment: Why not include a css file which hides it. You can dynamically add a css file via javascript
Comment: @SteveTomlin You still have the problem of how to specify which row to hide in CSS. There's no class or ID on the row.
Comment: See the linked question to get a reference to the current script tag. Then use `.closest("tr")` to get the parent row.
Comment: Barmar you closed my question but the link you reference does not answer the question.  It is only a general information link.
Answer:

const secondRow = document.querySelector('tr:nth-child(2)')
secondRow.hidden = true

      UserName
      Bob

      Password
      Fred

Comment: I think it's supposed to be dynamic -- they can add the script to any row in the table and it should hide that row. Hard-coding the row number doesn't seem right.
Comment: Thank you Konrad that is a great answer!


What are the Fundamentals of Applied Statistics?

Question: Would the knowledge of the following topics suffice for a crash course on fundamentals of applied statistics?

Basics of Probability
Descriptive Statistics
Estimation Theory
Hypothesis Testing

The targeted audience are those with little or no exposure to statistics. The course should bring about a clear understanding of what is statistics and its basic outline. It should also serve as a start for those who are interested in the subject but don't know where to begin.
The "applied" part comes with the implementation of the above theories in practical examples and exercises.
Comment: Who's judging what "suffices" and on what criteria? I'd say that no one is well prepared for applied statistics without knowing more about data production and data management, but there's only so much you can put in one course without strain or complaint. The premise of a "crash course" is arguable itself: applied statistics is a long slow art.
Comment: Hard to know for sure what you intend to cover under each of those headings, but your list reads like an introduction to *theoretical* Statistics - as a pre-requisite for intermediate applied Statistics perhaps.
Comment: I am concerned about the potential for this thread to devolve into a list of personal opinions, but at the same time I am optimistic that this community can contribute some well-reasoned informed replies. Instead of closing the thread, I have provisionally made it CW (in the same spirit as other threads that have no unique best answer but can be useful to readers). Ébe Isaac, some elaboration in the post of what you mean by "applied statistics" would be welcome. As @Scortchi has suggested, most of your topics don't look applied at all.
Comment: You have to teach said course?
Comment: Yes, @Repmat, but the syllabus is on my own accord.
Comment: Thanks, @NickCox. I've added the necessary details to the question.
Comment: It might be instructive to compare your list with the syllabus for the Royal Statistical Society's [Ordinary Certificate](http://www.rss.org.uk/RSS/pro_dev/Examinations_sub/key_information/Key_information.aspx). *Half* the material is "Collection and Compilation of Data" (sampling methods, surveys, bias, experimental vs observational studies, use of computers). The other half is "Analysis & presentation of data" (frequency & contingency tables, descriptive statistics, various graphical methods, outlier identification, basic probability, linear regression, rank correlation, ...
Comment: , moving averages & seasonality in time series), & includes neither hypothesis testing nor a formal account of parameter estimation. Clearly much of this would be too basic for people already educated in the natural or social sciences, but it's undoubtedly useful stuff for immediate practical application. So what have your audience been exposed to rather than Statistics, & what *skills*, if any, do you want them to develop? Also, what's a "crash course" in terms of time spent studying?
Comment: @whuber: I've included a brief description on the "applied" part. Kindly notify of any necessary correction.
Comment: @Scortchi: Thanks for the info. I could elaborate on the syllabus on the post, but it would be giving too much away at the start. But for now, I could say that the Probability part includes salient probability distributions, estimation covers both max. likelihood and method of moments, hypothesis testing includes tests of mean, variances, independent and goodness of fit.
Comment: I don't think there need to be fundamentals of applied statistics. There's got to be fundamentals of statistics.
Comment: @Aksakal Good point. I'll take it into account.
Answer: If these are subject-matter-experts I would spend more time discussing:

How to ask the right question in a way that it can be answered.
How to collect data so that you can answer the question.
How to select a statistical procedure that can answer your question.
What the result of the statistical analysis means and how to know if it is of any practical value.
When to call in professional statisticians and how to effectively work with them.
Answer:
The targeted audience are those with little or no exposure to statistics.

My favourite audience!

It should also serve as a start for those who are interested in the subject but don't know where to begin.

Your choice of textbook is going to be crucial. My strategy is to have one very short stats textbook (e.g. Urdan, Stats in Plain English), and to do everything else through code and tutorials.

The "applied" part comes with the implementation of the above theories in practical examples and exercises.

This is the crucial part. Make the examples relevant: no synthetic data, and of the right dimensions for your audience (don't teach flower or airplane data to would-be survey analysts).

Basics of Probability
Descriptive Statistics
Estimation Theory
Hypothesis Testing

That's one way to put it. I would stress:

Data. What it is (observations, variables, samples), how is it produced.

Data collection, sample design, measurement issues.
Question(s) -> Data -> Question(s) -> Data -> etc.

Distributions. How do we describe one variable, several variables.

Your descriptive stats are here.
Tons of EDA (exploratory data analysis) / data visualization always helps.
Concentration indices, quantiles, ECDFs. Invaluable.

Estimation. When we have $\bar x$, how do we estimate $\mu$?

A bit of probability and estimation theory here.

Inference. When we observe an association, how do we measure its robustness?

Hypothesis testing happens here. More probability here.
Downplay $p$-values, emphasize standard errors.
If you have time, models.

My strategy:
Anticipate that students will forget (3) and (4). That's alright, the next course will take it up again. But (1) and (2), your students need to be familiar with the jargon, and should be critical quantifiers, who know that data are dirty, that sampling is complex, that "raw data" is an oxymoron, etc.
General philosophy:

Source.
Comment: How I hate this "tidy" buzz word after taking a data science course. I'd never use it in a professional setting
Comment: Is "tidy" just not in the workflow, or the jargon is different? (If I understand correctly, in my area this would be something like "QC and standardize", the latter w.r.t. format)
Comment: "Tidy" means easily manipulable in R (i.e. rectangular). You can forget about it if your course/area uses something else.
Comment: There is no reason the "tidy" principles would not be useful in other contexts than R.
Comment: "Tidy" turns out to be exactly the layout of data I've regarded as standard for just about 50 years....


How to ~ print('You Fail') ~ CORRECTLY in secret number guess code. Im stuck

Question: Disclaimer I am a noob. Just started learning python. I know no computer languages, I just thought it would be nice to change my career for me and my family. I'm learning from online video on youtube. I think he is good... I still don't understand/know what he is talking about(terminology and stuff) but im trying to follow along and hoping I will understand wth he is talking about after hearing him say the words over and over again....
The problem is, if I win, it still says that I lose... If I lose it doesn't say that I WON... so what do I have to do differently?
I tried … if guess =/= secret_number: but apparently that / doesn't mean not equal to...
My code -
secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
    guess = int(input('Guess: '))
    guess_count += 1
    if guess == secret_number:
            print('You Won!')
    else:
            print('You Lose!')

Comment: Please [edit] and fix your indentation.
Comment: Does this answer your question? [Is there a "not equal" operator in Python?](https://stackoverflow.com/questions/11060506/is-there-a-not-equal-operator-in-python)
Comment: You really do need to make sure the indentation shown here looks exactly as you have it in your actual code. If you've done it properly, then the code should work and you need to be more clear about what's happening. I can think of exactly one way you might have done it improperly, though.
Comment: hi sorry it didn't transfer properly. but the code is working. the problem which I didn't know till now is that when you guess correctly the 1st time it just says you win... which is good... but if you guess correctly on the third try it says you win AND you lose
Comment: ok I found it out guys... got to add a break after you won line. Thank you for your input!!!
Comment: also thanks I found out "not equal" can also be showed as !=
Answer: secret_number = 9
guess_count = 0
guess_limit = 3
while guess_count < guess_limit:
    guess = int(input('Guess: '))
    guess_count += 1
    if guess == secret_number:
        print('You Won!')
        break
else:
    print('You Lose!')

your code is right. I guess your problem is the indentation of if statement. you need to have if in your while loop so every time you get a number you can check if it's right or not
Comment: hi thanks for the response. So I guess it didn't transfer properly. I had trouble inputing the code properly into the stackoverflow website. I guess I didn't clarify enough... but at the time I didn't know…. If you win by guessing 9 the first time it says You won... but if you wait till the 3rd try to guess correctly it will say you won... AND you lose … so I guess I didn't explain the problem correctly but I had assumed that You lose displayed after every win... didn't know it was only if you win on the 3rd attempt
Comment: So did my code solve your problem or you still need to change it?
Answer: secret_number = 9
guess_count = 0
guess_limit = 3
status = False
while guess_count < guess_limit:
    guess = int(input('Guess: '))
    guess_count += 1
    if guess == secret_number:
        print('You Won!')
        status = True
        break
if status == False:
    print('You Lose!')

Comment: I didn't see you posted how to fix it... I didn't know about adding break... but I found the answer thanks for the fast response !


How to build VS 2015 solution with projects which import targets and props from nuget packages using msbuild 14?

Question: The scenario
You add a nuget package, which in turn injects <Import .../> statement into your csproj file which references a targets or props file from the package itself.
This works fine when building the code in Visual Studio, but fails miserably when building the same solution with msbuild.
The root cause
There are several. First, the logic to restore the packages is executed by the VS itself outside of the build proper. We can solve it by importing Nuget.targets which would run the RestorePackage target before the build. Check.
But the second problem is more serious. The Import statements importing targets/props from the packages can only be resolved after the packages are restored. Meaning restoring the packages cannot be part of the build. It must happen before the msbuild is given the solution to build. Yes, Visual Studio does it already, but I do not use Visual Studio on my Gated Check-In or CI server. I need it to work with msbuild.
What one can do?
As far as I understand, I need to be able to run the same logic VS does only on the command line. I.e. identify the packages and restore them before running msbuild. But devil is in details. Cannot be I am the first one to face this problem.
How do you do it?
Answer: Found the answer in this blog post - http://sedodream.com/2013/06/06/HowToSimplifyShippingBuildUpdatesInANuGetPackage.aspx
Following this blog I have created before.MySolutionName.sln.targets file with the following content:
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="Restore">
  <Target Name="Restore" BeforeTargets="Build">
    <Exec Command=".nuget\nuget.exe restore $(MSBuildProjectName)" LogStandardErrorAsError="true" />
  </Target>
</Project>

Now all the packages in the solution are restored before the build.
Thank you, Sayed Ibrahim Hashimi.