问:
XPath Query to find supplier name through an XML table
I am trying to find out the cities where there is a supplier with the name of Herman. We are using XPath through Microsoft SQL Server Management Studio.

I am not a CIS major and I have no idea where to start. So that's why I'm asking for help...

I have the following table created:

```<code>CREATE TABLE Tb_Supplier(
XMLColumn XML)
GO

INSERT Tb_Supplier VALUES(
    '<SuppliersList>
      <Supplier name="Joe">
        <City>Paris</City>
        <Product name="Airplane"/>
        <Product name="Milk"/>
        <Product name="TV"/>
        <Product name="Orange"/>
     </Supplier>
      <Supplier name="Herman">
        <City>Chicago</City>
        <Product name="Orange"/>
     </Supplier>
     <Supplier name="Bernstein">
        <City>Madison</City>
        <Product name="Truck"/>
        <Product name="TV"/>
      </Supplier>
     <Supplier name="Hunter">
        <City>Wausau</City>
      </Supplier>
      <Supplier name="Mayer">
        <City>Madison</City>
      </Supplier>
      <Supplier name="Rosenfeld">
        <City>Chicago</City>
        <Product name="Computer"/>
        <Product name="Book"/>
        <Product name="Truck"/>
      </Supplier>
    </SuppliersList>');
</code>```

The output is supposed to show:

```<code><City>Chicago</City>
</code>```

I got the it to work by the following:

```<code>SELECT XMLColumn.query('/SuppliersList/Supplier[@name="Herman"]/City')
FROM Tb_Suppliers
</code>```

I am kind of getting the grasp of things.
Currently I am having trouble how to find out the following:
List the products are TV's, and are offered in Madison.
Obviously the output will be  since it is looking for TV.

I have this so far, I don't know what I'm doing wrong as this makes the most sense to me.

```<code>SELECT XMLColumn.query('/SuppliersList/Supplier/Product[@name="TV"]/../City[@name="Madison"]/../Product')
FROM Tb_Suppliers
</code>```

答:
It depends whether you know, that there is exactly one "Herman" in your list. Then it's a pure call on .value() with the appropriate XPath:

```<code>SELECT XMLColumn.value(N'(/SuppliersList/Supplier[@name="Herman"]/City/text())[1]',N'nvarchar(max)') AS Herman_City
FROM Tb_Supplier
</code>```

If you expect more than one, you need .nodes() to get a derived table and value() on the relative path (below the node coming from .nodes()):

```<code>SELECT AllHerman.cities.value(N'(City/text())[1]',N'nvarchar(max)') AS Herman_City
FROM Tb_Supplier
CROSS APPLY XMLColumn.nodes(N'/SuppliersList/Supplier[@name="Herman"]') AS AllHerman(cities)
</code>```

Body:
I am trying to find out the cities where there is a supplier with the name of Herman. We are using XPath through Microsoft SQL Server Management Studio.

I am not a CIS major and I have no idea where to start. So that's why I'm asking for help...

I have the following table created:

CREATE TABLE Tb_Supplier(
XMLColumn XML)
GO

INSERT Tb_Supplier VALUES(
    '<SuppliersList>
      <Supplier name="Joe">
        <City>Paris</City>
        <Product name="Airplane"/>
        <Product name="Milk"/>
        <Product name="TV"/>
        <Product name="Orange"/>
     </Supplier>
      <Supplier name="Herman">
        <City>Chicago</City>
        <Product name="Orange"/>
     </Supplier>
     <Supplier name="Bernstein">
        <City>Madison</City>
        <Product name="Truck"/>
        <Product name="TV"/>
      </Supplier>
     <Supplier name="Hunter">
        <City>Wausau</City>
      </Supplier>
      <Supplier name="Mayer">
        <City>Madison</City>
      </Supplier>
      <Supplier name="Rosenfeld">
        <City>Chicago</City>
        <Product name="Computer"/>
        <Product name="Book"/>
        <Product name="Truck"/>
      </Supplier>
    </SuppliersList>');

The output is supposed to show:

<City>Chicago</City>

I got the it to work by the following:

SELECT XMLColumn.query('/SuppliersList/Supplier[@name="Herman"]/City')
FROM Tb_Suppliers

I am kind of getting the grasp of things.
Currently I am having trouble how to find out the following:
List the products are TV's, and are offered in Madison.
Obviously the output will be  since it is looking for TV.

I have this so far, I don't know what I'm doing wrong as this makes the most sense to me.

SELECT XMLColumn.query('/SuppliersList/Supplier/Product[@name="TV"]/../City[@name="Madison"]/../Product')
FROM Tb_Suppliers

Body:
It depends whether you know, that there is exactly one "Herman" in your list. Then it's a pure call on .value() with the appropriate XPath:

SELECT XMLColumn.value(N'(/SuppliersList/Supplier[@name="Herman"]/City/text())[1]',N'nvarchar(max)') AS Herman_City
FROM Tb_Supplier

If you expect more than one, you need .nodes() to get a derived table and value() on the relative path (below the node coming from .nodes()):

SELECT AllHerman.cities.value(N'(City/text())[1]',N'nvarchar(max)') AS Herman_City
FROM Tb_Supplier
CROSS APPLY XMLColumn.nodes(N'/SuppliersList/Supplier[@name="Herman"]') AS AllHerman(cities)


来源: stackexchange

问:
Remove VS2010 references to deleted files in web project
I went behind VS2010's back and deleted some images from an image folder that's referenced by a web project as Content.  In the solution navigator, these files now show up with the yellow warning icon that the file cannot be found.  Refreshing the folder has no effect.  Is there a way to tell VS2010 to automatically synch a folder?  The VS Website project does this by default. </p>

答:
I made a very simple console app for this:

```<code>using System;
using System.IO;
using System.Collections.Generic;

namespace CleanProject
{
    class Program
    {
        static void Main(string[] args)
        {
            var newFile = new List<string>();
            if (args.Length == 0)
            {
                Console.WriteLine("Please specify the project full path as an argument");
                return;
            }

            var projFile = args[0];
            if (!File.Exists(projFile))
            {
                Console.WriteLine("The specified project file does not exist: {0}", projFile);
                return;
            }

            if (!projFile.ToLowerInvariant().EndsWith(".csproj"))
            {
                Console.WriteLine("The specified does not seem to be a project file: {0}", projFile);
                return;
            }

            Console.WriteLine("Started removing missing files from project:", projFile);

            var newProjFile = Path.Combine(Path.GetDirectoryName(projFile), Path.GetFileNameWithoutExtension(projFile) + ".Clean.csproj");
            var lines = File.ReadAllLines(projFile);
            var projectPath = Path.GetDirectoryName(projFile);
            for(var i = 0; i < lines.Length; i++)
            {
                var line = lines[i];
                if (!line.Contains("<Content Include=\"") && !line.Contains("<None Include=\""))
                {
                    newFile.Add(line);
                }
                else
                {
                    var start = line.IndexOf("Include=\"") + "Include=\"".Length;
                    var end = line.LastIndexOf("\"");
                    var path = line.Substring(start, end - start);
                    if (File.Exists(Path.Combine(projectPath, path)))
                    {
                        newFile.Add(line);
                    }
                    else
                    {
                        if (!line.EndsWith("/>")) // I'm assuming it's only one line inside the tag
                            i += 2;
                    }
                }
            }
            File.WriteAllLines(newProjFile, newFile);

            Console.WriteLine("Finished removing missing files from project.");
            Console.WriteLine("Cleaned project file: {0}", newProjFile);
        }
    }
}
</code>```

https://github.com/woodp/remove-missing-project-files

ContentLicense: CC BY-SA 3.0

Body:
I made a very simple console app for this:

using System;
using System.IO;
using System.Collections.Generic;

namespace CleanProject
{
    class Program
    {
        static void Main(string[] args)
        {
            var newFile = new List<string>();
            if (args.Length == 0)
            {
                Console.WriteLine("Please specify the project full path as an argument");
                return;
            }

            var projFile = args[0];
            if (!File.Exists(projFile))
            {
                Console.WriteLine("The specified project file does not exist: {0}", projFile);
                return;
            }

            if (!projFile.ToLowerInvariant().EndsWith(".csproj"))
            {
                Console.WriteLine("The specified does not seem to be a project file: {0}", projFile);
                return;
            }

            Console.WriteLine("Started removing missing files from project:", projFile);

            var newProjFile = Path.Combine(Path.GetDirectoryName(projFile), Path.GetFileNameWithoutExtension(projFile) + ".Clean.csproj");
            var lines = File.ReadAllLines(projFile);
            var projectPath = Path.GetDirectoryName(projFile);
            for(var i = 0; i < lines.Length; i++)
            {
                var line = lines[i];
                if (!line.Contains("<Content Include=\"") && !line.Contains("<None Include=\""))
                {
                    newFile.Add(line);
                }
                else
                {
                    var start = line.IndexOf("Include=\"") + "Include=\"".Length;
                    var end = line.LastIndexOf("\"");
                    var path = line.Substring(start, end - start);
                    if (File.Exists(Path.Combine(projectPath, path)))
                    {
                        newFile.Add(line);
                    }
                    else
                    {
                        if (!line.EndsWith("/>")) // I'm assuming it's only one line inside the tag
                            i += 2;
                    }
                }
            }
            File.WriteAllLines(newProjFile, newFile);

            Console.WriteLine("Finished removing missing files from project.");
            Console.WriteLine("Cleaned project file: {0}", newProjFile);
        }
    }
}

https://github.com/woodp/remove-missing-project-files


问:
numpy stacking matrices together of same sub dimension
Suppose I have a matrix

```<code>mat = np.empty((0, 3, 5))
</code>```

and I have a another matrix of shape (3, 5), how can I add that matrix to mat[0]?

I've tried different combinations of stack, vstack, hstack, concatenate and insert and they don't seem to work

答:
I understand that you want to insert a 3x5 matrix to an empty array. Then np.append can do that. Just specify the right axis.

```<code>import numpy as np

mat = np.empty((0,3,5))

mat3x5 = np.matrix('1,1,1,1,2;3,1,2,3,1;2,3,1,2,3')

mat3x5 = np.expand_dims(mat3x5, 0)

result = np.append(mat, mat3x5, axis=0)
</code>```

Body:
Suppose I have a matrix

mat = np.empty((0, 3, 5))

and I have a another matrix of shape (3, 5), how can I add that matrix to mat[0]?

I've tried different combinations of stack, vstack, hstack, concatenate and insert and they don't seem to work

Body:
I understand that you want to insert a 3x5 matrix to an empty array. Then np.append can do that. Just specify the right axis.

import numpy as np

mat = np.empty((0,3,5))

mat3x5 = np.matrix('1,1,1,1,2;3,1,2,3,1;2,3,1,2,3')

mat3x5 = np.expand_dims(mat3x5, 0)

result = np.append(mat, mat3x5, axis=0)


问:
Java: for each within for each?
so I was wondering if it's correct to make two for each in a row. In World I have an ArrayList<House> and in each House there's an ArrayList<Furniture>. I want to compare all furnitures in all houses with each other (said comparing method is done). Can I make:

```<code>  for (House h: _housesWorld)
      for (House h2: _housesWorld)
          i = compare(h, h2);
</code>```

Or if I cannot make a for each within a for each, what can I do to compare all the houses with each other?

答:
if you want to compare elements of the ArrayList you can use nested for loop</p>

```<code>for(int i=0; i<_houseWorld.length;i++)
  for(int j=1; j<_houseWorld.length;j++)
    {
      flag=compare(_houseWorld.get(i),_houseWorld.get(j));

    }
 }
</code>```

Title: Java: for each within for each?

Body:
so I was wondering if it's correct to make two for each in a row. In World I have an ArrayList<House> and in each House there's an ArrayList<Furniture>. I want to compare all furnitures in all houses with each other (said comparing method is done). Can I make:

  for (House h: _housesWorld)
      for (House h2: _housesWorld)
          i = compare(h, h2);

Or if I cannot make a for each within a for each, what can I do to compare all the houses with each other?

Body:
if you want to compare elements of the ArrayList you can use nested for loop

for(int i=0; i<_houseWorld.length;i++)
  for(int j=1; j<_houseWorld.length;j++)
    {
      flag=compare(_houseWorld.get(i),_houseWorld.get(j));

    }
 }


问:
Is train/test-Split in unsupervised learning necessary/useful?
In supervised learning I have the typical train/test split to learn the algorithm, e.g. Regression or Classification. Regarding unsupervised learning, my question is: Is train/test split necessary and useful? If yes, why?</p>

答:
Well This Depend on the Problem, the form of dataset and Class of Unsupervised algorithm used to solve the particular problem.

Roughly:-
Dimensionality reduction techniques are usually tested by calculating the error in reconstruction  so there we can use k-fold cross-validation procedure

But on clustering algorithm, I would suggest doing statistical testing in order to test performance. There is also little time-consuming trick which splitting dataset and hand label the test set  with meaningfull classes and cross validate

In any case unsupervised algorithm is used on supervised data then it always good cross-validate

overall:- It is not necessary to split data in the train-test set but if we can do it it is always better

Here is article which explains how cross-validation is a good tool for unsupervised learning
http://udini.proquest.com/view/cross-validation-for-unsupervised-pqid:1904931481/ and the full text is available here http://arxiv.org/pdf/0909.3052.pdf

https:///www.researchgate.net/post/Which_are_the_methods_to_validate_an_unsupervised_machine_learning_algorithm


问:
Group_concat with Query builder laravel

Hello! , i have an issue with an sql Call on laravel 5.5 using query builder. when i do this

```<code>    $result = DB::table(self::$TABLA_COMPONENTE)
        ->join(self::$TABLA_ARCHIVOS ,self::$TABLA_COMPONENTE.'.com_id','=',self::$TABLA_ARCHIVOS.'.com_id')
        ->select(self::$TABLA_COMPONENTE.'.*',DB::raw('group_concat('.self::$TABLA_ARCHIVOS.'.ar_url) as com_archivos'))
        ->where(self::$TABLA_COMPONENTE.'.com_id',$id)->first();
</code>```

i get the following error

SQLSTATE[42000]: Syntax error or access violation: 1140 Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause (SQL: select componente.*, group_concat(archivos.ar_url) as com_archivos from componente inner join archivos on componente.com_id = archivos.com_id where componente.com_id = 2 limit 1)

this is the raw sql i get by using ->toSql()

```<code>This is the sql with ->toSql()

"select `componente`.*, group_concat(archivos.ar_url) as com_archivos from `componente` inner join `archivos` on `componente`.`com_id` = `archivos`.`com_id` where `componente`.`com_id` = ?
</code>```

And it works fine on Phpmyadmin.

i also tried using Group by with no luck.

If you could help me with a solution I would be very grateful!

答:
This is actually mysql problem not laravel problem. Try add

```<code>->groupBy(self::$TABLA_COMPONENTE . '.id')
</code>```

to you query.

EDITED: something like this one :

```<code>$result = DB::table(self::$TABLA_COMPONENTE)
    ->join(self::$TABLA_ARCHIVOS ,self::$TABLA_COMPONENTE.'.com_id','=',self::$TABLA_ARCHIVOS.'.com_id')
    ->select(self::$TABLA_COMPONENTE.'.*',DB::raw('group_concat('.self::$TABLA_ARCHIVOS.'.ar_url) as com_archivos'))
    ->groupBy(self::$TABLA_COMPONENTE . '.id')
    ->where(self::$TABLA_COMPONENTE.'.com_id',$id)->first();
</code>```

note : it is not testet

Title: Group_concat with Query builder laravel

Body:
Hello! , i have an issue with an sql Call on laravel 5.5 using query builder. when i do this

    $result = DB::table(self::$TABLA_COMPONENTE)
        ->join(self::$TABLA_ARCHIVOS ,self::$TABLA_COMPONENTE.'.com_id','=',self::$TABLA_ARCHIVOS.'.com_id')
        ->select(self::$TABLA_COMPONENTE.'.*',DB::raw('group_concat('.self::$TABLA_ARCHIVOS.'.ar_url) as com_archivos'))
        ->where(self::$TABLA_COMPONENTE.'.com_id',$id)->first();

i get the following error

SQLSTATE[42000]: Syntax error or access violation: 1140 Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause (SQL: select componente.*, group_concat(archivos.ar_url) as com_archivos from componente inner join archivos on componente.com_id = archivos.com_id where componente.com_id = 2 limit 1)

this is the raw sql i get by using ->toSql()

This is the sql with ->toSql()

"select `componente`.*, group_concat(archivos.ar_url) as com_archivos from `componente` inner join `archivos` on `componente`.`com_id` = `archivos`.`com_id` where `componente`.`com_id` = ?

And it works fine on Phpmyadmin.

i also tried using Group by with no luck.

If you could help me with a solution I would be very grateful!

Body:
This is actually mysql problem not laravel problem. Try add

->groupBy(self::$TABLA_COMPONENTE . '.id')

to you query.

EDITED: something like this one :

$result = DB::table(self::$TABLA_COMPONENTE)
    ->join(self::$TABLA_ARCHIVOS ,self::$TABLA_COMPONENTE.'.com_id','=',self::$TABLA_ARCHIVOS.'.com_id')
    ->select(self::$TABLA_COMPONENTE.'.*',DB::raw('group_concat('.self::$TABLA_ARCHIVOS.'.ar_url) as com_archivos'))
    ->groupBy(self::$TABLA_COMPONENTE . '.id')
    ->where(self::$TABLA_COMPONENTE.'.com_id',$id)->first();

note : it is not testet


问:
How to pull DCM reports with more than 10000 rows into google sheets using apps script?

I'm triyng to get a full report from DCM via Google apps scripts, to insert it in a spreadsheet.
This code works fine, except I cannot pull reports with more than 10K rows.

```<code>function DCMdownload() {

  var reportId = 111825394
  var profileId = 2406185;
  var httpOptions = {'headers': {'Authorization': 'Bearer ' +
ScriptApp.getOAuthToken()}};
  var additionalParameters = {'synchronous': 'true'};

  //corro el reporte e identifico el file ID
  var ReportFile = DoubleClickCampaigns.Reports.run(profileId, reportId,
additionalParameters);
  var ReportFileID = (ReportFile.id);

  //obtengo el csv y lo parseo
  var newReportFile = DoubleClickCampaigns.Files.get(reportId,
ReportFileID);
  if(newReportFile.urls) {var httpOptions = {'headers': {'Authorization':
'Bearer ' + ScriptApp.getOAuthToken()}};
  var csvContent = UrlFetchApp.fetch(newReportFile.urls.apiUrl,
httpOptions).getContentText();
  var csvData = Utilities.parseCsv(csvContent);

  //pego la data en la sheet que esté activa
  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange(1, 1, csvData.length,
csvData[0].length).setValues(csvData);

  //eliminar primeras filas y fila de total
  var lastrow = sheet.getLastRow()
  sheet.deleteRows(1, 11);
  var lastrow = sheet.getLastRow()
  sheet.deleteRows(lastrow);

}
}
</code>```

This works ok with reports with less than 10.000 rows, as you can add them to drive with a button in the DCM interface. If it has more than 10k rows, this option is disabled. It seems that you cannot import it neither in google sheets.

Any work around to solve this?

Cross-posted to SOes

Cómo insertar reportes de DCM de más de 10000 filas en google sheets con apps scripts?

答:
You have this in you code:

```<code>var csvContent = UrlFetchApp.fetch(newReportFile.urls.apiUrl,
httpOptions).getContentText();
</code>```

There is a rate limit set on fetch calls as I remember it is 10 mb per call and 100 mb per day. Workarounds could involve using some kind of limit in your request and then calling again to get the next part of the data. This is okay as long as they don't go above the 100 mb for that day. From my limited experience if the Sheet is going to be 10,000 + rows I would consider using something else for analysis. How about Google's Data Studio? That can pull data from multiple source types?

Body:
I'm triyng to get a full report from DCM via Google apps scripts, to insert it in a spreadsheet.
This code works fine, except I cannot pull reports with more than 10K rows.

function DCMdownload() {

  var reportId = 111825394
  var profileId = 2406185;
  var httpOptions = {'headers': {'Authorization': 'Bearer ' +
ScriptApp.getOAuthToken()}};
  var additionalParameters = {'synchronous': 'true'};

  //corro el reporte e identifico el file ID
  var ReportFile = DoubleClickCampaigns.Reports.run(profileId, reportId,
additionalParameters);
  var ReportFileID = (ReportFile.id);

  //obtengo el csv y lo parseo
  var newReportFile = DoubleClickCampaigns.Files.get(reportId,
ReportFileID);
  if(newReportFile.urls) {var httpOptions = {'headers': {'Authorization':
'Bearer ' + ScriptApp.getOAuthToken()}};
  var csvContent = UrlFetchApp.fetch(newReportFile.urls.apiUrl,
httpOptions).getContentText();
  var csvData = Utilities.parseCsv(csvContent);

  //pego la data en la sheet que esté activa
  var sheet = SpreadsheetApp.getActiveSheet();
  sheet.getRange(1, 1, csvData.length,
csvData[0].length).setValues(csvData);

  //eliminar primeras filas y fila de total
  var lastrow = sheet.getLastRow()
  sheet.deleteRows(1, 11);
  var lastrow = sheet.getLastRow()
  sheet.deleteRows(lastrow);

}
}

This works ok with reports with less than 10.000 rows, as you can add them to drive with a button in the DCM interface. If it has more than 10k rows, this option is disabled. It seems that you cannot import it neither in google sheets.

Any work around to solve this?

Cross-posted to SOes

Cómo insertar reportes de DCM de más de 10000 filas en google sheets con apps scripts?

Body:
You have this in you code:

var csvContent = UrlFetchApp.fetch(newReportFile.urls.apiUrl,
httpOptions).getContentText();

There is a rate limit set on fetch calls as I remember it is 10 mb per call and 100 mb per day. Workarounds could involve using some kind of limit in your request and then calling again to get the next part of the data. This is okay as long as they don't go above the 100 mb for that day. From my limited experience if the Sheet is going to be 10,000 + rows I would consider using something else for analysis. How about Google's Data Studio? That can pull data from multiple source types?


答:
You could do it all in one step, but it's clearer to add a column for the control mean and then take it out later.

```<code>tissue_merge %>%
    group_by(.dots = c("Experiment", "Tissue", "variable")) %>%
    mutate(control_mean = mean(value[Genotype == "miR-15/16 FL"], na.rm = T),
           value_norm = value / control_mean) %>%
    select(-control_mean)
</code>```

Demo Below you can see that, for Experiment 170911 and Tissue Spleen, for each variable, MFI CD127 Foxp3+ CD4+, MFI CD127 Foxp3- CD4+, and MFI CD127 CD127 CD8+, the control_mean is equal to the mean of the values for that variable when Genotype == "miR-15/16 FL", and the value_norm is the value divided by the control_mean.

```<code>tissue_merge %>%
    group_by(.dots = c("Experiment", "Tissue", "variable")) %>%
    mutate(control_mean = mean(value[Genotype == "miR-15/16 FL"], na.rm = T),
           value_norm = value / control_mean) %>%
    filter(Experiment == 170911 & Tissue == "Spleen") %>%
    arrange(variable) %>%
    print.data.frame
#    Experiment     Sample      Genotype              variable value Tissue control_mean value_norm
# 1      170911 Spl_cKO_19 miR-15/16 cKO MFI CD127 Foxp3+ CD4+  3076 Spleen       1816.4  1.6934596
# 2      170911 Spl_cKO_21 miR-15/16 cKO MFI CD127 Foxp3+ CD4+  3083 Spleen       1816.4  1.6973134
# 3      170911 Spl_cKO_29 miR-15/16 cKO MFI CD127 Foxp3+ CD4+  3058 Spleen       1816.4  1.6835499
# 4      170911 Spl_cKO_37 miR-15/16 cKO MFI CD127 Foxp3+ CD4+  3531 Spleen       1816.4  1.9439551
# 5      170911 Spl_cKO_39 miR-15/16 cKO MFI CD127 Foxp3+ CD4+  3032 Spleen       1816.4  1.6692359
# 6      170911 Spl_FL_622  miR-15/16 FL MFI CD127 Foxp3+ CD4+  1757 Spleen       1816.4  0.9672980
# 7      170911 Spl_FL_630  miR-15/16 FL MFI CD127 Foxp3+ CD4+  2039 Spleen       1816.4  1.1225501
# 8      170911 Spl_FL_631  miR-15/16 FL MFI CD127 Foxp3+ CD4+  1927 Spleen       1816.4  1.0608897
# 9      170911 Spl_FL_635  miR-15/16 FL MFI CD127 Foxp3+ CD4+  1611 Spleen       1816.4  0.8869192
# 10     170911 Spl_FL_638  miR-15/16 FL MFI CD127 Foxp3+ CD4+  1748 Spleen       1816.4  0.9623431
# 11     170911 Spl_cKO_19 miR-15/16 cKO MFI CD127 Foxp3- CD4+  4718 Spleen       3788.4  1.2453806
# 12     170911 Spl_cKO_21 miR-15/16 cKO MFI CD127 Foxp3- CD4+  5317 Spleen       3788.4  1.4034949
# 13     170911 Spl_cKO_29 miR-15/16 cKO MFI CD127 Foxp3- CD4+  5007 Spleen       3788.4  1.3216661
# 14     170911 Spl_cKO_37 miR-15/16 cKO MFI CD127 Foxp3- CD4+  5308 Spleen       3788.4  1.4011192
# 15     170911 Spl_cKO_39 miR-15/16 cKO MFI CD127 Foxp3- CD4+  4804 Spleen       3788.4  1.2680815
# 16     170911 Spl_FL_622  miR-15/16 FL MFI CD127 Foxp3- CD4+  4173 Spleen       3788.4  1.1015204
# 17     170911 Spl_FL_630  miR-15/16 FL MFI CD127 Foxp3- CD4+  3501 Spleen       3788.4  0.9241368
# 18     170911 Spl_FL_631  miR-15/16 FL MFI CD127 Foxp3- CD4+  4434 Spleen       3788.4  1.1704150
# 19     170911 Spl_FL_635  miR-15/16 FL MFI CD127 Foxp3- CD4+  3325 Spleen       3788.4  0.8776792
# 20     170911 Spl_FL_638  miR-15/16 FL MFI CD127 Foxp3- CD4+  3509 Spleen       3788.4  0.9262485
# 21     170911 Spl_cKO_19 miR-15/16 cKO        MFI CD127 CD8+  4987 Spleen       3487.2  1.4300872
# 22     170911 Spl_cKO_21 miR-15/16 cKO        MFI CD127 CD8+  5345 Spleen       3487.2  1.5327483
# 23     170911 Spl_cKO_29 miR-15/16 cKO        MFI CD127 CD8+  4744 Spleen       3487.2  1.3604038
# 24     170911 Spl_cKO_37 miR-15/16 cKO        MFI CD127 CD8+  5143 Spleen       3487.2  1.4748222
# 25     170911 Spl_cKO_39 miR-15/16 cKO        MFI CD127 CD8+  4409 Spleen       3487.2  1.2643382
# 26     170911 Spl_FL_622  miR-15/16 FL        MFI CD127 CD8+  3991 Spleen       3487.2  1.1444712
# 27     170911 Spl_FL_630  miR-15/16 FL        MFI CD127 CD8+  3357 Spleen       3487.2  0.9626635
# 28     170911 Spl_FL_631  miR-15/16 FL        MFI CD127 CD8+  3910 Spleen       3487.2  1.1212434
# 29     170911 Spl_FL_635  miR-15/16 FL        MFI CD127 CD8+  3085 Spleen       3487.2  0.8846639
# 30     170911 Spl_FL_638  miR-15/16 FL        MFI CD127 CD8+  3093 Spleen       3487.2  0.8869580
</code>```

For example, for the MFI CD127 Foxp3- CD4+ Genotype, the miR-15/16 FL values are 4173, 3501, 4434, 3325, 3509, and the mean is correct.

```<code>mean(c(4173, 3501, 4434, 3325, 3509))
# [1] 3788.4
</code>```

Title: Normalizing to average of control group within a data frame

Body:
I have a data frame:

    tissue_merge <-structure(list(Experiment = c(170911L, 170911L, 170911L, 170911L,
170911L, 170911L, 170911L, 170911L, 170911L, 170911L, 170911L,
170911L, 170911L, 170911L, 170911L, 170911L, 170911L, 170911L,
170911L, 170911L, 170911L, 170911L, 170911L, 170911L, 170911L,
170911L, 170911L, 170911L, 170911L, 170911L, 170911L, 170911L,
170911L, 170911L, 170911L, 170911L, 170911L, 170911L, 170911L,
170911L, 170911L, 170911L, 170911L, 170911L, 170911L, 170911L,
170911L, 170911L, 170911L, 170911L, 170911L, 170911L, 170911L,
170911L, 170911L, 170911L, 170911L, 170911L, 170911L, 170911L,
170911L, 170911L, 170911L, 170911L, 170911L, 170911L, 170911L,
170911L, 170911L, 170911L, 170911L, 170911L, 170911L, 170911L,
170911L, 170911L, 170911L, 170911L, 170911L, 170911L, 170911L,
170911L, 170911L, 170911L, 170911L, 170911L, 170911L, 170911L,
170911L, 170911L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L, 170918L, 170918L,
170918L, 170918L, 170918L, 170918L, 170918L), Sample = structure(c(11L,
11L, 11L, 12L, 12L, 12L, 13L, 13L, 13L, 14L, 14L, 14L, 15L, 15L,
15L, 16L, 16L, 16L, 17L, 17L, 17L, 18L, 18L, 18L, 19L, 19L, 19L,
20L, 20L, 20L, 21L, 21L, 21L, 22L, 22L, 22L, 23L, 23L, 23L, 24L,
24L, 24L, 25L, 25L, 25L, 26L, 26L, 26L, 27L, 27L, 27L, 28L, 28L,
28L, 29L, 29L, 29L, 30L, 30L, 30L, 31L, 31L, 31L, 32L, 32L, 32L,
33L, 33L, 33L, 34L, 34L, 34L, 35L, 35L, 35L, 36L, 36L, 36L, 37L,
37L, 37L, 38L, 38L, 38L, 39L, 39L, 39L, 40L, 40L, 40L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L,
2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 4L, 4L, 4L, 4L, 4L,
4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 5L, 5L,
5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 5L, 6L, 6L, 6L, 6L, 6L, 6L, 6L,
6L, 6L, 6L, 6L, 6L, 6L, 6L, 6L, 7L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L, 7L, 7L, 7L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L, 8L,
8L, 8L, 8L, 8L, 8L, 8L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L, 9L,
9L, 9L, 9L, 9L, 9L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L, 10L,
10L, 10L, 10L, 10L, 10L, 10L), .Label = c("1: FL_643", "10: cKO_657",
"2: FL_645", "3: FL_647", "4: FL_656", "5: FL_658", "6: cKO_644",
"7: cKO_646", "8: cKO_654", "9: cKO_655", "Spl_cKO_19", "Spl_cKO_21",
"Spl_cKO_29", "Spl_cKO_37", "Spl_cKO_39", "Spl_FL_622", "Spl_FL_630",
"Spl_FL_631", "Spl_FL_635", "Spl_FL_638", "iLN_cKO_19", "iLN_cKO_21",
"iLN_cKO_29", "iLN_cKO_37", "iLN_cKO_39", "iLN_FL_622", "iLN_FL_630",
"iLN_FL_631", "iLN_FL_635", "iLN_FL_638", "Thy_cKO_19", "Thy_cKO_21",
"Thy_cKO_29", "Thy_cKO_37", "Thy_cKO_39", "Thy_FL_622", "Thy_FL_630",
"Thy_FL_631", "Thy_FL_635", "Thy_FL_638"), class = "factor"),
    Genotype = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L), .Label = c("miR-15/16 FL", "miR-15/16 cKO"
    ), class = "factor"), variable = structure(c(1L, 2L, 3L,
    1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L,
    1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L,
    1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L,
    1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L,
    1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L,
    1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 2L, 3L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L,
    1L, 1L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), .Label = c("MFI CD127 Foxp3+ CD4+",
    "MFI CD127 Foxp3- CD4+", "MFI CD127 CD8+"), class = "factor"),
    value = c(3076, 4718, 4987, 3083, 5317, 5345, 3058, 5007,
    4744, 3531, 5308, 5143, 3032, 4804, 4409, 1757, 4173, 3991,
    2039, 3501, 3357, 1927, 4434, 3910, 1611, 3325, 3085, 1748,
    3509, 3093, 1992, 4502, 4866, 2306, 5047, 5062, 2295, 5084,
    4900, 2436, 5266, 5139, 2396, 4804, 4648, 1363, 3974, 3903,
    1550, 3829, 3653, 1543, 4356, 4013, 1356, 3587, 3334, 1444,
    3715, 3410, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
    NA, NA, NA, 494, 518, 524, 917, 1786, 848, 912, 1092, 1191,
    1343, 543, 882, 914, 1127, 1237, 649, 843, 926, 1084, 3714,
    894, 1271, 1382, 1623, 1629, 570, 902, 1363, 1490, 1963,
    528, 610, 715, 2079, NA, 857, 1139, 1147, 1278, 1325, 377,
    1212, 1280, 1635, NA, 572, 613, 727, 1066, 2199, 976, 1025,
    1089, 1304, 1311, 276, 1037, 1165, 1400, 1654, 524, 599,
    624, 1059, 2345, 970, 1090, 1140, 1154, 1208, 470, 1139,
    1267, 1359, 1583, 603, 614, 631, 939, 2360, 868, 1147, 1180,
    1202, 1555, 868, 961, 1102, 1251, 1607, 772, 881, 925, 1269,
    2408, 985, 1095, 1165, 1517, 1735, 402, 1019, 1445, 1583,
    1720, 743, 779, 880, 1047, 2509, 916, 1179, 1190, 1406, 1441,
    489, 904, 1374, 1483, 1817, 719, 722, 932, 974, 3129, 839,
    1188, 1344, 1455, 1616, 524, 966, 1088, 1342, 2100, 764,
    779, 876, 1048, 3263, 866, 1336, 1413, 1560, 1571, 570, 1038,
    1446, 1499, 2051), Tissue = structure(c(2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L,
    2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L,
    3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 3L, 1L, 5L, 4L,
    4L, 5L, 2L, 3L, 1L, 4L, 5L, 3L, 2L, 1L, 1L, 3L, 2L, 5L, 4L,
    5L, 1L, 4L, 3L, 2L, 4L, 5L, 1L, 3L, 2L, 1L, 2L, 3L, 4L, 5L,
    5L, 4L, 1L, 2L, 3L, 4L, 1L, 3L, 2L, 5L, 3L, 2L, 1L, 5L, 4L,
    5L, 4L, 3L, 2L, 1L, 4L, 5L, 3L, 1L, 2L, 1L, 3L, 2L, 5L, 4L,
    5L, 1L, 2L, 3L, 4L, 4L, 5L, 3L, 1L, 2L, 1L, 3L, 2L, 5L, 4L,
    5L, 3L, 2L, 1L, 4L, 5L, 4L, 3L, 1L, 2L, 1L, 3L, 2L, 5L, 4L,
    4L, 1L, 5L, 2L, 3L, 4L, 5L, 1L, 3L, 2L, 3L, 1L, 2L, 5L, 4L,
    5L, 4L, 1L, 2L, 3L, 4L, 5L, 1L, 3L, 2L, 1L, 3L, 2L, 5L, 4L,
    5L, 1L, 4L, 3L, 2L, 4L, 5L, 3L, 1L, 2L, 1L, 3L, 2L, 5L, 4L,
    5L, 1L, 4L, 3L, 2L, 4L, 5L, 1L, 3L, 2L), .Label = c("Thymus",
    "Spleen", "iLN", "Skin", "Colon"), class = "factor")), .Names = c("Experiment",
"Sample", "Genotype", "variable", "value", "Tissue"), row.names = c(19L,
23L, 30L, 71L, 75L, 82L, 123L, 127L, 134L, 175L, 179L, 186L,
227L, 231L, 238L, 279L, 283L, 290L, 331L, 335L, 342L, 383L, 387L,
394L, 435L, 439L, 446L, 487L, 491L, 498L, 539L, 543L, 550L, 591L,
595L, 602L, 643L, 647L, 654L, 695L, 699L, 706L, 747L, 751L, 758L,
799L, 803L, 810L, 851L, 855L, 862L, 903L, 907L, 914L, 955L, 959L,
966L, 1007L, 1011L, 1018L, 1049L, 1053L, 1055L, 1098L, 1102L,
1104L, 1147L, 1151L, 1153L, 1196L, 1200L, 1202L, 1245L, 1249L,
1251L, 1294L, 1298L, 1300L, 1343L, 1347L, 1349L, 1392L, 1396L,
1398L, 1441L, 1445L, 1447L, 1490L, 1494L, 1496L, 1589L, 1590L,
1591L, 1592L, 1593L, 1609L, 1610L, 1611L, 1612L, 1613L, 1629L,
1630L, 1631L, 1632L, 1633L, 1842L, 1843L, 1844L, 1845L, 1846L,
1862L, 1863L, 1864L, 1865L, 1866L, 1882L, 1883L, 1884L, 1885L,
1886L, 2095L, 2096L, 2097L, 2098L, 2099L, 2115L, 2116L, 2117L,
2118L, 2119L, 2135L, 2136L, 2137L, 2138L, 2139L, 2348L, 2349L,
2350L, 2351L, 2352L, 2368L, 2369L, 2370L, 2371L, 2372L, 2388L,
2389L, 2390L, 2391L, 2392L, 2601L, 2602L, 2603L, 2604L, 2605L,
2621L, 2622L, 2623L, 2624L, 2625L, 2641L, 2642L, 2643L, 2644L,
2645L, 2854L, 2855L, 2856L, 2857L, 2858L, 2874L, 2875L, 2876L,
2877L, 2878L, 2894L, 2895L, 2896L, 2897L, 2898L, 3107L, 3108L,
3109L, 3110L, 3111L, 3127L, 3128L, 3129L, 3130L, 3131L, 3147L,
3148L, 3149L, 3150L, 3151L, 3360L, 3361L, 3362L, 3363L, 3364L,
3380L, 3381L, 3382L, 3383L, 3384L, 3400L, 3401L, 3402L, 3403L,
3404L, 3613L, 3614L, 3615L, 3616L, 3617L, 3633L, 3634L, 3635L,
3636L, 3637L, 3653L, 3654L, 3655L, 3656L, 3657L, 3866L, 3867L,
3868L, 3869L, 3870L, 3886L, 3887L, 3888L, 3889L, 3890L, 3906L,
3907L, 3908L, 3909L, 3910L), class = "data.frame")

What I would like to do is normalize each value to the average of its respective "miR-15/16 FL" control for each tissue and each experiment.

I have tried to do this using dplyr with an average function

tissue_merge <- tissue_merge %>%
  group_by(.dots = c("Experiment", "Tissue", "variable"), na.rm = T) %>%
  mutate(value_norm = value/mean(value))

However, this function just gives me "NA" as the value_norm for every number.

I realize that in my current code, I am not specifying that I want to only use the average of the "miR-15/16 FL" samples but I do not know how to incorporate that into this function (not to mention that the function doesn't even give values at all as is).

For clarification:

For a given tissue, say "Spleen", for a given variable, say "MFI CD127 Foxp3- CD4+", for a given experiment, say "170911" I would like to take each value and divide it by the average of the "miR-15/16 FL" samples. This should result in a batch normalization for each experiment so that when I pool data from multiple experiments, everything is relative to the "miR-15/16 FL" samples within each experiment.

For "Spleen" "MFI CD127 Foxp3- CD4+", the normalized data should look like this when combining the multiple experiments post normalization:

Body:
You could do it all in one step, but it's clearer to add a column for the control mean and then take it out later.

tissue_merge %>%
    group_by(.dots = c("Experiment", "Tissue", "variable")) %>%
    mutate(control_mean = mean(value[Genotype == "miR-15/16 FL"], na.rm = T),
           value_norm = value / control_mean) %>%
    select(-control_mean)

Demo Below you can see that, for Experiment 170911 and Tissue Spleen, for each variable, MFI CD127 Foxp3+ CD4+, MFI CD127 Foxp3- CD4+, and MFI CD127 CD127 CD8+, the control_mean is equal to the mean of the values for that variable when Genotype == "miR-15/16 FL", and the value_norm is the value divided by the control_mean.

tissue_merge %>%
    group_by(.dots = c("Experiment", "Tissue", "variable")) %>%
    mutate(control_mean = mean(value[Genotype == "miR-15/16 FL"], na.rm = T),
           value_norm = value / control_mean) %>%
    filter(Experiment == 170911 & Tissue == "Spleen") %>%
    arrange(variable) %>%
    print.data.frame
#    Experiment     Sample      Genotype              variable value Tissue control_mean value_norm
# 1      170911 Spl_cKO_19 miR-15/16 cKO MFI CD127 Foxp3+ CD4+  3076 Spleen       1816.4  1.6934596
# 2      170911 Spl_cKO_21 miR-15/16 cKO MFI CD127 Foxp3+ CD4+  3083 Spleen       1816.4  1.6973134
# 3      170911 Spl_cKO_29 miR-15/16 cKO MFI CD127 Foxp3+ CD4+  3058 Spleen       1816.4  1.6835499
# 4      170911 Spl_cKO_37 miR-15/16 cKO MFI CD127 Foxp3+ CD4+  3531 Spleen       1816.4  1.9439551
# 5      170911 Spl_cKO_39 miR-15/16 cKO MFI CD127 Foxp3+ CD4+  3032 Spleen       1816.4  1.6692359
# 6      170911 Spl_FL_622  miR-15/16 FL MFI CD127 Foxp3+ CD4+  1757 Spleen       1816.4  0.9672980
# 7      170911 Spl_FL_630  miR-15/16 FL MFI CD127 Foxp3+ CD4+  2039 Spleen       1816.4  1.1225501
# 8      170911 Spl_FL_631  miR-15/16 FL MFI CD127 Foxp3+ CD4+  1927 Spleen       1816.4  1.0608897
# 9      170911 Spl_FL_635  miR-15/16 FL MFI CD127 Foxp3+ CD4+  1611 Spleen       1816.4  0.8869192
# 10     170911 Spl_FL_638  miR-15/16 FL MFI CD127 Foxp3+ CD4+  1748 Spleen       1816.4  0.9623431
# 11     170911 Spl_cKO_19 miR-15/16 cKO MFI CD127 Foxp3- CD4+  4718 Spleen       3788.4  1.2453806
# 12     170911 Spl_cKO_21 miR-15/16 cKO MFI CD127 Foxp3- CD4+  5317 Spleen       3788.4  1.4034949
# 13     170911 Spl_cKO_29 miR-15/16 cKO MFI CD127 Foxp3- CD4+  5007 Spleen       3788.4  1.3216661
# 14     170911 Spl_cKO_37 miR-15/16 cKO MFI CD127 Foxp3- CD4+  5308 Spleen       3788.4  1.4011192
# 15     170911 Spl_cKO_39 miR-15/16 cKO MFI CD127 Foxp3- CD4+  4804 Spleen       3788.4  1.2680815
# 16     170911 Spl_FL_622  miR-15/16 FL MFI CD127 Foxp3- CD4+  4173 Spleen       3788.4  1.1015204
# 17     170911 Spl_FL_630  miR-15/16 FL MFI CD127 Foxp3- CD4+  3501 Spleen       3788.4  0.9241368
# 18     170911 Spl_FL_631  miR-15/16 FL MFI CD127 Foxp3- CD4+  4434 Spleen       3788.4  1.1704150
# 19     170911 Spl_FL_635  miR-15/16 FL MFI CD127 Foxp3- CD4+  3325 Spleen       3788.4  0.8776792
# 20     170911 Spl_FL_638  miR-15/16 FL MFI CD127 Foxp3- CD4+  3509 Spleen       3788.4  0.9262485
# 21     170911 Spl_cKO_19 miR-15/16 cKO        MFI CD127 CD8+  4987 Spleen       3487.2  1.4300872
# 22     170911 Spl_cKO_21 miR-15/16 cKO        MFI CD127 CD8+  5345 Spleen       3487.2  1.5327483
# 23     170911 Spl_cKO_29 miR-15/16 cKO        MFI CD127 CD8+  4744 Spleen       3487.2  1.3604038
# 24     170911 Spl_cKO_37 miR-15/16 cKO        MFI CD127 CD8+  5143 Spleen       3487.2  1.4748222
# 25     170911 Spl_cKO_39 miR-15/16 cKO        MFI CD127 CD8+  4409 Spleen       3487.2  1.2643382
# 26     170911 Spl_FL_622  miR-15/16 FL        MFI CD127 CD8+  3991 Spleen       3487.2  1.1444712
# 27     170911 Spl_FL_630  miR-15/16 FL        MFI CD127 CD8+  3357 Spleen       3487.2  0.9626635
# 28     170911 Spl_FL_631  miR-15/16 FL        MFI CD127 CD8+  3910 Spleen       3487.2  1.1212434
# 29     170911 Spl_FL_635  miR-15/16 FL        MFI CD127 CD8+  3085 Spleen       3487.2  0.8846639
# 30     170911 Spl_FL_638  miR-15/16 FL        MFI CD127 CD8+  3093 Spleen       3487.2  0.8869580

For example, for the MFI CD127 Foxp3- CD4+ Genotype, the miR-15/16 FL values are 4173, 3501, 4434, 3325, 3509, and the mean is correct.

mean(c(4173, 3501, 4434, 3325, 3509))
# [1] 3788.4


问:
AsyncStorage doesnt return anything
I want to store data via asyncstorage in my react-native app, But I have a problem. I using it like that:

```<code> async componentDidMount() {
 console.log("Flag1");
 await AsyncStorage.setItem('name', 'I like to save it.');
 console.log("Flag2");
 }
</code>```

But for some reason I cant reach "Flag2", And I am not getting an error or a data from the await call.
I also tried use try/catch, facing the same problem.

edit I noticed that AsyncStorage works for me only when I just open the emulator, after a couple of uses it stops working.

答:
I think the best practice is, as suggested on react-native docs here, is to wrap it with a try catch expression.

```<code>_setAsyncStorage = async () => {
    try { await AsyncStorage.setItem('@name', 'I like to save it');
  } catch (error) {
    // Error saving data
  }
}
</code>```

you can call this function from any point within your component.

Title: AsyncStorage doesnt return anything

Body:
I want to store data via asyncstorage in my react-native app, But I have a problem. I using it like that:

 async componentDidMount() {
 console.log("Flag1");
 await AsyncStorage.setItem('name', 'I like to save it.');
 console.log("Flag2");
 }

But for some reason I cant reach "Flag2", And I am not getting an error or a data from the await call.
I also tried use try/catch, facing the same problem.

edit I noticed that AsyncStorage works for me only when I just open the emulator, after a couple of uses it stops working.

Body:
I think the best practice is, as suggested on react-native docs here, is to wrap it with a try catch expression.

_setAsyncStorage = async () => {
    try { await AsyncStorage.setItem('@name', 'I like to save it');
  } catch (error) {
    // Error saving data
  }
}

you can call this function from any point within your component.


问:
Function that create a directory and an unlimited number of subdirectories
My aim is to create a function, from a list corresponding to directories and subdirectories.

For example : 'reports/English' corresponds to the subdirectory 'English' in the directory 'reports'.

Here's my function :

```<code>for i in lst:
  splitted = i.split('/')
  if not os.path.exists(destination_directory + '\\' + splitted[0]) :
    os.mkdir(destination_directory + '\\' + splitted[0])
    os.mkdir(destination_directory + '\\' + splitted[0] + '\\' + splitted[1])
  else :
    os.mkdir(destination_directory + '\\' + splitted[0] + '\\' + splitted[1])
</code>```

I don't want to use the function os.chdir out of fear of losing myself in the folders.

I'd like to do a recursive function, I tried this :

```<code>def my_sub_function(splitted):
"""
"""
if splitted == []:
    return None

else:
    if not os.path.exists(destination_directory + '\\' + splitted[0]) :
        os.mkdir(destination_directory + '\\' + splitted[0])
        os.mkdir(destination_directory + '\\' + splitted[0] + '\\' + splitted[1])
    else :
        os.mkdir(destination_directory + '\\' + splitted[0] + '\\' + splitted[1])
        return t1(splitted[1:])
</code>```

So, consider this list :

```<code>lst_1 =

['music',
 'reports/English',
 'reports/Spanish',
 'videos',
 'pictures/family',
 'pictures/party']
</code>```

if I do :

```<code>it will creates these directories :
.\\music
.\\reports\\English
.\\reports\\Spanish
.\\videos
.\\pictures\\family
.\\pictures\\party
</code>```

But I'm limited to on directory and only one sub_directory.
I'd like for my function to handle 3 or 4 subdirectories so that it could create something like this :

```<code>.\\pictures\\family\\Christmas\\meal\\funny
</code>```

Does anyone has an idea ?

Thank you !

答:
You don't need recursion necessarily, just a simple directory walk:

```<code>import os

def create_path(path):
    current_path = "."  # start with the current path
    segments = os.path.split(path)  # split the path into segments
    for segment in segments:
        candidate = os.path.join(current_path, segment)  # get the candidate
        if not os.path.exists(candidate):  # the path doesn't exist
            os.mkdir(candidate)  # create it
        current_path = candidate  # this is now our new path
    return current_path  # return the final path
</code>```

Of course, you can use os.makedirs() instead to do all this for you. Either way, you should also check if you encounter a file along the way (as simple os.path.exists() won't suffice in all cases) and do error handling in case the user doesn't have permissions to create directories.

Also, don't use literal path separators as those differ from platform to platform (althouth CPython is usually smart enough to deal with platform differences).

Body:
My aim is to create a function, from a list corresponding to directories and subdirectories.

For example : 'reports/English' corresponds to the subdirectory 'English' in the directory 'reports'.

Here's my function :

for i in lst:
  splitted = i.split('/')
  if not os.path.exists(destination_directory + '\\' + splitted[0]) :
    os.mkdir(destination_directory + '\\' + splitted[0])
    os.mkdir(destination_directory + '\\' + splitted[0] + '\\' + splitted[1])
  else :
    os.mkdir(destination_directory + '\\' + splitted[0] + '\\' + splitted[1])

I don't want to use the function os.chdir out of fear of losing myself in the folders.

I'd like to do a recursive function, I tried this :

def my_sub_function(splitted):
"""
"""
if splitted == []:
    return None

else:
    if not os.path.exists(destination_directory + '\\' + splitted[0]) :
        os.mkdir(destination_directory + '\\' + splitted[0])
        os.mkdir(destination_directory + '\\' + splitted[0] + '\\' + splitted[1])
    else :
        os.mkdir(destination_directory + '\\' + splitted[0] + '\\' + splitted[1])
        return t1(splitted[1:])

So, consider this list :

lst_1 =

['music',
 'reports/English',
 'reports/Spanish',
 'videos',
 'pictures/family',
 'pictures/party']

if I do :

it will creates these directories :
.\\music
.\\reports\\English
.\\reports\\Spanish
.\\videos
.\\pictures\\family
.\\pictures\\party

But I'm limited to on directory and only one sub_directory.
I'd like for my function to handle 3 or 4 subdirectories so that it could create something like this :

.\\pictures\\family\\Christmas\\meal\\funny

Does anyone has an idea ?

Thank you !

Body:
You don't need recursion necessarily, just a simple directory walk:

import os

def create_path(path):
    current_path = "."  # start with the current path
    segments = os.path.split(path)  # split the path into segments
    for segment in segments:
        candidate = os.path.join(current_path, segment)  # get the candidate
        if not os.path.exists(candidate):  # the path doesn't exist
            os.mkdir(candidate)  # create it
        current_path = candidate  # this is now our new path
    return current_path  # return the final path

Of course, you can use os.makedirs() instead to do all this for you. Either way, you should also check if you encounter a file along the way (as simple os.path.exists() won't suffice in all cases) and do error handling in case the user doesn't have permissions to create directories.

Also, don't use literal path separators as those differ from platform to platform (althouth CPython is usually smart enough to deal with platform differences).


问:
jQuery DataTables fixed size for ONE of the columns?
I have a DataTables table where I want it to autosize as default (when resizing window and according to initial content etc.), except for one special column, for which I'd like to have a fixed width.

It seems, if I set a width using columnDefs, the table is initially autosized according to content, but it no longer adapts to a changed window width. Doesn't seem to matter if I specify a % width or a pixel width.

答:
If you want precise control over the table column widths you must use CSS:

table.dataTable thead th:nth-child(4),
table.dataTable tbody td:nth-child(4) {
  width: 200px;
  max-width: 200px;
  min-width: 200px;
}
```

<p>If you inspect the above column you will see the that <em>computed</em> <code>width</code> is larger than <code>200px</code>. This is the padding kicking in, so you must reset <code>padding-left</code> and <code>padding-right</code> to get exactly 200px.</p>

<p>If you want to shrink a column to a width beyond "reasonable" you must add som additional CSS :</p>

<pre class="lang-css prettyprint-override"><code>table.dataTable {
  table-layout: fixed;
}
</code>```

Why this is needed you can read about here -> https://developer.mozilla.org/en-US/docs/Web/CSS/table-layout#Values

table.dataTable thead th:nth-child(2),
table.dataTable tbody td:nth-child(2) {
  word-break: break-all;
  overflow-wrap: break-word;
  width: 20px;
  max-width: 20px;
  padding-right: 0px;
  padding-left: 0px;
}
```

demo -> http://jsfiddle.net/n4j1wgu5/

Body:
If you want precise control over the table column widths you must use CSS:

table.dataTable thead th:nth-child(4),
table.dataTable tbody td:nth-child(4) {
  width: 200px;
  max-width: 200px;
  min-width: 200px;
}

If you inspect the above column you will see the that computed width is larger than 200px. This is the padding kicking in, so you must reset padding-left and padding-right to get exactly 200px.

If you want to shrink a column to a width beyond "reasonable" you must add som additional CSS :

table.dataTable {
  table-layout: fixed;
}

Why this is needed you can read about here -> https://developer.mozilla.org/en-US/docs/Web/CSS/table-layout#Values

table.dataTable thead th:nth-child(2),
table.dataTable tbody td:nth-child(2) {
  word-break: break-all;
  overflow-wrap: break-word;
  width: 20px;
  max-width: 20px;
  padding-right: 0px;
  padding-left: 0px;
}

demo -> http://jsfiddle.net/n4j1wgu5/


问:
RecyclerView in fragment crash after start
please help . i have used RecycleView in fragment . but when i start the activity... get crash! i think caused from view . but dont know why !?
anybody have idea?
Hi .please help . i have used RecycleView in fragment . but when i start the activity... get crash! i think caused from view . but dont know why !?
anybody have idea?

fragmentHome.java

```<code>public class HomeFragment2 extends Fragment {

List<DataAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http://androidblog.esy.es/ImageJsonData.php";
String Image_Name_JSON = "image_title";
String Image_URL_JSON = "image_url";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;

public static HomeFragment2 newInstance() {

    return new HomeFragment2();
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_home2, container, false);

    ImageTitleNameArrayListForClick = new ArrayList<>();

    ListOfdataAdapter = new ArrayList<>();

    recyclerView =getActivity(). findViewById(R.id.recyclerview1);

    recyclerView.setHasFixedSize(true);

    layoutManagerOfrecyclerView = new LinearLayoutManager(getActivity());

    recyclerView.setLayoutManager(layoutManagerOfrecyclerView);

    JSON_HTTP_CALL();

    // Implementing Click Listener on RecyclerView.
    recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {

        GestureDetector gestureDetector = new GestureDetector(getActivity(), new GestureDetector.SimpleOnGestureListener() {

            @Override public boolean onSingleTapUp(MotionEvent motionEvent) {

                return true;
            }

        });
        @Override
        public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {

            view = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());

            if(view != null && gestureDetector.onTouchEvent(motionEvent)) {

                //Getting RecyclerView Clicked Item value.
                RecyclerViewItemPosition = Recyclerview.getChildAdapterPosition(view);

                // Showing RecyclerView Clicked Item value using Toast.
                Toast.makeText(getActivity(), ImageTitleNameArrayListForClick.get(RecyclerViewItemPosition), Toast.LENGTH_LONG).show();
            }

            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {

        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    });

    return v;

}

public void JSON_HTTP_CALL(){

    RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL,

            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    ParseJSonResponse(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    requestQueue = Volley.newRequestQueue(getActivity());

    requestQueue.add(RequestOfJSonArray);
}

public void ParseJSonResponse(JSONArray array){

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

        DataAdapter GetDataAdapter2 = new DataAdapter();

        JSONObject json = null;
        try {

            json = array.getJSONObject(i);

            GetDataAdapter2.setImageTitle(json.getString(Image_Name_JSON));

            // Adding image title name in array to display on RecyclerView click event.
            ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));

            GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));

        } catch (JSONException e) {

            e.printStackTrace();
        }
        ListOfdataAdapter.add(GetDataAdapter2);
    }

    recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, getActivity());

    recyclerView.setAdapter(recyclerViewadapter);
}
}
</code>```

and error in logcat is :

```<code>                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
                                                                          at android.app.ActivityThread.access$600(ActivityThread.java:156)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                          at android.os.Looper.loop(Looper.java:153)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5297)
                                                                          at java.lang.reflect.Method.invokeNative(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:511)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                                                                          at dalvik.system.NativeStart.main(Native Method)
                                                                       Caused by: java.lang.NullPointerException
                                                                          at ir.dadevarzjooya.MainActivity2.HomeFragment2.onCreateView(HomeFragment2.java:60)
                                                                          at android.app.Fragment.performCreateView(Fragment.java:1695)
                                                                          at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:885)
                                                                          at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
                                                                          at android.app.BackStackRecord.run(BackStackRecord.java:694)
                                                                          at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
                                                                          at android.app.Activity.performStart(Activity.java:5131)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2279)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
                                                                          at android.app.ActivityThread.access$600(ActivityThread.java:156)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                          at android.os.Looper.loop(Looper.java:153)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5297)
                                                                          at java.lang.reflect.Method.invokeNative(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:511)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                                                                          at dalvik.system.NativeStart.main(Native Method)
</code>```

any body have idea ?
i think this problem is caused from view ...

答:
The problem is on this line.

```<code>recyclerView = getActivity().findViewById(R.id.recyclerview1);
</code>```

Replace that line with this

```<code>recyclerView = v.findViewById(R.id.recyclerview1);
</code>```

You should get your recycler view from the fragment's layout which is being initialized in the beginning of your method, not from the activity

Body:
please help . i have used RecycleView in fragment . but when i start the activity... get crash! i think caused from view . but dont know why !?
anybody have idea?
Hi .please help . i have used RecycleView in fragment . but when i start the activity... get crash! i think caused from view . but dont know why !?
anybody have idea?

fragmentHome.java

public class HomeFragment2 extends Fragment {

List<DataAdapter> ListOfdataAdapter;
RecyclerView recyclerView;
String HTTP_JSON_URL = "http://androidblog.esy.es/ImageJsonData.php";
String Image_Name_JSON = "image_title";
String Image_URL_JSON = "image_url";
JsonArrayRequest RequestOfJSonArray ;
RequestQueue requestQueue ;
View view ;
int RecyclerViewItemPosition ;
RecyclerView.LayoutManager layoutManagerOfrecyclerView;
RecyclerView.Adapter recyclerViewadapter;
ArrayList<String> ImageTitleNameArrayListForClick;

public static HomeFragment2 newInstance() {

    return new HomeFragment2();
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {

    View v = inflater.inflate(R.layout.fragment_home2, container, false);

    ImageTitleNameArrayListForClick = new ArrayList<>();

    ListOfdataAdapter = new ArrayList<>();

    recyclerView =getActivity(). findViewById(R.id.recyclerview1);

    recyclerView.setHasFixedSize(true);

    layoutManagerOfrecyclerView = new LinearLayoutManager(getActivity());

    recyclerView.setLayoutManager(layoutManagerOfrecyclerView);

    JSON_HTTP_CALL();

    // Implementing Click Listener on RecyclerView.
    recyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {

        GestureDetector gestureDetector = new GestureDetector(getActivity(), new GestureDetector.SimpleOnGestureListener() {

            @Override public boolean onSingleTapUp(MotionEvent motionEvent) {

                return true;
            }

        });
        @Override
        public boolean onInterceptTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {

            view = Recyclerview.findChildViewUnder(motionEvent.getX(), motionEvent.getY());

            if(view != null && gestureDetector.onTouchEvent(motionEvent)) {

                //Getting RecyclerView Clicked Item value.
                RecyclerViewItemPosition = Recyclerview.getChildAdapterPosition(view);

                // Showing RecyclerView Clicked Item value using Toast.
                Toast.makeText(getActivity(), ImageTitleNameArrayListForClick.get(RecyclerViewItemPosition), Toast.LENGTH_LONG).show();
            }

            return false;
        }

        @Override
        public void onTouchEvent(RecyclerView Recyclerview, MotionEvent motionEvent) {

        }

        @Override
        public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {

        }
    });

    return v;

}

public void JSON_HTTP_CALL(){

    RequestOfJSonArray = new JsonArrayRequest(HTTP_JSON_URL,

            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {

                    ParseJSonResponse(response);
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {

                }
            });

    requestQueue = Volley.newRequestQueue(getActivity());

    requestQueue.add(RequestOfJSonArray);
}

public void ParseJSonResponse(JSONArray array){

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

        DataAdapter GetDataAdapter2 = new DataAdapter();

        JSONObject json = null;
        try {

            json = array.getJSONObject(i);

            GetDataAdapter2.setImageTitle(json.getString(Image_Name_JSON));

            // Adding image title name in array to display on RecyclerView click event.
            ImageTitleNameArrayListForClick.add(json.getString(Image_Name_JSON));

            GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));

        } catch (JSONException e) {

            e.printStackTrace();
        }
        ListOfdataAdapter.add(GetDataAdapter2);
    }

    recyclerViewadapter = new RecyclerViewAdapter(ListOfdataAdapter, getActivity());

    recyclerView.setAdapter(recyclerViewadapter);
}
}

and error in logcat is :

                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2306)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
                                                                          at android.app.ActivityThread.access$600(ActivityThread.java:156)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                          at android.os.Looper.loop(Looper.java:153)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5297)
                                                                          at java.lang.reflect.Method.invokeNative(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:511)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                                                                          at dalvik.system.NativeStart.main(Native Method)
                                                                       Caused by: java.lang.NullPointerException
                                                                          at ir.dadevarzjooya.MainActivity2.HomeFragment2.onCreateView(HomeFragment2.java:60)
                                                                          at android.app.Fragment.performCreateView(Fragment.java:1695)
                                                                          at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:885)
                                                                          at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1057)
                                                                          at android.app.BackStackRecord.run(BackStackRecord.java:694)
                                                                          at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1435)
                                                                          at android.app.Activity.performStart(Activity.java:5131)
                                                                          at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2279)
                                                                          at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2358)
                                                                          at android.app.ActivityThread.access$600(ActivityThread.java:156)
                                                                          at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1340)
                                                                          at android.os.Handler.dispatchMessage(Handler.java:99)
                                                                          at android.os.Looper.loop(Looper.java:153)
                                                                          at android.app.ActivityThread.main(ActivityThread.java:5297)
                                                                          at java.lang.reflect.Method.invokeNative(Native Method)
                                                                          at java.lang.reflect.Method.invoke(Method.java:511)
                                                                          at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
                                                                          at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
                                                                          at dalvik.system.NativeStart.main(Native Method)

any body have idea ?
i think this problem is caused from view ...

Body:
The problem is on this line.

recyclerView = getActivity().findViewById(R.id.recyclerview1);

Replace that line with this

recyclerView = v.findViewById(R.id.recyclerview1);

You should get your recycler view from the fragment's layout which is being initialized in the beginning of your method, not from the activity


问:
How to pass Global variables to classes in PHP?
How can I pass the global variables to the classes I want to use without declare them as GLOBAL in every method of the class ?

example :

```<code>$admin = "admin_area";

if($_POST['login']){
      $user = new Administrator;
      $user->auth($pass,$username);
    }
</code>```

in the class Administrator I want the variable $admin be accessible in all methods of the class without doing this :

```<code>class Administrator{

   public function auth($pass,$user){

     global $admin;
     .....

  }
  public function logout(){
    global $admin;

    .....
}

}
</code>```

答:
Generally, PHP provides $GLOBAL array, which can be used to access superglobal variables. BTW, using this array is not much better than using "global" statement in the beginning of all your methods. Also, using such approach does not seem to be a good practice for object-oriented code.

So, you can:

either pass these variables as constructor parameter (see answer from ircmaxell for details)

or use some configuration class (singleton)

Decision depends on semantics of your global parameters.

ContentLicense: CC BY-SA 2.5

Body:
How can I pass the global variables to the classes I want to use without declare them as GLOBAL in every method of the class ?

example :

$admin = "admin_area";

if($_POST['login']){
      $user = new Administrator;
      $user->auth($pass,$username);
    }

in the class Administrator I want the variable $admin be accessible in all methods of the class without doing this :

class Administrator{

   public function auth($pass,$user){

     global $admin;
     .....

  }
  public function logout(){
    global $admin;

    .....
}

}


问:
Excel CountIf with Multiple Nested If Statements

I have a table of Data in Excel on one tab that I have created a report for on another tab. The Report is a table filled with calculations which are fed from the data tab. Right now all results are shown for the week ending date I select. I am now trying to add code to the formula calculations that allows me to further progressively filter the table results.

For example From:

"All" Default Data for selected Week Ending

```<code>-->Filter by column F in data tab
--> Filter by column F & G, but if F is blank show all values in column  F and filter only on G
--> Filter by column F, G and H, but if F or G is blank filter only on column G- and for any combination of blanks and selected values there should be.
</code>```

I have the extra filters set up as drop down selections from the data validation tab and the lists are all in a 3rd tab away from the report and master data. I have 8 columns right now that I am trying to be able to filter on in any combination.

This is an example of the code I started with for the filter:

```<code>(1) =IF($Q$4="",COUNTIFS(Master!A:A,B$2),COUNTIFS(Master!$A:$A,B$2,Master!B:B,$Q$4))

(2)=IF($Q$5="",COUNTIFS(Master!$A:$A,B$2),COUNTIFS(Master!$A:$A,B$2,Master!C:C,$Q$5))
</code>```

Breakdown of Formula 1 (same concept for the remaining):

Q4 refers to the cell that the dropdown list resides for this particular filter
Master!A:A is the master data file
B2 is the Date being searched for in the Master Data
Master!B:B is the column to be filtered by the Q4 selection

So far when trying to combine two or more of the Q selections (there are several, Q4,Q5,Q6,Q7,Q8,Q9,Q10,Q11 which filters columns B:B,C:C,D:D,E:E and so on in the master data. I need the table formulas to be able to handle receiving input from the dropdown and progressively filter down the data for each selection, or allow all data from that column (not already filtered out) to pass through to the next criteria.

So far when I try to combine the Q dropdown formulas I end up with a value of 0, since even if I have a

```<code>    countifs(if(OR(Q2="", Q3="") followed by the filter criteria
</code>```

if one of the filters is not selected, the formula drops the total value to "0" when it gets to the blank in the Q criteria.

Someone please help! Is there another way to do this? I feel like I am so close and am just missing something small.

TIA,

Jesse

Body:
I have a table of Data in Excel on one tab that I have created a report for on another tab. The Report is a table filled with calculations which are fed from the data tab. Right now all results are shown for the week ending date I select. I am now trying to add code to the formula calculations that allows me to further progressively filter the table results.

For example From:

"All" Default Data for selected Week Ending

-->Filter by column F in data tab
--> Filter by column F & G, but if F is blank show all values in column  F and filter only on G
--> Filter by column F, G and H, but if F or G is blank filter only on column G- and for any combination of blanks and selected values there should be.

I have the extra filters set up as drop down selections from the data validation tab and the lists are all in a 3rd tab away from the report and master data. I have 8 columns right now that I am trying to be able to filter on in any combination.

This is an example of the code I started with for the filter:

(1) =IF($Q$4="",COUNTIFS(Master!A:A,B$2),COUNTIFS(Master!$A:$A,B$2,Master!B:B,$Q$4))

(2)=IF($Q$5="",COUNTIFS(Master!$A:$A,B$2),COUNTIFS(Master!$A:$A,B$2,Master!C:C,$Q$5))

Breakdown of Formula 1 (same concept for the remaining):

Q4 refers to the cell that the dropdown list resides for this particular filter
Master!A:A is the master data file
B2 is the Date being searched for in the Master Data
Master!B:B is the column to be filtered by the Q4 selection

So far when trying to combine two or more of the Q selections (there are several, Q4,Q5,Q6,Q7,Q8,Q9,Q10,Q11 which filters columns B:B,C:C,D:D,E:E and so on in the master data. I need the table formulas to be able to handle receiving input from the dropdown and progressively filter down the data for each selection, or allow all data from that column (not already filtered out) to pass through to the next criteria.

So far when I try to combine the Q dropdown formulas I end up with a value of 0, since even if I have a

    countifs(if(OR(Q2="", Q3="") followed by the filter criteria

if one of the filters is not selected, the formula drops the total value to "0" when it gets to the blank in the Q criteria.

Someone please help! Is there another way to do this? I feel like I am so close and am just missing something small.

TIA,

Jesse

Body:
So something like this:

=COUNTIFS(Master!$A:$A,B$2,Master!B:B,IF($Q$4<>"",$Q$4,"*"),Master!c:C,IF($Q$5<>"",$Q$5,"*"),...)


问:
python: Move file to ftp folder shortcut without credentials, possible?
So I have files on c:\some_folder, that I want to move to a folder that is in path c:\Users\my_user\Desktop\hello_shortcut, but actually hello_shortcut is an ftp folder. It has an address like 192.100.xxx.xxx. When I copy the address from the toolbar, I get something like ftp://some-text:some-text@192.100.xxx.xxx.

I tried using shutil.move and setting the destination as the shortcut hello_shortcut, but that doesn't work. Although I certainly can simply drag and drop files to this folder manually, and they will appear on the server.

Any solutions to this, except getting the credentials? Can I acquire the credentials from Windows itself, seeing as I already have them stored somewhere? or maybe find a way to transfer files to this shortcut folder anyway?

答:
Shortcut is not a folder, it is just a file pointing to some object. So you can't use it as a directory while moving file. If the shortcut refers to the ftp shared directory, you can use its real path.

Or, if the shortcut can be modified and you can't rely on the real path, read its target with separate function:

```<code>import sys
import win32com.client

def get_target(path):
    shell = win32com.client.Dispatch("WScript.Shell")
    shortcut = shell.CreateShortCut(path)
    return shortcut.Targetpath

get_target("c:\\Users\\my_user\\Desktop\\hello_shortcut.lnk")
</code>```

And then use this path as usual to operate with the file.

Body:
Shortcut is not a folder, it is just a file pointing to some object. So you can't use it as a directory while moving file. If the shortcut refers to the ftp shared directory, you can use its real path.

Or, if the shortcut can be modified and you can't rely on the real path, read its target with separate function:

import sys
import win32com.client

def get_target(path):
    shell = win32com.client.Dispatch("WScript.Shell")
    shortcut = shell.CreateShortCut(path)
    return shortcut.Targetpath

get_target("c:\\Users\\my_user\\Desktop\\hello_shortcut.lnk")

And then use this path as usual to operate with the file.


问:
zeppelin 8-SNAPSHOT helium not loading from local repository
I am using the current Zeppelin - 0.8.0 Snapshot from today Dec 6 2017. I am trying to modify a helium module for Zeppelin. I have loaded the three files needed into zeppelin/helium/ but when I go to the helium page there are no Helium modules listed.

If I delete the helium directory the helium modules hosted on npm show back up.

I put these three files in a helium directory I created under the zeppelin directory:
index.js, package.json, volume-leaflet.json

Where do the errors show up for this?

I also tried running these commands:
    cd zeppelin-web
    yarn run dev:helium
As indicated on:
https://zeppelin.apache.org/docs/0.8.0-SNAPSHOT/development/helium/writing_visualization_basic.html

Then I tried port 9000 but still the helium module does not show up.

Thanks for the help.

brad

答:
Just figured out the answer.

Do not put all the files that compose the helium module into the zeppelin/helium directory.

Only place the helium package file in the helium directory. In this case volume-leaflet.json file. This file points to another location where the code for the helium module you are building lives.

In the development directory which can be anywhere else place the package.json and the javascript file and other code files.

Then you make another json file with the name of your helium module into the zeppelin/helium directory. And make sure the archive: directive is pointed at the path where the development code is.

If you have the wrong files in the zeppelin/helium directory none of the Helium modules will work.

Also if your helium module has the same name as one hosted at npm it will not show up. I had to change the name to volume-leaflet-dev to get it to show up.


问:
Spark on Windows - "The system cannot find the path specified."
This seems like a common problem with trying to use Spark on Windows from the research I've done so far, and usually has to do with the PATH being set incorrectly.
I've triple checked the PATH however, and tried out many of the solutions I've come across online, and I still can't figure out what's causing the problem.

Trying to run spark-shell from the command prompt in Windows 7 (64-bit) returns The system cannot find the path specified.

However I can run that same command from within the directory where the spark-shell.exe is located (albeit with some errors), which leads me to believe that this is a PATH issue like most of the other posts regarding this problem on the internet. However...

Spark-shell works when called from directory:

Shell appears to be working:

From what I can tell, my PATH appears to be set correctly. Most of the solutions for this issue that I've come across involve fixing the %JAVA_HOME% system variable to point to the correct location and adding '%JAVA_HOME%/bin' to the PATH (along with the directory holding 'spark-shell.exe'), however both my JAVA_HOME variable and PATH variable appear to contain the required directories.

答:
Turns out this issue was being caused by a previously installed version of Spark on my computer. PySpark was already installed via "pip install PySpark" when I tried installing the standalone Spark client, and with two instances of Spark installed, running "spark-shell" created a conflict when both of these locations were being referenced.

So even though the PATH was set correctly, the fact that "spark-shell" was referencing a previous PySpark install AND a standalone Spark install was creating the issue.

I noticed when I ran "pyspark" from the command line, it returned two instances of "The system could not find the path specified." error.. which lead me to believe that pyspark/spark was installed in two locations, and could potentially cause an issue with resolving the PATH when I called "spark-shell".

I ran "pip uninstall pyspark", and then when I re-tried "spark-shell" from the command line it worked as expected!

ContentLicense: CC BY-SA 4.0


问:
Pandas- creating a table that inserts new rows based on column values?
I have a dataframe that has names of an item, data on it, and then competitor data all in one row:

```<code> name   value1   value2    ex_value1     ex_value2
 jim       0.4      0.6           0.7           0.3
 tim       0.2      0.8   0.766666667   0.233333333
 john        1        0           0.5           0.5
 paul      0.9      0.1   0.533333333   0.466666667
</code>```

What I want to do is create a new table that has indexes by name, but inserts new rows based on the competitor data, so that it shows jim, ex-jim, tim,ex-tim, etc:

```<code>   name       value1        value2
  jim               0.4           0.6
  tim               0.2           0.8
  john                1             0
  paul              0.9           0.1
  ex_jim            0.7           0.3
  ex_tim    0.766666667   0.233333333
  ex_john           0.5           0.5
  ex_paul   0.533333333   0.466666667
</code>```

How would I go about doing this? Would I have to set index on name, then insert new that way? Would I got about this through a loop? Appreciate guidance on this

答:
You could use a combination of melt and pivot

```<code>df2 = df.melt('name')
df2.loc[df2.variable.str.contains('ex'),'name'] = 'ex_' +df2.name
df2.variable = df2.variable.str.strip('ex_')
df2 = df2.pivot(index='name',columns='variable').reset_index()
df2.columns = df2.columns.droplevel(0)
</code>```

which gives you

```<code>variable             value1    value2
0          ex_jim  0.700000  0.300000
1         ex_john  0.500000  0.500000
2         ex_paul  0.533333  0.466667
3          ex_tim  0.766667  0.233333
4             jim  0.400000  0.600000
5            john  1.000000  0.000000
6            paul  0.900000  0.100000
7             tim  0.200000  0.800000
</code>```

Body:
I have a dataframe that has names of an item, data on it, and then competitor data all in one row:

 name   value1   value2    ex_value1     ex_value2
 jim       0.4      0.6           0.7           0.3
 tim       0.2      0.8   0.766666667   0.233333333
 john        1        0           0.5           0.5
 paul      0.9      0.1   0.533333333   0.466666667

What I want to do is create a new table that has indexes by name, but inserts new rows based on the competitor data, so that it shows jim, ex-jim, tim,ex-tim, etc:

   name       value1        value2
  jim               0.4           0.6
  tim               0.2           0.8
  john                1             0
  paul              0.9           0.1
  ex_jim            0.7           0.3
  ex_tim    0.766666667   0.233333333
  ex_john           0.5           0.5
  ex_paul   0.533333333   0.466666667

How would I go about doing this? Would I have to set index on name, then insert new that way? Would I got about this through a loop? Appreciate guidance on this

Body:
You could use a combination of melt and pivot

df2 = df.melt('name')
df2.loc[df2.variable.str.contains('ex'),'name'] = 'ex_' +df2.name
df2.variable = df2.variable.str.strip('ex_')
df2 = df2.pivot(index='name',columns='variable').reset_index()
df2.columns = df2.columns.droplevel(0)

which gives you

variable             value1    value2
0          ex_jim  0.700000  0.300000
1         ex_john  0.500000  0.500000
2         ex_paul  0.533333  0.466667
3          ex_tim  0.766667  0.233333
4             jim  0.400000  0.600000
5            john  1.000000  0.000000
6            paul  0.900000  0.100000
7             tim  0.200000  0.800000


问:
What type of NoSQL database is best suited to store hierarchical data?
What type of NoSQL database is best suited to store hierarchical data?

Say for example I want to store posts of a forum with a tree structure:

```<code>original post
 + re: original post
 + re: original post
   + re2: original post
     + re3: original post
   + re2: original post
</code>```

答:
Here's a non-answer for you. SQLServer 2008!!!!  It's great for recursive queries.  Or you can go the old fashioned route and store hierarchy data in a separate table to avoid recursion.

I think relational databases lend themselves very well to tree data. Both in query performance and ease of use.  With one caveat.... you will be inserting into an indexed table, and probably several other indexed tables every time someone makes a post. Insert performance could be an issue on a facebook caliber forum.

Body:
What type of NoSQL database is best suited to store hierarchical data?

Say for example I want to store posts of a forum with a tree structure:

original post
 + re: original post
 + re: original post
   + re2: original post
     + re3: original post
   + re2: original post


问:
"Call to a member function put() on null" in Laravel 5
Below I got my middleware that returns message to user

```<code>public function handle($request, Closure $next)
  {
      $error = [
        'title' => 'Brak dostępu',
        'description' => '123'
      ];
      $request->session->put('error', $error);

return $next($request);
  }
</code>```

Some notification is poping me up "Call to a member function put() on null" Any idea how to fix it?

答:
That is because it isn't the property session, its the method session:

```<code>$request->session()->.....
</code>```

Laravel 5.5 Docs - Session - Retrieving Data

Body:
Below I got my middleware that returns message to user

public function handle($request, Closure $next)
  {
      $error = [
        'title' => 'Brak dostępu',
        'description' => '123'
      ];
      $request->session->put('error', $error);

return $next($request);
  }

Some notification is poping me up "Call to a member function put() on null" Any idea how to fix it?

Body:
That is because it isn't the property session, its the method session:

$request->session()->.....

Laravel 5.5 Docs - Session - Retrieving Data


问:
I want to invite the member to team on tfs but getting error 'No identities found'
I am getting error "No identities found" when inserting member to my team. I've verified the email address is correct. Why am I seeing this text? How can i fix this?
why cannot found?</p>

答: You have to use an Active Directory account for on-premise TFS -- you can't provide a hotmail account.</p>


问:
View runs in split mode in PyCharm
I'm running Python, zmq code for a server and a client. I would like to see the runs(console messages) in a side-by-side mode (split mode) for better analysis of the interaction between the two.
It has the "split" mode between "Run" and "Terminal" and others but could not find split mode within the Runs category.
Were you able to see multiple runs in a side-by-side mode?
Is there any plugin or other way make it work?</p>

答: You can run one python file in the run window, and debug another python file but without any breakpoints.  This allows you to see the console outputs of two concurrently running python scripts in Pycharm.  Not ideal, but it's the best work-around I've found to this annoying problem.</p>

Title: View runs in split mode in PyCharm


问:
Android Emulator problems, CPU might not support virtualization?
I'm trying to get back into android programming on my new computer.

I installed everything using TheNewBoston's tutorials 1-4 on YouTube, but when I go in to my AVD manager to run the Nexus 5 API 21 x86 I get the following error:

```<code>emulator: ERROR: x86 emulation currently requires hardware acceleration!
Please ensure Intel HAXM is properly installed and usable.
CPU acceleration status: HAX kernel module is not installed!
</code>```

So naturally I googled around and found several threads with the same problem and solutions.

Error in launching AVD with AMD processor

Is one example and I also tried to manually install the "Intel x86 Emulator Accelerator (HAXM installer) where I got the following problem.

```<code>Failed to configure driver: unknown error. Failed to open driver
</code>```

So then I found this thread saying that my CPU might not support Virtualization, but I have no idea how to check if it is.

HAX kernel module is not installed

My CPU is an Intel(R) Core(TM) i5-3570K CPU @3.40 GHz. If it doesn't support Virtualization...what are my options? Can I still test my applications on a phone?

Thanks in advance.

答:
Don't worry your CPU does support virtualization. Please go to boot menu and enable your virtualization settings from there.
you'll be good to go then.</p>

Body:
I'm trying to get back into android programming on my new computer.

I installed everything using TheNewBoston's tutorials 1-4 on YouTube, but when I go in to my AVD manager to run the Nexus 5 API 21 x86 I get the following error:

emulator: ERROR: x86 emulation currently requires hardware acceleration!
Please ensure Intel HAXM is properly installed and usable.
CPU acceleration status: HAX kernel module is not installed!

So naturally I googled around and found several threads with the same problem and solutions.

Error in launching AVD with AMD processor

Is one example and I also tried to manually install the "Intel x86 Emulator Accelerator (HAXM installer) where I got the following problem.

Failed to configure driver: unknown error. Failed to open driver

So then I found this thread saying that my CPU might not support Virtualization, but I have no idea how to check if it is.

HAX kernel module is not installed

My CPU is an Intel(R) Core(TM) i5-3570K CPU @3.40 GHz. If it doesn't support Virtualization...what are my options? Can I still test my applications on a phone?

Thanks in advance.