Grouping types in a single project [duplicate]

This question already has an answer here:

  • Folder-by-type or Folder-by-feature 3 answers

I have many models in my project that are unrelated to each other. I wanted to group them but I wonder what’s better:

Folder/namespace per group

  • Group1.Constants, Group2.Constants
  • Group1.Models, Group2.Models
Group1/ ├── Models/ │   ├── Class1.cs │   ├── Class2.cs ├── Constants/ │   ├── Constants1.cs │   ├── Constants2.cs  

Folder/namespace per type

  • Constants.Group1, Constants.Group2
  • Models.Group1, Models.Group2
Models/ ├── Group1/ │   ├── Class1.cs │   ├── Class2.cs  Constants/ ├── Group1/ │   ├── Constants1.cs │   ├── Constants2.cs 

Which is better and why?

Note: I don’t want to put them in separate projects, as those types will be used only by 1 project.

Python Grouping csv by name

I’m converting the csv format to json format. Now I generated the json structure but I need to group the data by name.

student.csv file:

name,email,date,phone john,example.com,26/11/18,123 johnny,hello.com,12/08/18,123456 

Code:

import csv from collections import defaultdict  result2 = defaultdict(list) result = [] with open("student.csv", "r") as csv_ledger:     for row in csv.DictReader(csv_ledger, skipinitialspace=True):         result.append({             "name": row["name"],             "email": row["email"],             "items": [{                 "phone": row["phone"],                 "info": {"date": row["date"]},             }],         })      result2[row['name']].append(row['phone'])<---append whole items list      result2[row['name'],row['email']].append(row['items'])<---not support 

The result above code:

"john": [         "123"     ] 

Grouping comma-separated lines together

Okay so the problem is I have a file like this :

Case 1 ( 1st file ) :

abcd,1 abcd,21 abcd,122 abce,12 abcf,13 abcf,21 

Case 2 ( and another file like this ) :

abcd,1 abcd,21 abcd,122 

So, as you can see it’s sorted and in increasing order.

What I want to do is convert the first file to like this :

abcd 1,21,122 abce 12 abcf 13,21 

And similarly, for the second file like this :

abcd 1,21,122 

Now, I wrote a very ugly code with a lot of if’s to check whether the next line’s string before the comma is same as current line’s string so, if it is then do ….

It’s so badly written that, I wrote it myself around 6 months back and it took me around 3-4 minutes to understand why I did what I did in this code. Well in short it’s ugly, in case you would like to see, here it is ( also there’s a bug currently in here and since I needed a better way than this whole code so I didn’t sort it out, for the curious folks out there the bug is that it doesn’t print anything for the second case mentioned above and I know why ).

def clean_file(filePath, destination):     f = open(filePath, 'r')     data = f.read()     f.close()     curr_string = current_number = next_string = next_number = ""     current_numbers = ""     final_payload = ""     lines = data.split('\n')[:-1]     for i in range(len(lines)-1):         print(lines[i])         curr_line = lines[i]         next_line = lines[i+1]         curr_string, current_number = curr_line.split(',')         next_string, next_number = next_line.split(',')         if curr_string == next_string:             current_numbers += current_number + ","         else:             current_numbers += current_number    # check to avoid ',' in the end             final_payload += curr_string + " " + current_numbers + "\n"             current_numbers = ""     print(final_payload)     # For last line     if curr_string != next_string:         # Directly add it to the final_payload         final_payload += next_line + "\n"     else:         # Remove the newline, add a comma and then finally add a newline         final_payload = final_payload[:-1] + ","+next_number+"\n"     with open(destination, 'a') as f:         f.write(final_payload)  

Any better solutions ( I know there are many ppl who would write way better than this 😉 ).

Grouping items in a list into inner lists in java

I have a function that looks up in a list the elements which share same values in order to group them.

This is my Test Code to see the output samples:

class A {   Long id;   String name;   Object param;    A(Long id, String name, Object param) {     this.id = id;     this.name = name;     this.param = param;   }    @Override   public String toString() {     return "{\tid:" + id + ",\tname:" + name + ",\tparam:" + param + "}";   } }  public class ListsTest {    private final A a1 = new A(1L, "A", 100);   private final A a2 = new A(2L, "B", 200);   private final A a3 = new A(1L, "A", 300);   private final A a4 = new A(1L, "B", 400);    @Test   public void groupByIdAndName() throws IllegalAccessException, NoSuchFieldException {     List<A> aList = List.of(a1, a2, a3, a4);     System.out.println("groupByIdAndName");     System.out.println("Input: ---> " + aList);     List<List<A>> aGroupedBy = Lists.groupByFields(aList, "id", "name");     System.out.println("Output: --> " + aGroupedBy);     System.out.println("------------------------------------------------------------------------");     assertThat(aGroupedBy, is(List.of(List.of(a1, a3), List.of(a2), List.of(a4))));    }    @Test   public void groupById() throws IllegalAccessException, NoSuchFieldException {     List<A> aList = List.of(a1, a2, a3, a4);     System.out.println("groupById");     System.out.println("Input: ---> " + aList);     List<List<A>> aGroupedBy = Lists.groupByFields(aList, "id");     System.out.println("Output: --> " + aGroupedBy);     System.out.println("------------------------------------------------------------------------");     assertThat(aGroupedBy, is(List.of(List.of(a1, a3, a4), List.of(a2))));   }    @Test   public void groupByName() throws IllegalAccessException, NoSuchFieldException {     List<A> aList = List.of(a1, a2, a3, a4);     System.out.println("groupByName");     System.out.println("Input: ---> " + aList);     List<List<A>> aGroupedBy = Lists.groupByFields(aList, "name");     System.out.println("Output: --> " + aGroupedBy);     System.out.println("------------------------------------------------------------------------");     assertThat(aGroupedBy, is(List.of(List.of(a1, a3), List.of(a2, a4))));   } } 

Which outputs:

groupById

Input: —> [{ id:1, name:A, param:100}, { id:2, name:B, param:200}, { id:1, name:A, param:300}, { id:1, name:B, param:400}] Output: –> [[{ id:1, name:A, param:100}, { id:1, name:A, param:300}], [{ id:2, name:B, param:200}], [{ id:1, name:B, param:400}]]

Output: –> [[{ id:1, name:A, param:100}, { id:1, name:A, param:300}, { id:1, name:B, param:400}], [{ id:2, name:B, param:200}]]


groupByIdAndName

Input: —> [{ id:1, name:A, param:100}, { id:2, name:B, param:200}, { id:1, name:A, param:300}, { id:1, name:B, param:400}]

Output: –> [[{ id:1, name:A, param:100}, { id:1, name:A, param:300}], [{ id:2, name:B, param:200}], [{ id:1, name:B, param:400}]]


groupByName

Input: —> [{ id:1, name:A, param:100}, { id:2, name:B, param:200}, { id:1, name:A, param:300}, { id:1, name:B, param:400}]

Output: –> [[{ id:1, name:A, param:100}, { id:1, name:A, param:300}], [{ id:2, name:B, param:200}, { id:1, name:B, param:400}]]


The code I developed for it is the following:

public class Lists {    private static <T> Object getObjectFieldsHash(T obj, String... fields) throws NoSuchFieldException, IllegalAccessException {     List<Object> vals = new ArrayList<>();     for (String field: fields) {       Field f = obj.getClass().getDeclaredField(field);       f.setAccessible(true);       vals.add(f.get(obj));     }     return Objects.hash(vals); }    public static <T> List<List<T>> groupByFields(List<T> objects, String... fields ) throws NoSuchFieldException, IllegalAccessException {     List<List<T>> result = new ArrayList<>(); // Is it possible to create same type of original List instead of always ArrayList?     Map<Object, Integer> indexes = new HashMap<>();     for (T obj: objects) {       Object hash = getObjectFieldsHash(obj, fields);       indexes.computeIfAbsent(hash, (_unused) -> indexes.size()); // How can I remove _unused variable?       Integer nextIndex = indexes.get(hash);       if (nextIndex >= result.size()) { // Maybe I could use ==. Does it improve anything?          result.add(new ArrayList<T>()); // Is it possible to create same type of original List instead of always ArrayList?       }       result.get(nextIndex).add(obj);     }     return result;   } } 

Is there any way to improve this?

I’m thinking of:

  1. I can pass as argument any subtype of List, but I’m always returning ArrayLists
  2. I was forced to declare the _unused variable in my lambda function, or won’t compile, producing error: “Cannot infer functional interface type”
  3. Does using == instead of >= to check if I already created a sublist provide me any kind of improvement?
  4. I named this method groupByFields, but I feel like is the opposite of “flatMap” kind functions. Is there any concept which gives me a more standarized method name?

Android File Grouping Plugin

Пытаюсь разобраться с иерархией каталогов в Android Studio. Хотелось бы группировать файлы ресурсов по каталогам, но иерархия Android Studio не позволяет (в каталогах ресурсов все файлы должны быть на одном уровне). Наткнулся на данный плагин (Android File Grouping Plugin). И мне интересно услышать мнения людей по поводу данного плагина. Стоит ли его использовать или лучше давать нормальные имена ресурсов и через поиск находить нужный файл ?

Google sheets – grouping columns question

There are two spreadsheets with columns being grouped. In the first the grouping looks pretty standard – note that the +/- control is on the left of grouped columns:

first spreadsheet

And in the second – I accidentally made the +/- control appearing on the right: second spreadsheet

I don’t realize the repro steps for the second variant. What happened and how can I undo that?

Mojave Stacks feature: More specificity for grouping

I am trying to use Mojave’s new Stacks feature that can group files on the desktop. I have it set to group by “Kind”. It created a stack called “Documents”. But the contents are very heterogeneous: this stack absorbs everything from Markdown documents through Mathematica notebooks to MS Word files.

I would much rather have these types separated. Is this possible?

For my use case, it would be sufficient to make the system consider Mathematica notebooks not to be “documents” (and let it mix the rest of the types).

Grouping by two columns in a table

I'm trying to create a very simple messaging system for a website and I am trying to group conversations by from or to using a single SQL statement. I have simplified the statement I am trying to use below:

$ messages_query = "SELECT * FROM tbl_messages WHERE from_id='$ current_user' OR to_id='$ current_user' GROUP BY from_id, to_id ORDER BY message_date DESC";

But ofcourse the grouping is a bit off. How would I get it to group by sender/receiver?