kandi background
Explore Kits

collections | Collections Abstraction Library | Functional Programming library

 by   doctrine PHP Version: 1.6.7 License: MIT

 by   doctrine PHP Version: 1.6.7 License: MIT

Download this library from

kandi X-RAY | collections Summary

collections is a PHP library typically used in Programming Style, Functional Programming applications. collections has no bugs, it has no vulnerabilities, it has a Permissive License and it has medium support. You can download it from GitHub.
Collections Abstraction Library
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • collections has a medium active ecosystem.
  • It has 5192 star(s) with 157 fork(s). There are 27 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 19 open issues and 40 have been closed. On average issues are closed in 218 days. There are 19 open pull requests and 0 closed requests.
  • It has a neutral sentiment in the developer community.
  • The latest version of collections is 1.6.7
collections Support
Best in #Functional Programming
Average in #Functional Programming
collections Support
Best in #Functional Programming
Average in #Functional Programming

quality kandi Quality

  • collections has 0 bugs and 0 code smells.
collections Quality
Best in #Functional Programming
Average in #Functional Programming
collections Quality
Best in #Functional Programming
Average in #Functional Programming

securitySecurity

  • collections has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • collections code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
collections Security
Best in #Functional Programming
Average in #Functional Programming
collections Security
Best in #Functional Programming
Average in #Functional Programming

license License

  • collections is licensed under the MIT License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
collections License
Best in #Functional Programming
Average in #Functional Programming
collections License
Best in #Functional Programming
Average in #Functional Programming

buildReuse

  • collections releases are available to install and integrate.
  • Installation instructions are not available. Examples and code snippets are available.
  • collections saves you 371 person hours of effort in developing the same functionality from scratch.
  • It has 886 lines of code, 162 functions and 12 files.
  • It has high code complexity. Code complexity directly impacts maintainability of the code.
collections Reuse
Best in #Functional Programming
Average in #Functional Programming
collections Reuse
Best in #Functional Programming
Average in #Functional Programming
Top functions reviewed by kandi - BETA

kandi has reviewed collections and discovered the below as its top functions. This is intended to give you an instant insight into collections implemented functionality, and help decide if they suit your requirements.

  • Walks down a comparison .
    • Get the value of an object field .
      • Find elements matching criteria
        • Walks down an Expression AST node .
          • Partitions the collection using the given truth test .
            • Appends an AND WHERE expression .
              • Appends an OR WHERE expression
                • Initializes this class .
                  • Returns the last element in the collection
                    • Returns the list of expressions .

                      Get all kandi verified functions for this library.

                      Get all kandi verified functions for this library.

                      collections Key Features

                      Collections Abstraction Library

                      collections Examples and Code Snippets

                      See all related Code Snippets

                      v1.1.0

                      copy iconCopydownload iconDownload
                        $criteria->andWhere($criteria->expr()->contains('property', 'Foo'));
                      

                      Python type hint for Iterable[str] that isn't str

                      copy iconCopydownload iconDownload
                      from typing import Union
                      ## Heading ##
                      def operate_on_files(file_paths: Union[TypeOneName, TypeTwoName, etc.]) -> None:
                          for path in file_paths:
                              ...
                      
                      ## Heading ##
                      def operate_on_files(file_paths: TypeOneName | TypeTwoName | etc.) -> None:
                          for path in file_paths:
                              ...
                      
                      from typing import Union
                      ## Heading ##
                      def operate_on_files(file_paths: Union[TypeOneName, TypeTwoName, etc.]) -> None:
                          for path in file_paths:
                              ...
                      
                      ## Heading ##
                      def operate_on_files(file_paths: TypeOneName | TypeTwoName | etc.) -> None:
                          for path in file_paths:
                              ...
                      

                      in VS Code ImportError: cannot import name 'Mapping' from 'collections'

                      copy iconCopydownload iconDownload
                      from collections import Mapping
                      
                      from collections.abc import Mapping
                      
                      from collections import Mapping
                      
                      from collections.abc import Mapping
                      
                      try:
                          from collections.abc import Mapping
                      except ImportError:
                          from collections import Mapping
                      

                      Emulate BTreeMap::pop_last in stable Rust

                      copy iconCopydownload iconDownload
                      // Safety: if key uses shared interior mutability, the comparison function
                      // must not use it. (E.g. it is not allowed to call borrow_mut() on a
                      // Rc<RefCell<X>> inside the key). It is extremely unlikely that such a
                      // key exists, but it's possible to write it, so this must be marked unsafe.
                      unsafe fn map_pop_last<K, V>(m: &mut BTreeMap<K, V>) -> Option<(K, V)>
                      where
                          K: Ord,
                      {
                          // We make a shallow copy of the key in the map, and pass a
                          // reference to the copy to BTreeMap::remove_entry(). Since
                          // remove_entry() is not dropping the key/value pair (it's returning
                          // it), our shallow copy will remain throughout the lifetime of
                          // remove_entry(), even if the key contains references.
                          let (last_key_ref, _) = m.iter().next_back()?;
                          let last_key_copy = ManuallyDrop::new(std::ptr::read(last_key_ref));
                          m.remove_entry(&last_key_copy)
                      }
                      
                      fn map_pop_last<K, V>(m: &mut BTreeMap<K, V>) -> Option<(K, V)>
                      where
                          K: Ord,
                      {
                          let mut temp = BTreeMap::new();
                          std::mem::swap(m, &mut temp);
                          let mut iter = temp.into_iter();
                          let ret = iter.next_back();
                          m.extend(iter);
                          ret  
                      }
                      

                      Java sorting list of array vs sorting list of list

                      copy iconCopydownload iconDownload
                      points.sort(null); // the same as   points.sort(Comparator.naturalOrder()); 
                      
                      Collections.sort(points, (a, b) -> {
                          int xCompare = a[0].compareTo(b[0];
                          if (xCompare != 0) {
                              return xCompare;
                          }
                          retirm a[1].compareTo(b[1];
                      });
                      
                      class Point {
                          public int x;
                          public int y;
                      }
                      
                      Collections.sort(points, (a, b) -> {
                          int xCompare = a[0].compareTo(b[0];
                          if (xCompare != 0) {
                              return xCompare;
                          }
                          retirm a[1].compareTo(b[1];
                      });
                      
                      class Point {
                          public int x;
                          public int y;
                      }
                      

                      django rest Error - AttributeError: module 'collections' has no attribute 'MutableMapping'

                      copy iconCopydownload iconDownload
                      Warning (from warnings module):
                        File "<pyshell#1>", line 1
                      DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop working
                      
                      FROM python:3.9.7-alpine3.14
                      
                      ...
                      
                      Warning (from warnings module):
                        File "<pyshell#1>", line 1
                      DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated since Python 3.3, and in 3.10 it will stop working
                      
                      FROM python:3.9.7-alpine3.14
                      
                      ...
                      

                      Merge two files and add computation and sorting the updated data in python

                      copy iconCopydownload iconDownload
                      import pandas as pd
                      
                      
                      def read_file(fn):
                          """
                          Read file fn and convert data into a dict of dict.
                          data = {pname1: {grp: grp1, pname: pname1, cnt: cnt1, cat: cat1},
                                  pname2: {gpr: grp2, ...} ...}
                          """
                          data = {}
                          with open(fn, 'r') as f:
                              for lines in f:
                                  line = lines.rstrip()
                                  grp, pname, cnt, cat = line.split(maxsplit=3)
                                  data.update({pname: {'grp': float(grp.replace(',', '')), 'pname': pname, 'cnt': int(cnt), 'cat': cat}})
                                  
                          return data
                      
                      
                      def process_data(oldfn, newfn):  
                          """
                          Read old and new files, update the old file based on new file.
                          Save output to text, and csv files.
                          """
                          # Get old and new data in dict.
                          old = read_file(oldfn)
                          new = read_file(newfn)
                      
                          # Update old data based on new data
                          u_data = {}
                          for ko, vo in old.items():
                              if ko in new:
                                  n = new[ko]
                                  
                                  # Update cnt.
                                  old_cnt = vo['cnt']
                                  new_cnt = n['cnt']
                                  u_cnt = old_cnt + new_cnt
                      
                                  # cnt change, if old is zero we set it to 1 to avoid division by zero error.
                                  tmp_old_cnt = 1 if old_cnt == 0 else old_cnt
                                  cnt_change = 100 * (new_cnt - tmp_old_cnt) / tmp_old_cnt
                      
                                  # grp change
                                  old_grp = vo['grp']
                                  new_grp = n['grp']
                                  grp_change = 100 * (new_grp - old_grp) / old_grp
                      
                                  u_data.update({ko: {'grp': n['grp'], 'pname': n['pname'], 'cnt': u_cnt, 'cat': n['cat'],
                                                      'cnt_change%': round(cnt_change, 2), 'grp_change%': round(grp_change, 2)}})
                      
                          # add new data to u_data, that is not in old data
                          for kn, vn in new.items():
                              if kn not in old:        
                                  # Since this is new item its old cnt is zero, we set it to 1 to avoid division by zero error.
                                  old_cnt = 1
                                  new_cnt = vn['cnt']
                                  cnt_change = 100 * (new_cnt - old_cnt) / old_cnt        
                      
                                  # grp change is similar to cnt change
                                  old_grp = 1
                                  new_grp = vn['grp']
                                  grp_change = 100 * (new_grp - old_grp) / old_grp
                                  
                                  # Update new columns.
                                  vn.update({'cnt_change%': round(cnt_change, 2), 'grp_change%': round(grp_change, 2)})        
                                  u_data.update({kn: vn})
                                  
                          # Create new data mydata list from u_data, and only extract the dict value.
                          mydata = []
                          for _, v in u_data.items():
                              mydata.append(v)
                              
                          # Convert mydata into pandas dataframe to easier manage the data.
                          df = pd.DataFrame(mydata)
                          df = df.sort_values(by=['cnt'], ascending=False)  # sort on cnt column
                          
                          # Save to csv file.
                          df.to_csv('output.csv', index=False)
                          
                          # Save to text file.
                          with open('output.txt', 'w') as w:
                              w.write(f'{df.to_string(index=False)}')
                              
                          # Print in console.    
                          print(df.to_string(index=False))
                      
                      
                      # Start
                      oldfn = 'F:/Tmp/oldFile.txt'
                      newfn = 'F:/Tmp/newFile.txt'
                      process_data(oldfn, newfn)
                      
                         grp                    pname  cnt                      cat  cnt_change%  grp_change%
                      8739.0 6ea059a29eccecee4e250414   62   MAXIMACASH (MAXCAS...)      2900.00       219.06
                       138.0 1c6bc8e962427deb4106ae06   58          Charge (Charge)       525.00       -68.49
                       860.0 31b5c07636dab8f0909dbd2d   46 Buff Unicorn (BUFFUN...)       566.67       272.29
                       200.0 9e4d81c8fc15870b15aef8dc   33          BABY BNB (BBNB)       900.00       -28.32
                        20.0 5esdsds2sd15870b15aef8dc   30       CharliesAngel (CA)      2900.00      1900.00
                      1560.0 c15e89f2149bcc0cbd5fb204   24          HUH_Token (HUH)       400.00        11.75
                      
                         grp                    pname  cnt                      cat  cnt_change%  grp_change%
                      8739.0 6ea059a29eccecee4e250414   62   MAXIMACASH (MAXCAS...)      2900.00       219.06
                       138.0 1c6bc8e962427deb4106ae06   58          Charge (Charge)       525.00       -68.49
                       860.0 31b5c07636dab8f0909dbd2d   46 Buff Unicorn (BUFFUN...)       566.67       272.29
                       200.0 9e4d81c8fc15870b15aef8dc   33          BABY BNB (BBNB)       900.00       -28.32
                        20.0 5esdsds2sd15870b15aef8dc   30       CharliesAngel (CA)      2900.00      1900.00
                      1560.0 c15e89f2149bcc0cbd5fb204   24          HUH_Token (HUH)       400.00        11.75
                      
                      grp,pname,cnt,cat,cnt_change%,grp_change%
                      8739.0,6ea059a29eccecee4e250414,62,MAXIMACASH (MAXCAS...),2900.0,219.06
                      138.0,1c6bc8e962427deb4106ae06,58,Charge (Charge),525.0,-68.49
                      860.0,31b5c07636dab8f0909dbd2d,46,Buff Unicorn (BUFFUN...),566.67,272.29
                      200.0,9e4d81c8fc15870b15aef8dc,33,BABY BNB (BBNB),900.0,-28.32
                      20.0,5esdsds2sd15870b15aef8dc,30,CharliesAngel (CA),2900.0,1900.0
                      1560.0,c15e89f2149bcc0cbd5fb204,24,HUH_Token (HUH),400.0,11.75
                      
                      import pandas as pd
                      
                      
                      def read_file(fn):
                          """
                          Read file fn and convert data into a dict of dict.
                          data = {pname1: {grp: grp1, pname: pname1, cnt: cnt1, cat: cat1},
                                  pname2: {gpr: grp2, ...} ...}
                          """
                          data = {}
                          with open(fn, 'r') as f:
                              for lines in f:
                                  line = lines.rstrip()
                                  grp, pname, cnt, cat = line.split(maxsplit=3)
                                  data.update({pname: {'grp': float(grp.replace(',', '')), 'pname': pname, 'cnt': int(cnt), 'cat': cat}})
                                  
                          return data
                      
                      
                      def process_data(oldfn, newfn):  
                          """
                          Read old and new files, update the old file based on new file.
                          Save output to text, and csv files.
                          """
                          # Get old and new data in dict.
                          old = read_file(oldfn)
                          new = read_file(newfn)
                      
                          # Update old data based on new data
                          u_data = {}
                          for ko, vo in old.items():
                              if ko in new:
                                  n = new[ko]
                                  
                                  # Update cnt.
                                  old_cnt = vo['cnt']
                                  new_cnt = n['cnt']
                                  u_cnt = old_cnt + new_cnt
                      
                                  # cnt change, if old is zero we set it to 1 to avoid division by zero error.
                                  tmp_old_cnt = 1 if old_cnt == 0 else old_cnt
                                  cnt_change = 100 * (new_cnt - tmp_old_cnt) / tmp_old_cnt
                      
                                  # grp change
                                  old_grp = vo['grp']
                                  new_grp = n['grp']
                                  grp_change = 100 * (new_grp - old_grp) / old_grp
                      
                                  u_data.update({ko: {'grp': n['grp'], 'pname': n['pname'], 'cnt': u_cnt, 'cat': n['cat'],
                                                      'cnt_change%': round(cnt_change, 2), 'grp_change%': round(grp_change, 2)}})
                      
                          # add new data to u_data, that is not in old data
                          for kn, vn in new.items():
                              if kn not in old:        
                                  # Since this is new item its old cnt is zero, we set it to 1 to avoid division by zero error.
                                  old_cnt = 1
                                  new_cnt = vn['cnt']
                                  cnt_change = 100 * (new_cnt - old_cnt) / old_cnt        
                      
                                  # grp change is similar to cnt change
                                  old_grp = 1
                                  new_grp = vn['grp']
                                  grp_change = 100 * (new_grp - old_grp) / old_grp
                                  
                                  # Update new columns.
                                  vn.update({'cnt_change%': round(cnt_change, 2), 'grp_change%': round(grp_change, 2)})        
                                  u_data.update({kn: vn})
                                  
                          # Create new data mydata list from u_data, and only extract the dict value.
                          mydata = []
                          for _, v in u_data.items():
                              mydata.append(v)
                              
                          # Convert mydata into pandas dataframe to easier manage the data.
                          df = pd.DataFrame(mydata)
                          df = df.sort_values(by=['cnt'], ascending=False)  # sort on cnt column
                          
                          # Save to csv file.
                          df.to_csv('output.csv', index=False)
                          
                          # Save to text file.
                          with open('output.txt', 'w') as w:
                              w.write(f'{df.to_string(index=False)}')
                              
                          # Print in console.    
                          print(df.to_string(index=False))
                      
                      
                      # Start
                      oldfn = 'F:/Tmp/oldFile.txt'
                      newfn = 'F:/Tmp/newFile.txt'
                      process_data(oldfn, newfn)
                      
                         grp                    pname  cnt                      cat  cnt_change%  grp_change%
                      8739.0 6ea059a29eccecee4e250414   62   MAXIMACASH (MAXCAS...)      2900.00       219.06
                       138.0 1c6bc8e962427deb4106ae06   58          Charge (Charge)       525.00       -68.49
                       860.0 31b5c07636dab8f0909dbd2d   46 Buff Unicorn (BUFFUN...)       566.67       272.29
                       200.0 9e4d81c8fc15870b15aef8dc   33          BABY BNB (BBNB)       900.00       -28.32
                        20.0 5esdsds2sd15870b15aef8dc   30       CharliesAngel (CA)      2900.00      1900.00
                      1560.0 c15e89f2149bcc0cbd5fb204   24          HUH_Token (HUH)       400.00        11.75
                      
                         grp                    pname  cnt                      cat  cnt_change%  grp_change%
                      8739.0 6ea059a29eccecee4e250414   62   MAXIMACASH (MAXCAS...)      2900.00       219.06
                       138.0 1c6bc8e962427deb4106ae06   58          Charge (Charge)       525.00       -68.49
                       860.0 31b5c07636dab8f0909dbd2d   46 Buff Unicorn (BUFFUN...)       566.67       272.29
                       200.0 9e4d81c8fc15870b15aef8dc   33          BABY BNB (BBNB)       900.00       -28.32
                        20.0 5esdsds2sd15870b15aef8dc   30       CharliesAngel (CA)      2900.00      1900.00
                      1560.0 c15e89f2149bcc0cbd5fb204   24          HUH_Token (HUH)       400.00        11.75
                      
                      grp,pname,cnt,cat,cnt_change%,grp_change%
                      8739.0,6ea059a29eccecee4e250414,62,MAXIMACASH (MAXCAS...),2900.0,219.06
                      138.0,1c6bc8e962427deb4106ae06,58,Charge (Charge),525.0,-68.49
                      860.0,31b5c07636dab8f0909dbd2d,46,Buff Unicorn (BUFFUN...),566.67,272.29
                      200.0,9e4d81c8fc15870b15aef8dc,33,BABY BNB (BBNB),900.0,-28.32
                      20.0,5esdsds2sd15870b15aef8dc,30,CharliesAngel (CA),2900.0,1900.0
                      1560.0,c15e89f2149bcc0cbd5fb204,24,HUH_Token (HUH),400.0,11.75
                      
                      import pandas as pd
                      
                      
                      def read_file(fn):
                          """
                          Read file fn and convert data into a dict of dict.
                          data = {pname1: {grp: grp1, pname: pname1, cnt: cnt1, cat: cat1},
                                  pname2: {gpr: grp2, ...} ...}
                          """
                          data = {}
                          with open(fn, 'r') as f:
                              for lines in f:
                                  line = lines.rstrip()
                                  grp, pname, cnt, cat = line.split(maxsplit=3)
                                  data.update({pname: {'grp': float(grp.replace(',', '')), 'pname': pname, 'cnt': int(cnt), 'cat': cat}})
                                  
                          return data
                      
                      
                      def process_data(oldfn, newfn):  
                          """
                          Read old and new files, update the old file based on new file.
                          Save output to text, and csv files.
                          """
                          # Get old and new data in dict.
                          old = read_file(oldfn)
                          new = read_file(newfn)
                      
                          # Update old data based on new data
                          u_data = {}
                          for ko, vo in old.items():
                              if ko in new:
                                  n = new[ko]
                                  
                                  # Update cnt.
                                  old_cnt = vo['cnt']
                                  new_cnt = n['cnt']
                                  u_cnt = old_cnt + new_cnt
                      
                                  # cnt change, if old is zero we set it to 1 to avoid division by zero error.
                                  tmp_old_cnt = 1 if old_cnt == 0 else old_cnt
                                  cnt_change = 100 * (new_cnt - tmp_old_cnt) / tmp_old_cnt
                      
                                  # grp change
                                  old_grp = vo['grp']
                                  new_grp = n['grp']
                                  grp_change = 100 * (new_grp - old_grp) / old_grp
                      
                                  u_data.update({ko: {'grp': n['grp'], 'pname': n['pname'], 'cnt': u_cnt, 'cat': n['cat'],
                                                      'cnt_change%': round(cnt_change, 2), 'grp_change%': round(grp_change, 2)}})
                      
                          # add new data to u_data, that is not in old data
                          for kn, vn in new.items():
                              if kn not in old:        
                                  # Since this is new item its old cnt is zero, we set it to 1 to avoid division by zero error.
                                  old_cnt = 1
                                  new_cnt = vn['cnt']
                                  cnt_change = 100 * (new_cnt - old_cnt) / old_cnt        
                      
                                  # grp change is similar to cnt change
                                  old_grp = 1
                                  new_grp = vn['grp']
                                  grp_change = 100 * (new_grp - old_grp) / old_grp
                                  
                                  # Update new columns.
                                  vn.update({'cnt_change%': round(cnt_change, 2), 'grp_change%': round(grp_change, 2)})        
                                  u_data.update({kn: vn})
                                  
                          # Create new data mydata list from u_data, and only extract the dict value.
                          mydata = []
                          for _, v in u_data.items():
                              mydata.append(v)
                              
                          # Convert mydata into pandas dataframe to easier manage the data.
                          df = pd.DataFrame(mydata)
                          df = df.sort_values(by=['cnt'], ascending=False)  # sort on cnt column
                          
                          # Save to csv file.
                          df.to_csv('output.csv', index=False)
                          
                          # Save to text file.
                          with open('output.txt', 'w') as w:
                              w.write(f'{df.to_string(index=False)}')
                              
                          # Print in console.    
                          print(df.to_string(index=False))
                      
                      
                      # Start
                      oldfn = 'F:/Tmp/oldFile.txt'
                      newfn = 'F:/Tmp/newFile.txt'
                      process_data(oldfn, newfn)
                      
                         grp                    pname  cnt                      cat  cnt_change%  grp_change%
                      8739.0 6ea059a29eccecee4e250414   62   MAXIMACASH (MAXCAS...)      2900.00       219.06
                       138.0 1c6bc8e962427deb4106ae06   58          Charge (Charge)       525.00       -68.49
                       860.0 31b5c07636dab8f0909dbd2d   46 Buff Unicorn (BUFFUN...)       566.67       272.29
                       200.0 9e4d81c8fc15870b15aef8dc   33          BABY BNB (BBNB)       900.00       -28.32
                        20.0 5esdsds2sd15870b15aef8dc   30       CharliesAngel (CA)      2900.00      1900.00
                      1560.0 c15e89f2149bcc0cbd5fb204   24          HUH_Token (HUH)       400.00        11.75
                      
                         grp                    pname  cnt                      cat  cnt_change%  grp_change%
                      8739.0 6ea059a29eccecee4e250414   62   MAXIMACASH (MAXCAS...)      2900.00       219.06
                       138.0 1c6bc8e962427deb4106ae06   58          Charge (Charge)       525.00       -68.49
                       860.0 31b5c07636dab8f0909dbd2d   46 Buff Unicorn (BUFFUN...)       566.67       272.29
                       200.0 9e4d81c8fc15870b15aef8dc   33          BABY BNB (BBNB)       900.00       -28.32
                        20.0 5esdsds2sd15870b15aef8dc   30       CharliesAngel (CA)      2900.00      1900.00
                      1560.0 c15e89f2149bcc0cbd5fb204   24          HUH_Token (HUH)       400.00        11.75
                      
                      grp,pname,cnt,cat,cnt_change%,grp_change%
                      8739.0,6ea059a29eccecee4e250414,62,MAXIMACASH (MAXCAS...),2900.0,219.06
                      138.0,1c6bc8e962427deb4106ae06,58,Charge (Charge),525.0,-68.49
                      860.0,31b5c07636dab8f0909dbd2d,46,Buff Unicorn (BUFFUN...),566.67,272.29
                      200.0,9e4d81c8fc15870b15aef8dc,33,BABY BNB (BBNB),900.0,-28.32
                      20.0,5esdsds2sd15870b15aef8dc,30,CharliesAngel (CA),2900.0,1900.0
                      1560.0,c15e89f2149bcc0cbd5fb204,24,HUH_Token (HUH),400.0,11.75
                      
                      import pandas as pd
                      
                      
                      def read_file(fn):
                          """
                          Read file fn and convert data into a dict of dict.
                          data = {pname1: {grp: grp1, pname: pname1, cnt: cnt1, cat: cat1},
                                  pname2: {gpr: grp2, ...} ...}
                          """
                          data = {}
                          with open(fn, 'r') as f:
                              for lines in f:
                                  line = lines.rstrip()
                                  grp, pname, cnt, cat = line.split(maxsplit=3)
                                  data.update({pname: {'grp': float(grp.replace(',', '')), 'pname': pname, 'cnt': int(cnt), 'cat': cat}})
                                  
                          return data
                      
                      
                      def process_data(oldfn, newfn):  
                          """
                          Read old and new files, update the old file based on new file.
                          Save output to text, and csv files.
                          """
                          # Get old and new data in dict.
                          old = read_file(oldfn)
                          new = read_file(newfn)
                      
                          # Update old data based on new data
                          u_data = {}
                          for ko, vo in old.items():
                              if ko in new:
                                  n = new[ko]
                                  
                                  # Update cnt.
                                  old_cnt = vo['cnt']
                                  new_cnt = n['cnt']
                                  u_cnt = old_cnt + new_cnt
                      
                                  # cnt change, if old is zero we set it to 1 to avoid division by zero error.
                                  tmp_old_cnt = 1 if old_cnt == 0 else old_cnt
                                  cnt_change = 100 * (new_cnt - tmp_old_cnt) / tmp_old_cnt
                      
                                  # grp change
                                  old_grp = vo['grp']
                                  new_grp = n['grp']
                                  grp_change = 100 * (new_grp - old_grp) / old_grp
                      
                                  u_data.update({ko: {'grp': n['grp'], 'pname': n['pname'], 'cnt': u_cnt, 'cat': n['cat'],
                                                      'cnt_change%': round(cnt_change, 2), 'grp_change%': round(grp_change, 2)}})
                      
                          # add new data to u_data, that is not in old data
                          for kn, vn in new.items():
                              if kn not in old:        
                                  # Since this is new item its old cnt is zero, we set it to 1 to avoid division by zero error.
                                  old_cnt = 1
                                  new_cnt = vn['cnt']
                                  cnt_change = 100 * (new_cnt - old_cnt) / old_cnt        
                      
                                  # grp change is similar to cnt change
                                  old_grp = 1
                                  new_grp = vn['grp']
                                  grp_change = 100 * (new_grp - old_grp) / old_grp
                                  
                                  # Update new columns.
                                  vn.update({'cnt_change%': round(cnt_change, 2), 'grp_change%': round(grp_change, 2)})        
                                  u_data.update({kn: vn})
                                  
                          # Create new data mydata list from u_data, and only extract the dict value.
                          mydata = []
                          for _, v in u_data.items():
                              mydata.append(v)
                              
                          # Convert mydata into pandas dataframe to easier manage the data.
                          df = pd.DataFrame(mydata)
                          df = df.sort_values(by=['cnt'], ascending=False)  # sort on cnt column
                          
                          # Save to csv file.
                          df.to_csv('output.csv', index=False)
                          
                          # Save to text file.
                          with open('output.txt', 'w') as w:
                              w.write(f'{df.to_string(index=False)}')
                              
                          # Print in console.    
                          print(df.to_string(index=False))
                      
                      
                      # Start
                      oldfn = 'F:/Tmp/oldFile.txt'
                      newfn = 'F:/Tmp/newFile.txt'
                      process_data(oldfn, newfn)
                      
                         grp                    pname  cnt                      cat  cnt_change%  grp_change%
                      8739.0 6ea059a29eccecee4e250414   62   MAXIMACASH (MAXCAS...)      2900.00       219.06
                       138.0 1c6bc8e962427deb4106ae06   58          Charge (Charge)       525.00       -68.49
                       860.0 31b5c07636dab8f0909dbd2d   46 Buff Unicorn (BUFFUN...)       566.67       272.29
                       200.0 9e4d81c8fc15870b15aef8dc   33          BABY BNB (BBNB)       900.00       -28.32
                        20.0 5esdsds2sd15870b15aef8dc   30       CharliesAngel (CA)      2900.00      1900.00
                      1560.0 c15e89f2149bcc0cbd5fb204   24          HUH_Token (HUH)       400.00        11.75
                      
                         grp                    pname  cnt                      cat  cnt_change%  grp_change%
                      8739.0 6ea059a29eccecee4e250414   62   MAXIMACASH (MAXCAS...)      2900.00       219.06
                       138.0 1c6bc8e962427deb4106ae06   58          Charge (Charge)       525.00       -68.49
                       860.0 31b5c07636dab8f0909dbd2d   46 Buff Unicorn (BUFFUN...)       566.67       272.29
                       200.0 9e4d81c8fc15870b15aef8dc   33          BABY BNB (BBNB)       900.00       -28.32
                        20.0 5esdsds2sd15870b15aef8dc   30       CharliesAngel (CA)      2900.00      1900.00
                      1560.0 c15e89f2149bcc0cbd5fb204   24          HUH_Token (HUH)       400.00        11.75
                      
                      grp,pname,cnt,cat,cnt_change%,grp_change%
                      8739.0,6ea059a29eccecee4e250414,62,MAXIMACASH (MAXCAS...),2900.0,219.06
                      138.0,1c6bc8e962427deb4106ae06,58,Charge (Charge),525.0,-68.49
                      860.0,31b5c07636dab8f0909dbd2d,46,Buff Unicorn (BUFFUN...),566.67,272.29
                      200.0,9e4d81c8fc15870b15aef8dc,33,BABY BNB (BBNB),900.0,-28.32
                      20.0,5esdsds2sd15870b15aef8dc,30,CharliesAngel (CA),2900.0,1900.0
                      1560.0,c15e89f2149bcc0cbd5fb204,24,HUH_Token (HUH),400.0,11.75
                      
                      from convtools import conversion as c
                      from convtools.contrib.tables import Table
                      
                      # your percentage change calculation
                      def c_change(column_name):
                          return c.if_(
                              c.and_(
                                  c.col(f"{column_name}_LEFT"),
                                  c.col(f"{column_name}_RIGHT").is_not(None),
                              ),
                              (
                                  (c.col(f"{column_name}_RIGHT") - c.col(f"{column_name}_LEFT"))
                                  / c.col(f"{column_name}_LEFT")
                                  * 100.0
                              ).pipe(round, 2),
                              None,
                          )
                      
                      prepare_columns = {
                          "COLUMN_0": c.col("COLUMN_0").as_type(float),
                          "COLUMN_2": c.col("COLUMN_2").as_type(float),
                      }
                      dialect = Table.csv_dialect(delimiter="\t")
                      
                      sorted_rows = sorted(
                          Table.from_csv("tmp1.csv", dialect=dialect)
                          .update(**prepare_columns)
                          .join(
                              Table.from_csv(
                                  "tmp2.csv",
                                  dialect=dialect,
                              ).update(**prepare_columns),
                              on=["COLUMN_1", "COLUMN_3"],
                              how="full",
                          )
                          .update(
                              COLUMN_4=c_change("COLUMN_2"),
                              COLUMN_5=c_change("COLUMN_0"),
                              COLUMN_2=c.col("COLUMN_2_RIGHT"),
                              COLUMN_0=c.col("COLUMN_0_RIGHT"),
                          )
                          .take(
                              "COLUMN_0",
                              "COLUMN_1",
                              "COLUMN_2",
                              "COLUMN_3",
                              "COLUMN_4",
                              "COLUMN_5",
                          )
                          .into_iter_rows(tuple),
                          key=lambda row: row[2],
                          reverse=True,
                      )
                      
                      Table.from_rows(sorted_rows).into_csv("tmp_result.csv", dialect=dialect)
                      
                      
                      COLUMN_0    COLUMN_1    COLUMN_2    COLUMN_3    COLUMN_4    COLUMN_5
                      8739.0  6ea059a29eccecee4e250414    60.0    MAXIMACASH (MAXCAS...)  2900.0  219.06
                      138.0   1c6bc8e962427deb4106ae06    50.0    Charge (Charge) 525.0   -68.49
                      860.0   31b5c07636dab8f0909dbd2d    40.0    Buff Unicorn (BUFFUN...)    566.67  272.29
                      200.0   9e4d81c8fc15870b15aef8dc    30.0    BABY BNB (BBNB) 900.0   -28.32
                      20.0    5esdsds2sd15870b15aef8dc    30.0    CharliesAngel (CA)      
                      1560.0  c15e89f2149bcc0cbd5fb204    20.0    HUH_Token (HUH) 400.0   11.75
                      
                      from convtools import conversion as c
                      from convtools.contrib.tables import Table
                      
                      # your percentage change calculation
                      def c_change(column_name):
                          return c.if_(
                              c.and_(
                                  c.col(f"{column_name}_LEFT"),
                                  c.col(f"{column_name}_RIGHT").is_not(None),
                              ),
                              (
                                  (c.col(f"{column_name}_RIGHT") - c.col(f"{column_name}_LEFT"))
                                  / c.col(f"{column_name}_LEFT")
                                  * 100.0
                              ).pipe(round, 2),
                              None,
                          )
                      
                      prepare_columns = {
                          "COLUMN_0": c.col("COLUMN_0").as_type(float),
                          "COLUMN_2": c.col("COLUMN_2").as_type(float),
                      }
                      dialect = Table.csv_dialect(delimiter="\t")
                      
                      sorted_rows = sorted(
                          Table.from_csv("tmp1.csv", dialect=dialect)
                          .update(**prepare_columns)
                          .join(
                              Table.from_csv(
                                  "tmp2.csv",
                                  dialect=dialect,
                              ).update(**prepare_columns),
                              on=["COLUMN_1", "COLUMN_3"],
                              how="full",
                          )
                          .update(
                              COLUMN_4=c_change("COLUMN_2"),
                              COLUMN_5=c_change("COLUMN_0"),
                              COLUMN_2=c.col("COLUMN_2_RIGHT"),
                              COLUMN_0=c.col("COLUMN_0_RIGHT"),
                          )
                          .take(
                              "COLUMN_0",
                              "COLUMN_1",
                              "COLUMN_2",
                              "COLUMN_3",
                              "COLUMN_4",
                              "COLUMN_5",
                          )
                          .into_iter_rows(tuple),
                          key=lambda row: row[2],
                          reverse=True,
                      )
                      
                      Table.from_rows(sorted_rows).into_csv("tmp_result.csv", dialect=dialect)
                      
                      
                      COLUMN_0    COLUMN_1    COLUMN_2    COLUMN_3    COLUMN_4    COLUMN_5
                      8739.0  6ea059a29eccecee4e250414    60.0    MAXIMACASH (MAXCAS...)  2900.0  219.06
                      138.0   1c6bc8e962427deb4106ae06    50.0    Charge (Charge) 525.0   -68.49
                      860.0   31b5c07636dab8f0909dbd2d    40.0    Buff Unicorn (BUFFUN...)    566.67  272.29
                      200.0   9e4d81c8fc15870b15aef8dc    30.0    BABY BNB (BBNB) 900.0   -28.32
                      20.0    5esdsds2sd15870b15aef8dc    30.0    CharliesAngel (CA)      
                      1560.0  c15e89f2149bcc0cbd5fb204    20.0    HUH_Token (HUH) 400.0   11.75
                      

                      Java Map.getOrDefault with bounded wildcard

                      copy iconCopydownload iconDownload
                      static <K1, K2, V, M extends Map<K2, V>> Map<K2, V> getOrEmpty(Map<K1, M> mapOfMaps, K1 key) {
                        Map<K2, V> submap = mapOfMaps.get(key);
                        return submap != null ? submap : Collections.emptyMap();
                      }
                      
                      Map<String, Integer> result = getOrEmpty(mapOfMaps,"aaa");
                      
                      static <K1, K2, V, M extends Map<K2, V>> Map<K2, V> getOrEmpty(Map<K1, M> mapOfMaps, K1 key) {
                        Map<K2, V> submap = mapOfMaps.get(key);
                        return submap != null ? submap : Collections.emptyMap();
                      }
                      
                      Map<String, Integer> result = getOrEmpty(mapOfMaps,"aaa");
                      
                      Map<String, ? extends Map<String, Integer>> mapOfMaps = new HashMap<>();
                      Map<String, Map<String, Integer>> view = Collections.unmodifiableMap(mapOfMaps);
                      Map<String, Integer> map = view.getOrDefault("foo", Collections.emptyMap());
                      
                      Map<String, Integer> map = Collections.<String, Map<String, Integer>>
                          unmodifiableMap(mapOfMaps).getOrDefault("foo", Collections.emptyMap());
                      
                      Map<String, ? extends Number> map = new HashMap<String, Integer>();
                      Map<String, ? extends Number> map = new HashMap<String, Double>();
                      
                      // compile-time error, could require a Double or any other Number-type
                      Number i = map.getOrDefault("foo", (Number)Integer.MAX_VALUE);
                      
                      Map<String, ? extends Map<String, Integer>> mapOfMaps = new HashMap<>();
                      Map<String, Map<String, Integer>> view = Collections.unmodifiableMap(mapOfMaps);
                      Map<String, Integer> map = view.getOrDefault("foo", Collections.emptyMap());
                      
                      Map<String, Integer> map = Collections.<String, Map<String, Integer>>
                          unmodifiableMap(mapOfMaps).getOrDefault("foo", Collections.emptyMap());
                      
                      Map<String, ? extends Number> map = new HashMap<String, Integer>();
                      Map<String, ? extends Number> map = new HashMap<String, Double>();
                      
                      // compile-time error, could require a Double or any other Number-type
                      Number i = map.getOrDefault("foo", (Number)Integer.MAX_VALUE);
                      
                      Map<String, ? extends Map<String, Integer>> mapOfMaps = new HashMap<>();
                      Map<String, Map<String, Integer>> view = Collections.unmodifiableMap(mapOfMaps);
                      Map<String, Integer> map = view.getOrDefault("foo", Collections.emptyMap());
                      
                      Map<String, Integer> map = Collections.<String, Map<String, Integer>>
                          unmodifiableMap(mapOfMaps).getOrDefault("foo", Collections.emptyMap());
                      
                      Map<String, ? extends Number> map = new HashMap<String, Integer>();
                      Map<String, ? extends Number> map = new HashMap<String, Double>();
                      
                      // compile-time error, could require a Double or any other Number-type
                      Number i = map.getOrDefault("foo", (Number)Integer.MAX_VALUE);
                      
                      Map<String, ? extends Map<String, Integer>> mapOfMaps = new HashMap<>();
                      Map<String, Map<String, Integer>> view = Collections.unmodifiableMap(mapOfMaps);
                      Map<String, Integer> map = view.getOrDefault("foo", Collections.emptyMap());
                      
                      Map<String, Integer> map = Collections.<String, Map<String, Integer>>
                          unmodifiableMap(mapOfMaps).getOrDefault("foo", Collections.emptyMap());
                      
                      Map<String, ? extends Number> map = new HashMap<String, Integer>();
                      Map<String, ? extends Number> map = new HashMap<String, Double>();
                      
                      // compile-time error, could require a Double or any other Number-type
                      Number i = map.getOrDefault("foo", (Number)Integer.MAX_VALUE);
                      

                      Is the key order the same for OrderedDict and dict?

                      copy iconCopydownload iconDownload
                      if sys.version_info[:2] >= (3, 6):
                        OrderedDict = dict
                      else:
                        from collections import OrderedDict as _OrderedDict
                      
                        class OrderedDict(_OrderedDict):
                          __eq__ = dict.__eq__
                          __ne__ = dict.__ne__
                      
                      from collections import OrderedDict
                      
                      d = { "a" : 1, "c" : 2}
                      
                      od = OrderedDict(d.items())
                      
                      print(list(reversed(od)))
                      print(list(reversed(d)))
                      
                      ['c', 'a']
                      
                      Traceback (most recent call last):
                        File "path/to/file", line 8, in <module>
                          print(list(reversed(d)))
                      TypeError: 'dict' object is not reversible
                      
                      from collections import OrderedDict
                      
                      d = { "a" : 1, "c" : 2}
                      
                      od = OrderedDict(d.items())
                      
                      print(list(reversed(od)))
                      print(list(reversed(d)))
                      
                      ['c', 'a']
                      
                      Traceback (most recent call last):
                        File "path/to/file", line 8, in <module>
                          print(list(reversed(d)))
                      TypeError: 'dict' object is not reversible
                      

                      Cant read data from collection in MongoDB Atlas Trigger

                      copy iconCopydownload iconDownload
                      exports = async function(changeEvent) {
                        const mongodb = context.services.get("Cluster0");
                        const db = mongodb.db("TestDB");
                        var collection = db.collection("Config");
                        config_docs = await collection.find().toArray(); 
                        console.log(JSON.stringify(config_docs));
                      
                      };
                      
                      exports = function(changeEvent) {
                        const mongodb = context.services.get("Cluster0");
                        const db = mongodb.db("TestDB");
                        var collection = db.collection("Config");
                        collection.find().toArray().then(config_docs => {
                          console.log(JSON.stringify(config_docs));
                        });
                      };
                      
                      exports = async function(changeEvent) {
                        const mongodb = context.services.get("Cluster0");
                        const db = mongodb.db("TestDB");
                        var collection = db.collection("Config");
                        config_docs = await collection.find().toArray(); 
                        console.log(JSON.stringify(config_docs));
                      
                      };
                      
                      exports = function(changeEvent) {
                        const mongodb = context.services.get("Cluster0");
                        const db = mongodb.db("TestDB");
                        var collection = db.collection("Config");
                        collection.find().toArray().then(config_docs => {
                          console.log(JSON.stringify(config_docs));
                        });
                      };
                      

                      What's the point of using [object instance].__self__?

                      copy iconCopydownload iconDownload
                      >>> a = []
                      >>> a.append.__self__ is a
                      True
                      
                      d = collections.defaultdict(list)
                      for item in seq:
                          d[key(item)].append(item)
                      
                      return {k: v.__self__ for k, v in d.items()}
                      
                      d = collections.defaultdict(list)
                      for item in seq:
                          d[key(item)].append(item)
                      
                      return {k: v.__self__ for k, v in d.items()}
                      

                      See all related Code Snippets

                      Community Discussions

                      Trending Discussions on collections
                      • Python type hint for Iterable[str] that isn't str
                      • in VS Code ImportError: cannot import name 'Mapping' from 'collections'
                      • Emulate BTreeMap::pop_last in stable Rust
                      • Java sorting list of array vs sorting list of list
                      • django rest Error - AttributeError: module 'collections' has no attribute 'MutableMapping'
                      • Merge two files and add computation and sorting the updated data in python
                      • Java Map.getOrDefault with bounded wildcard
                      • Is the key order the same for OrderedDict and dict?
                      • Cant read data from collection in MongoDB Atlas Trigger
                      • What's the point of using [object instance].__self__?
                      Trending Discussions on collections

                      QUESTION

                      Python type hint for Iterable[str] that isn't str

                      Asked 2022-Mar-29 at 06:43

                      In Python, is there a way to distinguish between strings and other iterables of strings?

                      A str is valid as an Iterable[str] type, but that may not be the correct input for a function. For example, in this trivial example that is intended to operate on sequences of filenames:

                      from typing import Iterable
                      
                      def operate_on_files(file_paths: Iterable[str]) -> None:
                          for path in file_paths:
                              ...
                      

                      Passing in a single filename would produce the wrong result but would not be caught by type checking. I know that I can check for string or byte types at runtime, but I want to know if it's possible to catch silly mistakes like that with a type-checking tool.

                      I've looked over the collections.abc module and there doesn't seem to be any abc that would include typical iterables (e.g. lists, tuples) but exclude strings. Similarly, for the typing module, there doesn't seem to be a type for iterables that don't include strings.

                      ANSWER

                      Answered 2022-Mar-29 at 06:36
                      As of March 2022, the answer is no.

                      This issue has been discussed since at least July 2016. On a proposal to distinguish between str and Iterable[str], Guido van Rossum writes:

                      Since str is a valid iterable of str this is tricky. Various proposals have been made but they don't fit easily in the type system.

                      You'll need to list out all of the types that you want your functions to accept explicitly, using Union (pre-3.10) or | (3.10 and higher).

                      e.g. For pre-3.10, use:

                      from typing import Union
                      ## Heading ##
                      def operate_on_files(file_paths: Union[TypeOneName, TypeTwoName, etc.]) -> None:
                          for path in file_paths:
                              ...
                      

                      For 3.10 and higher, use:

                      ## Heading ##
                      def operate_on_files(file_paths: TypeOneName | TypeTwoName | etc.) -> None:
                          for path in file_paths:
                              ...
                      

                      If you happen to be using Pytype, it will not treat str as an Iterable[str] (as pointed out by Kelly Bundy). But, this behavior is typechecker-specific, and isn't widely supported in other typecheckers.

                      Source https://stackoverflow.com/questions/71656644

                      Community Discussions, Code Snippets contain sources that include Stack Exchange Network

                      Vulnerabilities

                      No vulnerabilities reported

                      Install collections

                      You can download it from GitHub.
                      PHP requires the Visual C runtime (CRT). The Microsoft Visual C++ Redistributable for Visual Studio 2019 is suitable for all these PHP versions, see visualstudio.microsoft.com. You MUST download the x86 CRT for PHP x86 builds and the x64 CRT for PHP x64 builds. The CRT installer supports the /quiet and /norestart command-line switches, so you can also script it.

                      Support

                      For any new features, suggestions and bugs create an issue on GitHub. If you have any questions check and ask questions on community page Stack Overflow .

                      DOWNLOAD this Library from

                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                      over 430 million Knowledge Items
                      Find more libraries
                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                      Explore Kits

                      Save this library and start creating your kit

                      Share this Page

                      share link
                      Reuse Pre-built Kits with collections
                      Consider Popular Functional Programming Libraries
                      Try Top Libraries by doctrine
                      Compare Functional Programming Libraries with Highest Support
                      Compare Functional Programming Libraries with Highest Quality
                      Compare Functional Programming Libraries with Highest Security
                      Compare Functional Programming Libraries with Permissive License
                      Compare Functional Programming Libraries with Highest Reuse
                      Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
                      over 430 million Knowledge Items
                      Find more libraries
                      Reuse Solution Kits and Libraries Curated by Popular Use Cases
                      Explore Kits

                      Save this library and start creating your kit

                      • © 2022 Open Weaver Inc.