Gordon  Matlala

Gordon Matlala

1669605360

How ArrayList Class in Kotlin Works with Practical Code Examples

ArrayList class in Kotlin explained with code examples

The ArrayList class in Kotlin can be used to create a variable of ArrayList type.

An ArrayList type is a dynamic implementation of the array data type that allows you to add and remove element(s) from the array.

This means that the size of an ArrayList type can also increase or decrease dynamically.

Creating an ArrayList variable

To create an ArrayList instance, you can use the arrayListOf() function and assign the return to a variable.

The following example creates an ArrayList of Int type named myArrayList:

val myArrayList = arrayListOf(1, 2, 3)

println(myArrayList) // [1, 2, 3]

You can also declare the variable type as an ArrayList with a specific generic as shown below:

val myArrayList: ArrayList<Int> = arrayListOf(1, 2, 3)

Finally, you can also declare an empty ArrayList of a specific type like this:

val myArrayList = ArrayList<Int>()

println(myArrayList) // []

Once you declare an ArrayList variable, you can add, remove, or get an element from a specific index.

Let’s learn how to add a new element first.

Kotlin ArrayList adding new element(s)

To add a new element to an ArrayList variable, you can use the add() or addAll() method from the ArrayList class.

The add() method adds a specified element to the end of the ArrayList:

val myArrayList = arrayListOf(1, 2, 3)

myArrayList.add(77)
println(myArrayList) // [1, 2, 3, 77]

myArrayList.add(102)
println(myArrayList) // [1, 2, 3, 77, 102]

The addAll() method is used to add all elements of a collection (or list) to the end of the ArrayList.

The following example adds a List named myList to an ArrayList named numbers:

val numbers = arrayListOf(1, 2, 3)
val myList = listOf(55, 179)

numbers.addAll(myList)
println(numbers) // [1, 2, 3, 55, 179]

Next, let’s look at how to remove elements from an ArrayList.

Kotlin ArrayList removing element(s)

Kotlin ArrayList class has multiple methods that you can use to remove element(s) from its instance.

Some of these remove methods are as shown below:

  • clear()
  • remove()
  • removeAll()
  • retainAll()
  • removeLast()

The clear() method will remove all elements from an ArrayList as shown below:

val myArrayList = arrayListOf(1, 2, 3)

println(myArrayList) // [1, 2, 3]
myArrayList.clear()

println(myArrayList) // []

The remove() method will remove the element you specify as its argument.

When the ArrayList contains multiple identical elements, only the element at the lowest index will be removed.

When the element isn’t found, the method simply does nothing:

val myArrayList = arrayListOf(1, 2, 3, 1)

myArrayList.remove(1)
println(myArrayList) // [2, 3, 1]

myArrayList.remove(20)
println(myArrayList) // [2, 3, 1]

The remove() method also returns true when an element is removed. Otherwise, it returns false.

You don’t need to capture the return value if you don’t use it.

The removeAll() method accepts a list as its argument, and it removes all elements in an ArrayList that are identical to the ones in the list.

Here’s an example of the removeAll() method in action:

val myArrayList = arrayListOf(1, 2, 3, 1)
val myList = listOf(1, 2, 3)

myArrayList.removeAll(myList)
println(myArrayList) // []

As you can see from the above example, the removeAll() method will also remove all duplicates of elements that are in the list.

The retainAll() method is the opposite of the removeAll() method.

It will remove all elements that are not present in the list:

val myArrayList = arrayListOf(1, 2, 3, 1)
val myList = listOf(2, 3)

myArrayList.retainAll(myList)
println(myArrayList) // [2, 3]

Finally, the removeLast() method allows you to remove the element at the last index of the ArrayList variable.

Take a look at the following example:

val myArrayList = arrayListOf(1, 2, 3, 44, 99)

myArrayList.removeLast()
println(myArrayList) // [1, 2, 3, 44]

Kotlin ArrayList set() method

The set() method replaces the element at a certain index with another element.

The method requires two arguments:

  • The index where you want to set the new value
  • The element you want to set in the list

Here’s how to use the set() method:

val myArrayList = arrayListOf(1, 2, 3, 44, 99)

myArrayList.set(2, 88)
println(myArrayList) // [1, 2, 88, 44, 99]

Alternatively, you can also replace the set call with indexing operator assignment as shown below:

myArrayList[2] = 88

Kotlin ArrayList get() method

The get() method of the ArrayList class allows you to fetch an element at a certain index from your list.

You need to specify the index as an argument to the method as shown below:

val myArrayList = arrayListOf(1, 2, 3, 44, 99)
val element = myArrayList.get(3)

println(element) // 44

Just like the set() method, you can also replace the get method call with indexing operator assignment as follows:

val element = myArrayList[3]

And that’s how you can fetch a specific element from an ArrayList variable.

For more information on the ArrayList class, you can visit Kotlin ArrayList documentation.

Original article source at: https://sebhastian.com/

#kotlin #work #array #list 

How ArrayList Class in Kotlin Works with Practical Code Examples

How to Implement A Linked List Data Structure using JavaScript

JavaScript linked list data structure in five easy steps (code example included)

The linked list data structure is one of the fundamental data structures for computer programming.

Implementing a linked list using JavaScript is one of the most popular interview questions for software development related jobs.

This tutorial will help you to understand how the linked list data structure works and how you can implement the data structure using JavaScript in five easy steps.

The finished linked list implementation code can be found in the following GitHub Gist file.

You can download the file and run it using NodeJS on your local computer with the following command:

$ node linked-list
3
10
9
8

Let’s start with a quick introduction to the linked list first.

How linked list data structure works

A linked list is a representation of a list of values like an array, but each item in the list consists of a single object that has two properties:

  • The value property stored inside the object
  • The next property that points to the next object

The linked list data structure value can be of any valid JavaScript data types (string, number, boolean, object, etc)

A linked list usually also has two special pointers that refer to the first and last node in the list. They are called head and tail respectively.

Here’s an illustration of a typical linked list:

Linked list data structure illustratedLinked list data structure illustrated

When implemented, a linked list looks like a list of object that’s linked together through the next property value.

Take a look at the following basic linked list example that has three items:

{
  head: {
    value: 7, // first value
    next: {
      value: false, // second value
      next: {
        value: "A string", // third value
        next: null
      }
    }
  }
}

While a linked list looks similar to an array, a linked list is slower because it doesn’t store the index of its values, making random access at a specific index unavailable without traversing the entire linked list from the head to the tail.

Linked list types

There are three known types of linked list data structure:

  • Singly linked list where each node only has the next pointer
  • Doubly linked list where each node as both next and previous pointer
  • Circular linked list where the tail node points to the head node, creating a circle.

A circular linked list can be a singly or doubly linked list.

Now that you’ve learned how the data structure works, let’s learn how to implement a linked list using JavaScript next.

This tutorial will focus on implementing a singly, non-circular linked list.

Implementing a linked list using JavaScript

The linked list that you’re going to implement in this tutorial will have the ability to insert and remove nodes both from the head and the tail pointer.

It will also store the current length of the linked list so that you can easily check the size of the list like an array.

To implement a linked list using JavaScript, you can follow these 5 easy steps:

  • Create a function for creating a new Node object
  • Create the LinkedList class with the proper constructor
  • Create the insert() and print() methods
  • Create the remove() method to remove nodes
  • Create the methods to remove and insert from the head

Alright, let’s start with the first step and create a function for creating a new node object.

Creating the list node with a function

A linked list node can be implemented in JavaScript by using a function that returns an object as follows:

function createNode(value) {
  return {
    value: value,
    next: null,
  };
}

Now each time you need to create a node object, you just call the createNode() function above and pass the desired value as its argument:

let newNode = createNode("Hello");

console.log(newNode);
// { value: 'Hello', next: null }

You can also implement the node as a JavaScript class as follows:

class Node {
  constructor(value) {
    this.value = value;
    this.next = null;
  }
}

let newNode = new Node("World");
console.log(newNode);
// Node { value: 'World', next: null }

But I personally prefer to use a function over a class, so I’ll use the function implementation for the rest of this tutorial. You are free to use class if you want to though.

Writing the LinkedList class

Next, let’s start writing the LinkedList class implementation with the following constructor:

class LinkedList {
  constructor() {
    this.head = null;
    this.tail = null;
    this.length = 0;
  }
}

A new instance of the LinkedList object will have the head and tail pointers refer to the null value, while the length property will start at 0.

These values will be updated as you insert and remove nodes from the instance.

Creating the insert() and print() methods

With the LinkedList class ready, let’s add a method to insert a new node into the class.

First, create an insert() method that accepts a single parameter:

  • The value of the new node

The syntax of the function is as shown below:

insert(value) {}

First, you need to increment the length property by one. Then, you need to create a new node that will be inserted into the list.

insert(value) {
  this.length++;
  let newNode = createNode(value); // or use new Node(value);
}

After that, check on the value of the tail property. If the value is not null, then you need to do the following:

  • Point the tail.next property to the newNode object
  • Point the tail property to the newNode object
  • Return the newNode object to the caller

When the value of tail is null, it means that the linked list is still empty, so you need to assign the newNode object to the head and tail pointers.

The full code for the insert() method is as follows:

insert(value) {
  this.length++;
  let newNode = createNode(value);

  if (this.tail) {
    this.tail.next = newNode;
    this.tail = newNode;
    return newNode;
  }

  this.head = this.tail = newNode;
  return newNode;
}

Now that you can insert new values into the class instance, let’s add a print() method to see what’s inside the instance.

To print the linked list, you need to create a loop using a while statement from the head node.

If the current node is not null, then print the value property and assign the current.next property to current:

print() {
  let current = this.head;
  while (current) {
    console.log(current.value);
    current = current.next;
  }
}

Now you can try inserting and printing your linked list:

const linkedList = new LinkedList();

linkedList.insert(7);
linkedList.insert(true);
linkedList.insert(20);
linkedList.print(); // 7 true 20

You have both the insert() and print() methods work. Great job!

Removing nodes from the linked list

Now it’s time to add the remove() method to the LinkedList class.

First, the remove() methods needs to check if the tail pointer is not null.

When the tail pointer is null, you can simply return undefined to the methods caller:

remove() {
  if (this.tail) {
    // code omitted ...
  }
  return undefined;
}

When the tail pointer refers to a valid node, then it’s time to execute the code that will remove the node.

The steps to remove the last node is as follows:

  • Decrement the length property
  • Search for the node that has the next property points to the tail node
  • Set the tail to point to the previous node
  • Set the tail.next value to null

Here’s the complete code for the remove() methods:

remove() {
  if (this.tail) {
    this.length--;

    const tailNode = this.tail;

    // search for the node before tail
    let currentNode = this.head;

    // The while loop stops when the node next to tail node is found
    while (currentNode.next != tailNode) {
      currentNode = currentNode.next;
    }


    const beforeTail = currentNode;
    this.tail = beforeTail;
    this.tail.next = null;

    return tailNode;
  }
  return undefined;
}

Now you should be able to remove nodes from a linked list object.

You can stop for a break here, and let’s learn how to insert and remove nodes from the head next when you’re ready.

Creating methodss to insert and remove from the head

To make your linked list implementation more sophisticated, you can add methodss that will insert and remove nodes from the head instead of the tail.

Let’s write a new methods named insertHead() to insert a new node from the head.

The insertHead() methods works just like the insert() methods, but instead of changing the tail and tail.next pointer, you change the newNode.next property to point to the current this.head node and point this.head to the newNode

The code will be as follows:

insertHead(value) {
  this.length++;
  let newNode = createNode(value);

  if (this.head) {
    newNode.next = this.head;
    this.head = newNode;
    return newNode;
  }

  this.head = this.tail = newNode;
  return newNode;
}

Next, you need to create the removeHead() methods that removes a node from the head pointer.

To remove a node from the head, you just need to point this.head pointer to the head.next node:

removeHead() {
  if (this.head) {
    this.length--;
    const removedNode = this.head;
    this.head = this.head.next;
    return removedNode;
  }
  return undefined;
}

And with that, you can remove nodes from the head index. Nice work!

Bonus: Add methods to insert and remove a node at a specific index

While there’s nothing wrong with the linked list implementation we’ve created so far, you can still extend the functionalities of your linked list implementation by adding two more methods.

These methods are called insertIndex() and removeIndex() methods, and they allow you to insert and remove a node at a specific index inside your linked list data structure.

Let’s start with the insertIndex() function. This method needs to have two parameters:

  • The value parameter for the new node’s value
  • The index parameter for the index where the node will be inserted

Write the method syntax as follows:

insertIndex(value, index) {}

First, you need to make sure that the value of the index parameter is smaller than the length value of the linked list.

This is required because the method won’t be able to work properly when the value of index is equal to or higher than the length.

You need to throw an error and stop the method execution inside the if block as shown below:

if (index >= this.length) {
  throw new Error("Insert index out of bounds");
}

If you need to learn more about JavaScript throw statement, then you can check out another tutorial I’ve written here:

JavaScript throw statement guide

Next, if the index value is actually zero, then you can call the insertHead() method instead:

if (index === 0) {
  return this.insertHead(value);
}

Finally, when the index is not 0, it’s time to start writing the actual code to change your linked list instance.

To insert a new node at a specific index, JavaScript needs to scan the list from the first index and find two nodes:

  • The current node at the specified index
  • The node located the previous index

The code to find the currentNode and the previousNode looks as follows:

let previousNode = null;
let currentNode = this.head;
for (let i = 0; i < index; i++) {
  previousNode = currentNode;
  currentNode = currentNode.next;
}

A for statement is used in the code above to quickly traverse the list and grab the desired nodes. This is made possible because we have checked the index value at the beginning of the method.

Without checking if the index value is smaller than the length value, the for loop will cause both previousNode and currentNode value to be null and you won’t be able to add the new node in the right place.

Next, you need to call the createNode() method to create a newNode out of the value argument passed into the method.

const newNode = createNode(value);

Point the newNode.next property to the currentNode and previousNode.next to the newNode:

newNode.next = currentNode;
previousNode.next = newNode;

Finally, increment the length property and return the newNode to the method caller as follows:

this.length++;
return newNode;

Now your insertIndex() method is finished. Try add a new node on a specific index and print the list. You’ll see the new node added to the right index:

const linkedList = new LinkedList();

linkedList.insert(6);
linkedList.insert(7);
linkedList.insert(8);
linkedList.insertIndex(20, 1);

console.log(linkedList.length); // 4
linkedList.print(); // 6 20 7 8

From the output above, you can see that the node with value 20 is added right at index 1. Great!

Remove a node at a specific index

Now that you’ve learned how to add a new node at a specific index, removing a node at a specific index will be easy.

First, you need to write the removeIndex() method that accepts one parameter:

  • The index value to remove the node

The method syntax will be like this:

removeIndex(index) {}

Just like with insertIndex(), you need to start with making sure the value of the index parameter is smaller than the length value:

if (index >= this.length) {
  throw new Error("Remove index out of bounds");
}

Next, check if the index is equal to zero, and call the removeHead() method if it is:

if (index === 0) {
  return this.removeHead();
}

Then, find the previousNode and the currentNode values using a for statement as follows:

let previousNode = null;
let currentNode = this.head;
for (let i = 0; i < index; i++) {
  previousNode = currentNode;
  currentNode = currentNode.next;
}

Once you find the values, assign the currentNode.next property as the value of the previousNode.next property, decrement the length value, and return the removed node to the method caller:

previousNode.next = currentNode.next;
this.length--;
return currentNode;

And now the removeIndex() method is finished. You can test the method using the following snippets:

const linkedList = new LinkedList();

linkedList.insert(7);
linkedList.insert(8);
linkedList.insert(9);
linkedList.insert(10);
linkedList.removeIndex(2); // remove 9
console.log(linkedList.length); // 3
linkedList.print(); // 7 8 10

The node at index 2 above is removed, reducing the length and re-arranging the stored data.

You have just added two advanced methods to your linked list implementation. Well done! 👍

Here’s the GitHub Gist link again in case you need to compare it with your code.

Conclusion

With this tutorial, you’ve learned how the linked list data structure works and how to implement one using JavaScript.

You’ve also learned how to create a node object using both JavaScript class and function keywords.

The traditional way to create a node is by creating a new instance of the Node class, but I’d recommend you use the createNode() methods instead because methods are cleaner and simpler.

Next, you can learn about doubly linked list here:

Implementing doubly linked list using JavaScript

Thank you for reading, I hope you’ve learned something new from this tutorial 😉

Original article source at: https://sebhastian.com/

#javascript #list #datastructure 

How to Implement A Linked List Data Structure using JavaScript
Elian  Harber

Elian Harber

1667468220

A Curated List Of Articles Complaining That Go Isn't Good Enough

What's this

This repository is a list of articles that complain about golang's imperfection.

Motivation

Seems like complaining about go's flaws is becoming a trend. Any newbie must have a chance to read all the go-is-bad arguments before they go too far. So here it is.

What it's for

This repo is not aimed to offend or insult someone (at least not more than each author does it in its article), especially golang itself, its authors and the community. It is for educational purpose only. Any contributor can have an absolutely different point of view.

I don't think anyone would deny that go has weaknesses: it certainly has. But how do you know, is it really a language design flaw or is it just you, doing something completely wrong? This list here to help you quickly answer the question.

How to use it

You're writing some code. And suddenly you understand you need something that language can't give you. You go here and check if you're the one with that issue or not. If it's a common issue, it'll be here. Then you decide what to do: choose another tool for your task or go find a better solution or a workaround.

The List

Reverse complaints index

It's a reverse complaints index, generated by https://github.com/ksimka/go-is-not-good/blob/master/generator.go (thanks to @capoferro)

Get involved

Feel free to add a PR with a new or old article you found on the internet. The structure is simple, just look at existing entries. Run make and check in the resulting README.md along with your updated entries.json.

{
    "URL": "https://kaushalsubedi.com/blog/2015/11/10/golang-sucks-heres-why/",
    "Author": "Kaushal Subedi",
    "Year":  2015,
    "Complaints":[
        "no generics",
        "slow json parsing",
        "bad dependency management",
        "no subpackages"
    ]
}

TODO

  • merge complaints with the same ideas under the same names (make the complaints list smaller)
  • sort reverse index by the number of articles which have that complain (popular complains to the top)

Download Details:

Author: ksimka
Source Code: https://github.com/ksimka/go-is-not-good 

#go #golang #list #articles 

A Curated List Of Articles Complaining That Go Isn't Good Enough
Gordon  Matlala

Gordon Matlala

1667275140

Gravity: Minimal is The New Cool

Gravity

Minimal, Content Based, Liberal Jekyll theme for sharingyour awesome ideas.


INSTALLATION

Dependencies

Gravity uses Jekyll and it's built-in SCSS compiler for the associated CSS, so the first thing you'll need is Jekyll itself:

$ gem install jekyll

In case you don't have the bundler gem installed already, you can install it as follows:

$ gem install bundler

For pagination, Gravity uses the jekyll-paginate gem :

$ gem install jekyll-paginate

USAGE

Once you have the required gems, you can go ahead and clone the Gravity repository or download a zip of the master branch.

Run :

$ jekyll serve

Jekyll should now be generating your content!


ADDING POSTS

The theme by default ships with starter posts located in _posts/. Delete these posts and add your content to the _posts folder to see them being served up by Jekyll. This would be a good guide to getting started on writing posts using Jekyll. We've added a concise guide below:

  • Create a .markdown file inside _posts folder.
  • Name the file according to the format YY-MM-DD-[short name for your post].
  • 2016-03-30-i-love-design.markdown
  • Write the Front Matter and content in the file.

FORMAT

---
layout: post | default | page
title: String POST TITLE
date: Time Stamp
categories: String | Array of Strings CATEGORY / CATEGORIES
---

---
layout: post
title: "The One with the Blackout"
date: 2016-03-30 19:45:31 +0530
categories: ["life", friends]
---

CREATE PAGES

  • Create a .md file in the root directory.
  • Name the file with the desired page link name. about.md design.md
  • Write the Front Matter and content in the file.

FORMAT

---
layout: page
title: String TITLE OF THE WEBPAGE
permalink: / String / PERMALINK FOR THE WEBPAGE
tagline: String OPTIONAL GRAVITY FEATURE : TAGLINE FOR THE PAGE
---

---
layout: page
title: "Science"
permalink: /science/
tagline: "Humanity is overrated."
---

Introducing

ARCHIVE PAGES

You can display a list of all the posts corresponding to a particular category on a standalone page using the ARCHIVE layout.

  • Create a .md file in the root directory.
  • Name the file. Preferred name will be the name of the category. *life.md
  • Write the Front Matter and content in the file.

FORMAT

---
layout: archive ARCHIVE PAGE LAYOUT
title: String TITLE OF THE WEBPAGE
permalink: / String / PERMALINK FOR THE WEBPAGE
tagline: String TAGLINE FOR THE PAGE
category: String NAME OF THE CATEGORY OF WHICH THE PAGE WILL SHOW POSTS
---

---
layout: archive
title: "Design"
permalink: "Design"
tagline: "It's all about perception"
category: "design"
---

DIRECTORY STRUCTURE

├── css                                         # => Output of the combined SASS files
│   └── style.scss
├── _includes                                   # => Contains partials that can be used with your layouts
│   ├── footer.html
│   ├── header.html
│   ├── head.html
│   ├── icon-github.html
│   ├── icon-github.svg
│   ├── icon-twitter.html
│   └── icon-twitter.svg
├── _layouts                                    # => Layout related HTML files
│   ├── archive.html
│   ├── default.html
│   ├── page.html
│   └── post.html
├── _posts                                      # => posts, dynamic content. Follow the format: YEAR-MONTH-DAY-title.MARKUP
│   ├── 2016-03-30-design-stories.markdown
│   ├── 2016-03-30-science0.markdown
│   ├── 2016-03-30-science.markdown
│   └── 2016-03-30-welcome-to-jekyll.markdown
└── _sass                                       # => SASS partials for styling
|   ├── _base.scss
|   ├── _layout.scss
|   └── _syntax-highlighting.scss
├── about.md
├── _config.yml                                 # => Configuration options or flags for your site go here
├── design.md
├── download.md
├── feed.xml
├── index.html
├── LICENSE.txt                                 # => Licensing information
├── README.md
└── science.md

If there's any issue you are facing in setting up this theme I'm there for you. Just create an issue in this repository (http://github.com/hemangsk/Gravity), (https://help.github.com/articles/creating-an-issue/) and I'll get back to you asap.

Welcome to Gravity


Download Details:

Author: Hemangsk
Source Code: https://github.com/hemangsk/Gravity 
License: MIT license

#jekyll #theme #list 

Gravity: Minimal is The New Cool

Yallist: Yet another Linked List

Yallist

Yet Another Linked List

There are many doubly-linked list implementations like it, but this one is mine.

For when an array would be too big, and a Map can't be iterated in reverse order. 

basic usage

var yallist = require('yallist')
var myList = yallist.create([1, 2, 3])
myList.push('foo')
myList.unshift('bar')
// of course pop() and shift() are there, too
console.log(myList.toArray()) // ['bar', 1, 2, 3, 'foo']
myList.forEach(function (k) {
  // walk the list head to tail
})
myList.forEachReverse(function (k, index, list) {
  // walk the list tail to head
})
var myDoubledList = myList.map(function (k) {
  return k + k
})
// now myDoubledList contains ['barbar', 2, 4, 6, 'foofoo']
// mapReverse is also a thing
var myDoubledListReverse = myList.mapReverse(function (k) {
  return k + k
}) // ['foofoo', 6, 4, 2, 'barbar']

var reduced = myList.reduce(function (set, entry) {
  set += entry
  return set
}, 'start')
console.log(reduced) // 'startfoo123bar'

api

The whole API is considered "public".

Functions with the same name as an Array method work more or less the same way.

There's reverse versions of most things because that's the point.

Yallist

Default export, the class that holds and manages a list.

Call it with either a forEach-able (like an array) or a set of arguments, to initialize the list.

The Array-ish methods all act like you'd expect. No magic length, though, so if you change that it won't automatically prune or add empty spots.

Yallist.create(..)

Alias for Yallist function. Some people like factories.

yallist.head

The first node in the list

yallist.tail

The last node in the list

yallist.length

The number of nodes in the list. (Change this at your peril. It is not magic like Array length.)

yallist.toArray()

Convert the list to an array.

yallist.forEach(fn, [thisp])

Call a function on each item in the list.

yallist.forEachReverse(fn, [thisp])

Call a function on each item in the list, in reverse order.

yallist.get(n)

Get the data at position n in the list. If you use this a lot, probably better off just using an Array.

yallist.getReverse(n)

Get the data at position n, counting from the tail.

yallist.map(fn, thisp)

Create a new Yallist with the result of calling the function on each item.

yallist.mapReverse(fn, thisp)

Same as map, but in reverse.

yallist.pop()

Get the data from the list tail, and remove the tail from the list.

yallist.push(item, ...)

Insert one or more items to the tail of the list.

yallist.reduce(fn, initialValue)

Like Array.reduce.

yallist.reduceReverse

Like Array.reduce, but in reverse.

yallist.reverse

Reverse the list in place.

yallist.shift()

Get the data from the list head, and remove the head from the list.

yallist.slice([from], [to])

Just like Array.slice, but returns a new Yallist.

yallist.sliceReverse([from], [to])

Just like yallist.slice, but the result is returned in reverse.

yallist.toArray()

Create an array representation of the list.

yallist.toArrayReverse()

Create a reversed array representation of the list.

yallist.unshift(item, ...)

Insert one or more items to the head of the list.

yallist.unshiftNode(node)

Move a Node object to the front of the list. (That is, pull it out of wherever it lives, and make it the new head.)

If the node belongs to a different list, then that list will remove it first.

yallist.pushNode(node)

Move a Node object to the end of the list. (That is, pull it out of wherever it lives, and make it the new tail.)

If the node belongs to a list already, then that list will remove it first.

yallist.removeNode(node)

Remove a node from the list, preserving referential integrity of head and tail and other nodes.

Will throw an error if you try to have a list remove a node that doesn't belong to it.

Yallist.Node

The class that holds the data and is actually the list.

Call with var n = new Node(value, previousNode, nextNode)

Note that if you do direct operations on Nodes themselves, it's very easy to get into weird states where the list is broken. Be careful :)

node.next

The next node in the list.

node.prev

The previous node in the list.

node.value

The data the node contains.

node.list

The list to which this node belongs. (Null if it does not belong to any list.)

Download Details:

Author: isaacs
Source Code: https://github.com/isaacs/yallist 
License: ISC license

#javascript #link #list #node 

Yallist: Yet another Linked List
Hunter  Krajcik

Hunter Krajcik

1660453020

List_ext: Dart Extension Method for Iterable and List

list_ext 

Dart extension method for Iterable and List.

Usage

To use this plugin, add list_ext as a dependency in your pubspec.yaml file.

Than add import 'package:list_ext/list_ext.dart'; to the file for use extension methods.

Example

import 'package:list_ext/list_ext.dart';

void main() {
  final list = [1, 2, 5];
  final sum = list.sum();
  print('Sum: $sum');
  // Output: Sum: 8
}

Methods classifier

Common

  • countWhere() - returns count of elements that satisfy the predicate.
  • containsAll() - returns true if the collection contains all elements from the given collection.

Equality

  • isNullOrEmpty/isNotNullOrEmpty - check for null or empty.
  • isUnorderedEquivalent() - check equality of the elements of two iterables without considering order.

Search

  • firstWhereOrNull() - return the first found element or null if no element found.

Safe elements access

  • firstOrNull - returns the first element or null if collection is empty.
  • tryElementAt() - returns the element at the index if exists or orElse if it is out of range.

Transformation

  • reduceValue() - reduces values of elements in a collection to a single value by iteratively combining its using the provided function.

Iterables

  • chunks() - splits into chunks of the specified size.
  • intersperse() - adds an element between elements of the iterable.

String

  • joinOf() - get string value for each element and concatenates it with passed separator.

Map

  • toMap() - creates a Map instance from the iterable.

Math

  • maxOf() - returns max of values by elements.
  • minOf() - returns min of values by elements.
  • sumOf()/sumOfDouble() - returns sum of values by elements.
  • avgOf()/avgOfDouble() - returns the average value of values by elements.

There are specific version of methods for Iterables of num (int and double):

  • max().
  • min().
  • sum().
  • avg().

List specific methods

Common

Get an element

  • random - returns a random element from the list.

Modification

Element

  • replace() - Remove all element occurrences and replace its with another element.
  • replaceWhere() - Replace all elements of list that satisfy given predicate.
  • addIfNotNull() - Adds element to the end of this list if this element is not null.

Sorting

  • sortBy() - Sorts the list in ascending order of the object's field value.
  • sortByDescending() - Sorts the list in descending order of the object's field value.

Transformation

List

  • copyWith() - Copy current list with adding element.
  • copyWithAll() - Copy current list with adding all elements from another list.
  • copyWithReplace() - Copy current list, replacing all element occurrences with another element.
  • copyWithReplaceWhere() - Copy current list, replacing elements of list that satisfy given predicate with another element.
  • copyWithInsertAll() - Copy current list with adding all elements at the provided position of new list.

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add list_ext

With Flutter:

 $ flutter pub add list_ext

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  list_ext: ^1.0.4

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:list_ext/list_ext.dart';

example/main.dart

import 'package:list_ext/list_ext.dart';

void main() {
  final list = [1, 2, 5, 1];
  final sum = list.sum();
  print('Sum: $sum');

  final sumSquare = list.sumOf((v) => v * v);
  print('Sum of squares: $sumSquare');

  final count = list.countWhere((v) => v == 1);
  print('Count of 1: $count');
}

Download Details:

Author: Innim
Source Code: https://github.com/Innim/dart_list_extensions 
License: BSD-3-Clause license

#flutter #dart #list #extensions 

List_ext: Dart Extension Method for Iterable and List
Gordon  Murray

Gordon Murray

1659482400

A Customizable Listview with A-Z Side Scrollbar to Fast Jump

Alphabet List Scroll View

A customizable listview with A-Z side scrollbar to fast jump to the item of the selected character. Quick scroll through list via dragging through alphabets.

API

nametypedefaultdescription
strListList-List of Strings
itemBuilderitemBuilder(context, index)-itemBuilder similar to itemBuilder in ListView.builder
highlightTextStyleboolfalsehighlight the focused pin box.
normalTextStyleColorColors.blackSet color of the focused pin box.
showPreviewbooltrueshow preview on screen
keyboardUsagebooltrueThe alphabet list will be wrapped in scrollview.
indexedHeightdouble Function(int)query the height of widget with index 
headerWidgetListListheaders 
localeLocaleLocale('en')Change the language of the List Scroll

AlphabetScrollListHeader

nametypedefaultdescription
widgetListList[] 
iconIcon Icon shows in the side alphabet list and the preview
indexedHeaderHeightdouble Function(int) query the height of header with index

Installing

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add alphabet_list_scroll

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  alphabet_list_scroll: ^0.0.3

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:alphabet_list_scroll/alphabet_list_scroll.dart';

Author: Lawati97
Source Code: https://github.com/Lawati97/alphabet_list_scroll 
License: MIT license

#flutter #dart #list 

A Customizable Listview with A-Z Side Scrollbar to Fast Jump
Gordon  Murray

Gordon Murray

1659388080

Provide Enhanced List View include Jump Index, Keep Position Etc

Flutter List View

Enhance list view to support scroll to index, jump to index, header sticky, enable without scroll when insert data on top and turn performance to reused items.

Features

  1. Support the list view to jump to and scroll to index.
  2. Support for inserting data without scrolling
  3. Support for show top in reverse mode if the data can't fill the full viewport.
  4. Support sticky header.
  5. Support integrated pull_to_refresh
  6. When initializing data, allow for scrolling to specify an index.
  7. To save performance, flutter list_view always reuses the rendered item.
  8. Support to keep specifying items without reusing and disposing of them once the item is created.

Screen

  
jump.gifstickyHeader.gif
chat.gifpullToRefresh.gif

Example

FlutterListView(
      delegate: FlutterListViewDelegate(
    (BuildContext context, int index) =>
        ListTile(title: Text('List Item ${data[index]}')),
    childCount: data.length,
  ))

Jump to index

flutterListViewController.jumpToIndex(100);

OR

/// Declare
FlutterListViewController controller = FlutterListViewController();
...
controller.sliverController
                      .jumpToIndex(100);
...
FlutterListView(
  controller: controller,
  delegate: FlutterListViewDelegate(
    (BuildContext context, int index) => Container(
      color: Colors.white,
      child: ListTile(title: Text('List Item ${data[index]}')),
    ),
    childCount: data.length,
  ))

If you want better user expierence, preferItemHeight or onItemHeight may set to.

  • preferItemHeight The package don't know the item's height, If you don't set, package alway think the item height is 50 util layout the item. If you know the height, you should set it.
  • onItemHeight like preferItemHeight, the function will used to get height of each item util the item layout.

Keep Position

_renderList() {
  return FlutterListView(
      reverse: true,
      delegate: FlutterListViewDelegate(
          (BuildContext context, int index) => Align(
                alignment: Alignment.centerRight,
                child: Padding(
                  padding: const EdgeInsets.all(10.0),
                  child: Container(
                    decoration: const BoxDecoration(
                        color: Colors.blue,
                        borderRadius: BorderRadius.only(
                            topLeft: Radius.circular(20),
                            bottomLeft: Radius.circular(20),
                            bottomRight: Radius.circular(20))),
                    child: Padding(
                      padding: const EdgeInsets.all(10.0),
                      child: Text(
                        chatListContents[index].msg,
                        style: const TextStyle(
                            fontSize: 14.0, color: Colors.white),
                      ),
                    ),
                  ),
                ),
              ),
          childCount: chatListContents.length,
          onItemKey: (index) => chatListContents[index].id.toString(),
          keepPosition: true,
          keepPositionOffset: 80,
          firstItemAlign: FirstItemAlign.end));
}

Notice: Keep positoin need implement onItemKey, the onItemKey used to identify the unique of item. The key should difference with other items' key. We use the key to know what position you insert to current list. if you insert a item before the rendered item, package should increase the scrollOffset.

Sticky header

Widget _renderHeader(String text) {
  return Container(
    color: const Color(0xFFF3F4F5),
    child: Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 12.0),
      child: Text(
        text,
        style: const TextStyle(fontSize: 18, color: Color(0xFF767676)),
      ),
    ),
  );
}

Widget _renderItem(CountryModel itemData) {
  return Padding(
      padding: const EdgeInsets.only(right: 12.0),
      child: ListTile(
          title: Text(itemData.name), trailing: Text(itemData.phoneCode)));
}

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(title: const Text("Stick Header")),
    body: FlutterListView(
        delegate: FlutterListViewDelegate(
          (BuildContext context, int index) {
            var data = _countries[index];
            if (data is AlphabetHeader) {
              return _renderHeader(data.alphabet);
            } else {
              return _renderItem(data as CountryModel);
            }
          },
          childCount: _countries.length,
          onItemSticky: (index) => _countries[index] is AlphabetHeader,
        ),
        controller: controller),
  );
}

You can also check doc/stickyHeader.md

Integrate pull_to_refresh

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: const Text("Intergrate pull to refresh in list"),
    ),
    body: SmartRefresher(
      enablePullDown: true,
      enablePullUp: true,
      header: const WaterDropHeader(),
      footer: CustomFooter(
        builder: (context, mode) {
          Widget body;
          if (mode == LoadStatus.idle) {
            body = const Text("pull up load");
          } else if (mode == LoadStatus.loading) {
            body = const CupertinoActivityIndicator();
          } else if (mode == LoadStatus.failed) {
            body = const Text("Load Failed!Click retry!");
          } else if (mode == LoadStatus.canLoading) {
            body = const Text("release to load more");
          } else {
            body = const Text("No more Data");
          }
          return SizedBox(
            height: 55.0,
            child: Center(child: body),
          );
        },
      ),
      controller: _refreshController,
      onRefresh: _onRefresh,
      onLoading: _onLoading,
      child: FlutterListView(
          delegate: FlutterListViewDelegate(
        (BuildContext context, int index) =>
            ListTile(title: Text('List Item ${data[index]}')),
        childCount: data.length,
      )),
    ),
  );
}

Support to keep specifying items without reusing and disposing of them once the item is created.

FlutterListView(
  delegate: FlutterListViewDelegate(
      (BuildContext context, int index) =>
          Item(text: data[index].toString()),
      childCount: data.length,
      // If onItemKey is not given, the key is index
      // The example is indicate the "40" item will not be reused and disposed after it was created
      onIsPermanent: (key) => key == "40"))

Author: Robert-luoqing
Source Code: https://github.com/robert-luoqing/flutter_list_view 
License: MIT license

#flutter #dart #list #view 

Provide Enhanced List View include Jump Index, Keep Position Etc

Easy to Use and Read Action and Content Based Authorizations Of Ruby

If you like the straight forward and effective nature of Strong Parameters and suspect that cancan might be overkill for your project then you'll love Petergate's easy to use and read action and content based authorizations."

-- 1 Peter 3:41

Installation

Get the gem

Add this line to your application's Gemfile:

gem 'petergate'

And then execute:

bundle

Or install it yourself as:

gem install petergate

Prerequisites: Setup Authentication (Devise)

Make sure your user model is defined in app/models/user.rb and called User.

If you're using devise you're in luck, otherwise you'll have to add following methods to your project:

current_user
after_sign_in_path_for(current_user)
authenticate_user!

Run the generators

rails g petergate:install
rake db:migrate

This will add a migration and insert petergate into your User model.

Usage

User Model

Configure available roles by modifying this block at the top of your user.rb.

############################################################################################
## PeterGate Roles                                                                        ##
## The :user role is added by default and shouldn't be included in this list.             ##
## The :root_admin can access any page regardless of access settings. Use with caution!   ##
## The multiple option can be set to true if you need users to have multiple roles.       ##
petergate(roles: [:admin, :editor], multiple: false)                                      ##
############################################################################################

Instance Methods

user.role => :editor
user.roles => [:editor, :user]
user.roles=(v) #sets roles
user.available_roles => [:admin, :editor]
user.has_roles?(:admin, :editors) # returns true if user is any of roles passed in as params.

Class Methods

User.#{role}_editors => #list of editors. Method is created for all roles. Roles [admin, :teacher] will have corresponding methods role_admins, role_teachers, etc.

Controllers

Setup permissions in your controllers the same as you would for a before filter like so:

access all: [:show, :index], user: {except: [:destroy]}, company_admin: :all

# one other option that might seem a bit weird is to put a group of roles in an array:
access [:all, :user] => [:show, :index]

Inside your views you can use logged_in?(:admin, :customer, :etc) to show or hide content.

<%= link_to "destroy", destroy_listing_path(listing) if logged_in?(:admin, :customer, :etc) %>

If you need to access available roles within your project you can by calling:

User::ROLES
# or from an instance
User.first.available_roles
# ROLES is a CONSTANT and will still work from within the User model instance methods
# like in this default setter:

def roles=(v)
  self[:roles] = v.map(&:to_sym).to_a.select{|r| r.size > 0 && ROLES.include?(r)}
end

If you need to deny access you can use the forbidden! method:

before_action :check_active_user

def check_active_user
  forbidden! unless current_user.active
end

If you want to change the permission denied message you can add to the access line:

access user: [:show, :index], message: "You shall not pass"

User Admin Example Form for Multiple Roles

= form_for @user do |f| 
  - if @user.errors.any? 
    #error_explanation 
      h2 = "#{pluralize(@user.errors.count, "error")} prohibited this user from being saved:" 
      ul 
        - @user.errors.full_messages.each do |message| 
          li = message 
 
  .field 
    = f.label :email 
    = f.text_field :email 
  - if @user.new_record? || params[:passwd] 
    .field 
      = f.label :password 
      = f.text_field :password 
    .field 
      = f.label :password_confirmation 
      = f.text_field :password_confirmation 
  .field 
    = f.label :roles 
    = f.select :roles, @user.available_roles, {}, {multiple: true} 
  .actions = f.submit 

User Admin Example Form for Single Role Mode

= form_for @user do |f| 
  - if @user.errors.any? 
    #error_explanation 
      h2 = "#{pluralize(@user.errors.count, "error")} prohibited this user from being saved:" 
      ul 
        - @user.errors.full_messages.each do |message| 
          li = message 
 
  .field 
    = f.label :email 
    = f.text_field :email 
  - if @user.new_record? || params[:passwd] 
    .field 
      = f.label :password 
      = f.text_field :password 
    .field 
      = f.label :password_confirmation 
      = f.text_field :password_confirmation 
  .field 
    = f.label :role 
    = f.select :role, @user.available_roles
  .actions = f.submit 

Credits

PeterGate is written and maintaned by Isaac Sloan and friends.

Contributing

  1. Fork it ( https://github.com/isaacsloan/petergate/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request

Author:  elorest
Source code: https://github.com/elorest/petergate
License:  MIT license

#ruby  #ruby-on-rails 

Easy to Use and Read Action and Content Based Authorizations Of Ruby
Edward Jackson

Edward Jackson

1658802077

What is Bag of Words (BoW)? BoW Explained with Examples

In this Natural Language Processing (NLP) tutorial, you'll learn what Bag of Words (BoW) is, why BoW is used, learn about it’s implementation in Python and more.

  1. What is Bag of Words in NLP?
  2. Why is the Bag of Words algorithm used?
  3. Understanding Bag of Words with an example
  4. Implementing Bag of Words with Python
  5. Create a Bag of Words Model with Sklearn
  6. What are N-Grams?
  7. What is Tf-Idf ( term frequency-inverse document frequency)?
  8. Feature Extraction with Tf-Idf vectorizer
  9. Limitations of Bag of Word

Using Natural Language Processing, we make use of the text data available across the internet to generate insights for the business. In order to understand this huge amount of data and make insights from them, we need to make them usable. Natural language processing helps us to do so.

What is a Bag of Words in NLP?

Bag of words is a Natural Language Processing technique of text modelling. In technical terms, we can say that it is a method of feature extraction with text data. This approach is a simple and flexible way of extracting features from documents.

A bag of words is a representation of text that describes the occurrence of words within a document. We just keep track of word counts and disregard the grammatical details and the word order. It is called a “bag” of words because any information about the order or structure of words in the document is discarded. The model is only concerned with whether known words occur in the document, not where in the document.
 

Why is the Bag-of-Words algorithm used?

So, why bag-of-words, what is wrong with the simple and easy text?  

One of the biggest problems with text is that it is messy and unstructured, and machine learning algorithms prefer structured, well defined fixed-length inputs and by using the Bag-of-Words technique we can convert variable-length texts into a fixed-length vector.

Also, at a much granular level, the machine learning models work with numerical data rather than textual data. So to be more specific, by using the bag-of-words (BoW) technique, we convert a text into its equivalent vector of numbers.

Understanding Bag of Words with an example

Let us see an example of how the bag of words technique converts text into vectors

Example(1) without preprocessing: 

Sentence 1:  ”Welcome to Great Learning, Now start learning”

Sentence 2: “Learning is a good practice”

Sentence 1Sentence 2
WelcomeLearning
tois
Greata
Learninggood
,practice
Now 
start 
learning 

Step 1: Go through all the words in the above text and make a list of all of the words in our model vocabulary.

  • Welcome
  • To
  • Great
  • Learning
  • ,
  • Now
  • start
  • learning
  • is
  • a
  • good
  • practice

Note that the words ‘Learning’ and ‘ learning’ are not the same here because of the difference in their cases and hence are repeated. Also, note that a comma ‘ , ’ is also taken in the list.

Because we know the vocabulary has 12 words, we can use a fixed-length document-representation of 12, with one position in the vector to score each word.

The scoring method we use here is to count the presence of each word and mark 0 for absence. This scoring method is used more generally.

The scoring of sentence 1 would look as follows:

WordFrequency
Welcome1
to1
Great1
Learning1
,1
Now1
start1
learning1
is0
a0
good0
practice0

Writing the above frequencies in the vector 

Sentence 1 ➝ [ 1,1,1,1,1,1,1,1,0,0,0 ]

Now for sentence 2, the scoring would like 

WordFrequency
Welcome0
to0
Great0
Learning1
,0
Now0
start0
learning0
is1
a1
good1
practice1

Similarly, writing the above frequencies in the vector form

Sentence 2 ➝ [ 0,0,0,0,0,0,0,1,1,1,1,1 ]
 

SentenceWelcometoGreatLearning,Nowstart learningisagoodpractice
Sentence1111111110000
Sentence2000000011111

But is this the best way to perform a bag of words. The above example was not the best example of how to use a bag of words. The words Learning and learning, although having the same meaning are taken twice. Also, a comma ’,’ which does not convey any information is also included in the vocabulary.

Let us make some changes and see how we can use ‘bag of words in a more effective way.

Example(2) with preprocessing

Sentence 1: ”Welcome to Great Learning, Now start learning”

Sentence 2: “Learning is a good practice”
 

Step 1: Convert the above sentences in lower case as the case of the word does not hold any information.

Step 2: Remove special characters and stopwords from the text. Stopwords are the words that do not contain much information about text like ‘is’, ‘a’,’the and many more’.

After applying the above steps, the sentences are changed to

Sentence 1:  ”welcome great learning now start learning”

Sentence 2: “learning good practice”

Although the above sentences do not make much sense the maximum information is contained in these words only.

Step 3: Go through all the words in the above text and make a list of all of the words in our model vocabulary.

  • welcome
  • great
  • learning
  • now
  • start
  • good
  • practice

Now as the vocabulary has only 7 words, we can use a fixed-length document-representation of 7, with one position in the vector to score each word.

The scoring method we use here is the same as used in the previous example. For sentence 1, the count of words is as follow:

WordFrequency
welcome1
great1
learning2
now1
start1
good0
practice0

Writing the above frequencies in the vector 
 

Sentence 1 ➝ [ 1,1,2,1,1,0,0 ]
 

Now for sentence 2, the scoring would be like 

WordFrequency
welcome0
great0
learning1
now0
start0
good1
practice1

Similarly, writing the above frequencies in the vector form

Sentence 2 ➝ [ 0,0,1,0,0,1,1 ]
 

Sentencewelcomegreatlearningnowstart goodpractice
Sentence11121100
Sentence20010011

The approach used in example two is the one that is generally used in the Bag-of-Words technique, the reason being that the datasets used in Machine learning are tremendously large and can contain vocabulary of a few thousand or even millions of words. Hence, preprocessing the text before using bag-of-words is a better way to go.

In the examples above we use all the words from vocabulary to form a vector, which is neither a practical way nor the best way to implement the BoW model. In practice, only a few words from the vocabulary, more preferably most common words are used to form the vector. 

Implementing Bag of Words Algorithm with Python

In this section, we are going to implement a bag of words algorithm with Python. Also, this is a very basic implementation to understand how bag of words algorithm work, so I would not recommend using this in your project, instead use the method described in the next section.

def vectorize(tokens):
    ''' This function takes list of words in a sentence as input 
    and returns a vector of size of filtered_vocab.It puts 0 if the 
    word is not present in tokens and count of token if present.'''
    vector=[]
    for w in filtered_vocab:
        vector.append(tokens.count(w))
    return vector
def unique(sequence):
    '''This functions returns a list in which the order remains 
    same and no item repeats.Using the set() function does not 
    preserve the original ordering,so i didnt use that instead'''
    seen = set()
    return [x for x in sequence if not (x in seen or seen.add(x))]
#create a list of stopwords.You can import stopwords from nltk too
stopwords=["to","is","a"]
#list of special characters.You can use regular expressions too
special_char=[",",":"," ",";",".","?"]
#Write the sentences in the corpus,in our case, just two 
string1="Welcome to Great Learning , Now start learning"
string2="Learning is a good practice"
#convert them to lower case
string1=string1.lower()
string2=string2.lower()
#split the sentences into tokens
tokens1=string1.split()
tokens2=string2.split()
print(tokens1)
print(tokens2)
#create a vocabulary list
vocab=unique(tokens1+tokens2)
print(vocab)
#filter the vocabulary list
filtered_vocab=[]
for w in vocab: 
    if w not in stopwords and w not in special_char: 
        filtered_vocab.append(w)
print(filtered_vocab)
#convert sentences into vectords
vector1=vectorize(tokens1)
print(vector1)
vector2=vectorize(tokens2)
print(vector2)

Output:

Create a Bag of Words Model with Sklearn

We can use the CountVectorizer() function from the Sk-learn library to easily implement the above BoW model using Python.

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
 
sentence_1="This is a good job.I will not miss it for anything"
sentence_2="This is not good at all"
 
 
 
CountVec = CountVectorizer(ngram_range=(1,1), # to use bigrams ngram_range=(2,2)
                           stop_words='english')
#transform
Count_data = CountVec.fit_transform([sentence_1,sentence_2])
 
#create dataframe
cv_dataframe=pd.DataFrame(Count_data.toarray(),columns=CountVec.get_feature_names())
print(cv_dataframe)

What are N-Grams?

Again same questions, what are n-grams and why do we use them? Let us understand this with an example below-

Sentence 1: “This is a good job. I will not miss it for anything”

Sentence 2: ”This is not good at all”

For this example, let us take the vocabulary of 5 words only. The five words being-

  • good
  • job
  • miss
  • not
  • all

So, the respective vectors for these sentences are:

“This is a good job. I will not miss it for anything”=[1,1,1,1,0]

”This is not good at all”=[1,0,0,1,1]

Can you guess what is the problem here? Sentence 2 is a negative sentence and sentence 1 is a positive sentence. Does this reflect in any way in the vectors above? Not at all. So how can we solve this problem? Here come the N-grams to our rescue.

An N-gram is an N-token sequence of words: a 2-gram (more commonly called a bigram) is a two-word sequence of words like “really good”, “not good”, or “your homework”, and a 3-gram (more commonly called a trigram) is a three-word sequence of words like “not at all”, or “turn off light”.

For example, the bigrams in the first line of text in the previous section: “This is not good at all” are as follows:

  • “This is”
  • “is not”
  • “not good”
  • “good at”
  • “at all”

Now if instead of using just words in the above example, we use bigrams (Bag-of-bigrams) as shown above. The model can differentiate between sentence 1 and sentence 2. So, using bi-grams makes tokens more understandable (for example, “HSR Layout”, in Bengaluru, is more informative than “HSR” and “layout”)

So we can conclude that a bag-of-bigrams representation is much more powerful than bag-of-words, and in many cases proves very hard to beat.

What is Tf-Idf ( term frequency-inverse document frequency)?

The scoring method being used above takes the count of each word and represents the word in the vector by the number of counts of that particular word. What does a word having high word count signify?

Does this mean that the word is important in retrieving information about documents? The answer is NO. Let me explain, if a word occurs many times in a document but also along with many other documents in our dataset, maybe it is because this word is just a frequent word; not because it is relevant or meaningful.

One approach is to rescale the frequency of words by how often they appear in all documents so that the scores for frequent words like “the” that are also frequent across all documents are penalized. This approach is called term frequency-inverse document frequency or shortly known as Tf-Idf approach of scoring.TF-IDF is intended to reflect how relevant a term is in a given document. So how is Tf-Idf of a document in a dataset calculated?

TF-IDF for a word in a document is calculated by multiplying two different metrics:

The term frequency (TF) of a word in a document. There are several ways of calculating this frequency, with the simplest being a raw count of instances a word appears in a document. Then, there are other ways to adjust the frequency. For example, by dividing the raw count of instances of a word by either length of the document, or by the raw frequency of the most frequent word in the document. The formula to calculate Term-Frequency is

TF(i,j)=n(i,j)/Σ n(i,j)

Where,

n(i,j )= number of times nth word  occurred in a document
Σn(i,j) = total number of words in a document. 

The inverse document frequency(IDF) of the word across a set of documents. This suggests how common or rare a word is in the entire document set. The closer it is to 0, the more common is the word. This metric can be calculated by taking the total number of documents, dividing it by the number of documents that contain a word, and calculating the logarithm.

So, if the word is very common and appears in many documents, this number will approach 0. Otherwise, it will approach 1.

Multiplying these two numbers results in the TF-IDF score of a word in a document. The higher the score, the more relevant that word is in that particular document.

To put it in mathematical terms, the TF-IDF score is calculated as follows:

IDF=1+log(N/dN)

Where

N=Total number of documents in the dataset
dN=total number of documents in which nth word occur 

Also, note that the 1 added in the above formula is so that terms with zero IDF don’t get suppressed entirely. This process is known as IDF smoothing.

The TF-IDF is obtained by 

TF-IDF=TF*IDF

Does this seem too complicated? Don’t worry, this can be attained with just a few lines of code and you don’t even have to remember these scary formulas.

Feature Extraction with Tf-Idf vectorizer

We can use the TfidfVectorizer() function from the Sk-learn library to easily implement the above BoW(Tf-IDF), model.

import pandas as pd
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
 
sentence_1="This is a good job.I will not miss it for anything"
sentence_2="This is not good at all"
 
 
 
#without smooth IDF
print("Without Smoothing:")
#define tf-idf
tf_idf_vec = TfidfVectorizer(use_idf=True, 
                        smooth_idf=False,  
                        ngram_range=(1,1),stop_words='english') # to use only  bigrams ngram_range=(2,2)
#transform
tf_idf_data = tf_idf_vec.fit_transform([sentence_1,sentence_2])
 
#create dataframe
tf_idf_dataframe=pd.DataFrame(tf_idf_data.toarray(),columns=tf_idf_vec.get_feature_names())
print(tf_idf_dataframe)
print("\n")
 
#with smooth
tf_idf_vec_smooth = TfidfVectorizer(use_idf=True,  
                        smooth_idf=True,  
                        ngram_range=(1,1),stop_words='english')
 
 
tf_idf_data_smooth = tf_idf_vec_smooth.fit_transform([sentence_1,sentence_2])
 
print("With Smoothing:")
tf_idf_dataframe_smooth=pd.DataFrame(tf_idf_data_smooth.toarray(),columns=tf_idf_vec_smooth.get_feature_names())
print(tf_idf_dataframe_smooth)

Limitations of Bag-of-Words

Although Bag-of-Words is quite efficient and easy to implement, still there are some disadvantages to this technique which are given below:

  1. The model ignores the location information of the word. The location information is a piece of very important information in the text. For example  “today is off” and “Is today off”, have the exact same vector representation in the BoW model.
  2. Bag of word models doesn’t respect the semantics of the word. For example, words ‘soccer’ and ‘football’ are often used in the same context. However, the vectors corresponding to these words are quite different in the bag of words model. The problem becomes more serious while modeling sentences. Ex: “Buy used cars” and “Purchase old automobiles” are represented by totally different vectors in the Bag-of-words model.
  3. The range of vocabulary is a big issue faced by the Bag-of-Words model. For example, if the model comes across a new word it has not seen yet, rather we say a rare, but informative word like Biblioklept(means one who steals books). The BoW model will probably end up ignoring this word as this word has not been seen by the model yet.

Original article source at https://www.mygreatlearning.com

#bagofwords #python #datascience #nlp 

What is Bag of Words (BoW)? BoW Explained with Examples
Mike  Kozey

Mike Kozey

1658560380

Double_linked_list: A Library Presenting A Generic Double Linked List

Double Linked List

A library presenting a generic double linked list.

Double linked list structure:

dll_structure

Usage

Create a new empty list, from iterables or from another list

import 'package:double_linked_list/double_linked_list.dart';

main() {
  final emptyList = DoubleLinkedList<int>.empty();
  
  final fromList = DoubleLinkedList<int>.fromIterable([1, 2, 3]);
  final fromListExtension = [1, 2, 3].toDoubleLinkedList();
  
  final fromSet = DoubleLinkedList<int>.fromIterable({1, 2, 3});
  final fromSetExtension = {1, 2, 3}.toDoubleLinkedList();
  
  final copyList = DoubleLinkedList<int>.from(fromList);
  final copyListMethod = copyList.copy();
}

Iterate over a list in normal or reverse order

import 'package:double_linked_list/double_linked_list.dart';

main() {
  final list = [1, 3, 5].toDoubleLinkedList();
  for (var node = list.first; !node.isEnd; node = node.next) {
    node = node.insertAfter(node.content + 1);
  }
  print(list); // [1, 2, 3, 4, 5, 6]
  
  for (var node = list.last; !node.isBegin; node = node.previous) {
    print(node.content);
  }
  // 6 5 4 3 2 1
}

Be careful when iterating and inserting elements:

import 'package:double_linked_list/double_linked_list.dart';

main() {
  final list = [1, 3, 5].toDoubleLinkedList();
  for (var node = list.first; !node.isEnd; node = node.next) {
    node.insertAfter(node.content + 1);
  }
}

:warning:Program stuck at an endless loop.

To avoid this, move to the inserted node:

import 'package:double_linked_list/double_linked_list.dart';

main() {
  final list = [1, 3, 5].toDoubleLinkedList();
  for (var node = list.first; !node.isEnd; node = node.next) {
    node = node.insertAfter(node.content + 1);
  }
}

You can also use most of the functions available for Iterables, and some others:

import 'package:double_linked_list/double_linked_list.dart';

main() {
  final list = [1, 2, 3].toDoubleLinkedList();

  list.forEach(print);

  list.apply((e) => e * e);
  print(list); // [1 | 4 | 9]
    
  print(list.where((e) => e.isOdd)); // [1 | 9]
    
  print(list.reduce((value, element) => value + element)); // 14
  print(list.fold<int>(-14, (value, element) => value + element)); // 0
    
  print(list.any((e) => e > 2)); // true
  print(list.every((e) => e > 2)); // false
    
  print(list.firstWhere((e) => e > 2)); // (4)
  print(list.lastWhere((e) => e > 2)); // (9)
  
}

Complete example at example.

Installing

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add double_linked_list

With Flutter:

 $ flutter pub add double_linked_list

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  double_linked_list: ^2.0.1

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:double_linked_list/double_linked_list.dart';

example/double_linked_list_example.dart

import 'package:double_linked_list/double_linked_list.dart';

//ignore_for_file: unused_local_variable

void main() {
  final list = DoubleLinkedList.fromIterable([1, 2, 3]);
  //Empty
  final emptyList = DoubleLinkedList.empty();
  print(emptyList.length); // 0

  // From Iterables
  final fromList = DoubleLinkedList.fromIterable([1, 2, 3]);
  print(fromList.length); // 3
  print(fromList); // [1 | 2 | 3]

  final fromSet = DoubleLinkedList.fromIterable({1, 2, 3});
  print(fromSet.length); // 3
  print(fromSet); // [1 | 2 | 3]

  // With extension methods
  final fromListExtension = [1, 2, 3].toDoubleLinkedList();
  print(fromListExtension); // [1 | 2 | 3]

  final fromSetExtension = {1, 2, 3}.toDoubleLinkedList();
  print(fromSetExtension); // [1 | 2 | 3]

  // To iterables
  final Iterable<int> toIterable = list.content;
  final List<int> toList = list.toList();
  final Set<int> toSet = list.toSet();

  // From other DoubleLinkedLists
  final copy = DoubleLinkedList.from(fromList);
  final copy2 = fromList.copy();
  print(copy); // [1 | 2 | 3]
  print(copy == fromList); // false

  // Copy constructors perform shallow copy
  final originalList = [Object(), Object()];
  final firstLinkedList = DoubleLinkedList.fromIterable(originalList);
  final copyLinkedList = DoubleLinkedList.from(firstLinkedList);

  print(originalList.first == firstLinkedList.first.content); // true
  print(firstLinkedList.first.content == copyLinkedList.first.content); // true

  // New nodes are created in the list copy
  print(firstLinkedList.first == copyLinkedList.first); // false

  // Iteration
  for (var node = list.first; !node.isEnd; node = node.next) {
    print(node);
  }
  // (1)
  // (2)
  // (3)

  // Reverse iteration
  for (var node = list.last; !node.isBegin; node = node.previous) {
    print(node);
  }
  // (3)
  // (2)
  // (1)

  // Insertion
  var listCopy = list.copy();
  listCopy.begin.insertAfter(0);
  print(listCopy); // [0 | 1 | 2 | 3]

  listCopy = list.copy();
  for (var node = listCopy.first; !node.isEnd; node = node.next) {
    node.insertBefore(-1);
  }
  print(listCopy); // [-1 | 1 | -1 | 2 | -1 | 3]

  listCopy = list.copy();
  for (var node = listCopy.begin; !node.isEnd; node = node.next) {
    node = node.insertAfter(0);
  }
  print(listCopy); // [0 | 1 | 0 | 2 | 0 | 3 | 0]

  // ForEach
  list.forEach(print);
  // 1
  // 2
  // 3

  // Apply
  list.apply((e) => e * e);
  print(list); // [1 | 4 | 9]

  // Where
  print(list.where((e) => e.isOdd)); // [1 | 9]

  // Reduce
  print(list.reduce((value, element) => value + element)); // 14

  // Fold
  print(list.fold<int>(-14, (value, element) => value + element)); // 0

  // Any
  print(list.any((e) => e > 2)); // true

  // Every
  print(list.every((e) => e > 2)); // false

  // FirstWhere
  print(list.firstWhere((e) => e > 2)); // (4)

  // LastWhere
  print(list.lastWhere((e) => e > 2)); // (9)
}

Features and bugs

Please file feature requests and bugs at the issue tracker.

Author: Diviloper
Source Code: https://github.com/Diviloper/double_linked_list 
License: BSD-3-Clause license

#flutter #dart #list 

Double_linked_list: A Library Presenting A Generic Double Linked List

Level-list: Map Lists Of Data Stored in A LevelDB to DOM Elements

level-list

Map lists of data stored in a LevelDB to DOM elements.

Example

var List = require('level-list');
var MemDB = require('memdb');

// a levelup style database
var db = MemDB();

// create a list with your db and a function that generates dom elements
var list = List(db, function (row) {
  var el = document.createElement('p');
  el.appendChild(document.createTextNode(row.date));
  return el;
});

// insert the list into the dom
document.body.appendChild(list.el);

// insert some data into the db
(function insert () {
  db.put(Date.now(), { date: (new Date).toString() });
  setTimeout(insert, 1000);
})();

API

List(db[, tag][, fn])

Create a new list that pulls data from db. The list's elements will be wrapped inside tag, which defaults to div. Either pass a fn that creates dom elements here, or to List#create.

List#create(fn)

fn is called with a row and should return a dom element. row is an EventEmitter with all the json data read from the db on it. For its events, see below.

List#limit(count)

Limit the display to count entries.

List#sort(fn)

Sort the list by the given comparator function, that gets both rows as arguments.

Use comparator to create comparators conveniently. This would sort by row._key in descending order:

var comparator = require('comparator');

list.sort(comparator.desc('_key'));

List#el

The list's dom element.

Row#on('remove', fn)

A remove event is emitted when an already showed row needs to be removed, so you can clean up if necessary.

Row#on('update', fn), Row#on('change *', fn)

If you listen for the update and/or one of the change * events, your dom element won't be replaced. Instead, you can use row's updated data to update it yourself.

This is especially handy when using component/reactive, see the example.

Row#_key

The key that row's data was found under.

Row#_element

The row's element.

TODO

  • sorting with limit
  • infinite scrolling and/or load more
  • testling tests

Author: juliangruber
Source Code: https://github.com/juliangruber/level-list 
License: MIT

#javascript #list #node #leveldb #dom 

Level-list: Map Lists Of Data Stored in A LevelDB to DOM Elements
Lawson  Wehner

Lawson Wehner

1654384020

List_german_words: A List Of German Words for Use in Other tools

list_german_words

Overview

This package contains a list of german words for use in other tools. From spell checkers, to ngram analysis.

Warning: Loading Long Lists Can Reduce Application Performance

Usage

A simple usage example:

import 'package:list_german_words/list_german_words.dart';

main() {
  print(list_german_words.sublist(0, 50).join('\n'));
}

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add list_german_words

With Flutter:

 $ flutter pub add list_german_words

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  list_german_words: ^0.1.0+2

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:list_german_words/list_german_words.dart';

example/list_german_words_example.dart

import 'package:list_german_words/list_german_words.dart';

void main() {
  print(list_german_words.sublist(0, 50).join('\n'));
}

Features and bugs

Please file feature requests and bugs at the issue tracker.

Author: ALMDart
Source Code: https://github.com/ALMDart/dart_list_german_words 
License: MIT license

#flutter #dart #list 

List_german_words: A List Of German Words for Use in Other tools

12素晴らしいLinuxコマンドとユーティリティ

Linux用のあまり知られていないユーティリティとコマンドの別のリストが戻ってきました。これはあなたが日常の仕事をより速く進めるのに役立ちます。

1.グーグル

私たちは、ブラウザのグラフィカルインターフェイスを介してGoogle検索を使用することに慣れています。ただし、これは、グラフィカルインターフェイスが使用できない環境では問題になります。googlerユーティリティを使用すると、コマンドラインからGoogle検索を実行できるようになります。

Googlerは、Linuxターミナル内でGoogle(Web&News&Search)にアクセスするためのフル機能のPythonベースのコマンドラインツールです。

URL:https ://github.com/jarun/googler

インストール方法:

# ubuntu$ sudo add-apt-repository ppa:twodopeshaggy/jarun
$ sudo apt-get update
$ sudo apt install googlerOR$ sudo snap install googler

使用例:

$ googler ford usa

グーグル実行中

2. sl(蒸気機関車)

コマンド「ls」を入力する代わりに、「sl」と入力した頻度はどれくらいですか。

面倒な「コマンドが見つかりません」というメッセージを表示する代わりに、この小さなユーティリティは素敵な画像を表示します。少なくともこのように、あなたは少し笑うか、次回はもっと注意するでしょう。

インストール方法:

$sudo apt install sl

使用例:

$ sl

slランニング

確かに、注意を引くのにも役立ちますが、最終的には面倒になる可能性があります。

3. hstr

hstrは私が毎日使用している優れたツールで、シェル履歴の提案ボックスに入力されたコマンドの履歴を簡単に表示、参照、検索できます。bashとzshで使用できます。

URL:http ://dvorka.github.io/hstr/

URL:https ://github.com/dvorka/hstr

インストール方法:

#Ubuntu
$ sudo add-apt-repository ppa:ultradvorka/ppa && sudo apt-get update && sudo apt-get install hstr && hstr --show-configuration >> ~/.bashrc && . ~/.bashrc

4.はい

Linuxにデフォルトで付属しているこのコマンドは、事前定義された応答を端末に渡すために使用できるシステム管理者にとって便利です。

使用例:

$ yes hello-world

はい実行中

5. rev(リバース)

与えられたすべての文字列を逆にします。これは時々役に立ちます。

使用例:

$ rev
$ hello world!

revrunning

良いことは、何もインストールする必要がないことです。

6. Wikit

このLinuxユーティリティは、コマンドラインからウィキペディアの記事を検索するために使用されます。

使用する必要があるのは、情報を取得する検索語を使用してコマンドを実行することだけです。

URL:https ://www.tecmint.com/wikipedia-commandline-tool/

インストール方法:

# Debian/Ubuntu$ sudo apt install nodejs	$ sudo npm install wikit -g

使用例:

Wikit matrix

ウィキの実行

7. pydf

このツールは、「df」コマンドの優れた代替手段です。Linuxファイルシステムで使用されているディスク容量と使用可能なディスク容量がdfコマンドと同じように表示されますが、色が異なり、結果をカスタマイズすることもできます。

Pythonで書かれていることに注意してください。

URL:https ://pypi.org/project/pydf/

#Ubuntu# only if you do not have phyton installed:
$ sudo apt install python3-pip
$ pip install pydf

実行中のpydf

8.trash-cli

Trash-cliは、ファイルをゴミ箱に移動し、元の絶対パス、削除日、およびアクセス許可を記録するコマンドラインインターフェイスです。

URL:https://github.com/andreafrancia/trash-cli

インストール方法:

# Debian/Ubuntu systems
$ sudo easy_install trash-cli

使用例:

# We create an example file named file1
$ echo "hello world!" > file1
$ trash-put file1
#
$ trash-list

使用可能なコマンド:

$ trash-put           #trash files and directories.
$ trash-list          #list trashed files.
$ trash-restore       #restore a trashed file.
$ trash-rm            #remove individual files from the trashcan.
$ trash-empty         #empty the trashcan(s).

trash-cliの実行

9. eSpeak NG

eSpeak NGは、英語やその他の言語でテキストを音声に変換するために使用できる無料のオープンソースソフトウェアです。これは、JonathanDuddingtonによって作成されたeSpeakエンジンに基づいています。

URL: https://github.com/espeak-ng/espeak-ng

インストール方法:

# Ubuntu
$ apt-get install espeak

それでは、「こんにちはケスク!」というセリフを話しましょう。そしてそれをhello.mp4オーディオファイルに録音します:

$ espeak "Hi Kesk!" -w hello.mp4 -g 60 -p 70 -s 100 -v en-us

録音したいテキストファイルを指定することもできます。

$ espeak -f example.txt -w example.mp4 -g 60 -p 70 -s 100 -v en-us

今、あなたがしなければならないのはあなたの好きなアプリケーションでそれをプレイすることだけです、そしてそれはそれです。

10.一瞥

このコマンドラインシステム監視ユーティリティを使用すると、CPU、負荷平均、メモリ、ネットワークインターフェイス、ディスクI / O、プロセス、およびファイルシステムスペースの使用率を監視できます。

GlancesユーティリティはPythonで記述されており、psutilライブラリを使用してシステム情報を取得し、わかりやすい形式で表示します。

また、構成ファイルを使用してさまざまな警告しきい値を設定することもできます。

すべてを管理するのに非常に便利です。

URL:https ://nicolargo.github.io/glances/

インストール方法:

$ sudo apt install glances

使用例:

$ glances

走っている一瞥

11.gtop

gtopユーティリティは、システムとそのプロセスに関するさまざまな情報を表示するLinuxシステムモニターです。

このツールは使いやすく、リソースをほとんど消費しないため、リソースを無駄にすることなく実行できます。さらに、オペレーティングシステムのコマンドを使用するため、非常に印象的で正確な方法で情報を表示します。

これは、CanGüneyAksakalliによってJavaScriptで開発されたオープンソースツールであり、インストールして実行するには、コンピューターにnodejsをインストールする必要があります。

URL:git clone https://github.com/aksakalli/gtop.git

インストール方法:

$ sudo npm install gtop -g

使用例:

$ gtop

gtopランニング

12.ファクター

以前のユーティリティと同様に、この小さなプログラムはデフォルトであり、ある時点で役立つ場合があります。

ファクターランニング

Linuxのコマンドラインユーティリティや、特に役立つコマンドやあまり知られていないコマンドをご存知の場合は、それについて教えていただければ幸いです。

ありがとうございました!

ソース:https ://medium.com/codex/12-awesome-linux-commands-utilities-49ab56588a84

#linux 

12素晴らしいLinuxコマンドとユーティリティ

12 Increíbles Comandos Y Utilidades De Linux

Vuelvo con otra lista de utilidades y comandos poco conocidos para Linux que te ayudarán a ir más rápido con tu trabajo diario.

1. googleador

Estamos acostumbrados a utilizar la búsqueda de Google a través de una interfaz gráfica en el navegador. Sin embargo, esto es un problema en entornos donde la interfaz gráfica no está disponible. Con la utilidad googler podremos realizar búsquedas en Google desde la línea de comandos.

Googler es una herramienta de línea de comandos basada en Python con todas las funciones para acceder a Google (Web & News & Search) dentro de la terminal de Linux.

URL: https://github.com/jarun/googler

Cómo instalarlo:

# ubuntu$ sudo add-apt-repository ppa:twodopeshaggy/jarun
$ sudo apt-get update
$ sudo apt install googlerOR$ sudo snap install googler

Ejemplo de uso:

$ googler ford usa

google corriendo

2. sl (Locomotora de vapor)

En lugar de escribir el comando 'ls', ¿con qué frecuencia ha escrito 'sl'?

En lugar de mostrarte el tedioso mensaje de "comando no encontrado", esta pequeña utilidad te mostrará una bonita imagen; al menos así te reirás un poco o tendrás más cuidado la próxima vez.

Cómo instalarlo:

$sudo apt install sl

Ejemplo de uso:

$ sl

sl corriendo

Es cierto que al final puede resultar cansino, aunque también servirá para que prestes atención.

3. calle

hstr es una gran herramienta que uso a diario que le permite ver, explorar y buscar fácilmente el historial de comandos ingresados ​​en el cuadro de sugerencias del historial de shell. Está disponible para bash y zsh.

URL: http://dvorka.github.io/hstr/

URL: https://github.com/dvorka/hstr

Cómo instalarlo:

#Ubuntu
$ sudo add-apt-repository ppa:ultradvorka/ppa && sudo apt-get update && sudo apt-get install hstr && hstr --show-configuration >> ~/.bashrc && . ~/.bashrc

4. si

Este comando que viene por defecto en Linux es útil para los administradores de sistemas que pueden usarlo para pasar una respuesta predefinida a la terminal.

Ejemplo de uso:

$ yes hello-world

si corriendo

5. rev (Reversa)

Invierte cada cadena que se le da, lo que a veces es útil.

Ejemplo de uso:

$ rev
$ hello world!

revoluciones corriendo

Lo bueno es que no tienes que instalar nada.

6. Wiki

Esta utilidad de Linux se utiliza para buscar artículos de Wikipedia desde la línea de comandos.

Lo único que tienes que hacer para usar es ejecutar el comando con el término de búsqueda que deseas obtener la información.

URL: https://www.tecmint.com/wikipedia-commandline-tool/

Cómo instalarlo:

# Debian/Ubuntu$ sudo apt install nodejs	$ sudo npm install wikit -g

Ejemplo de uso:

Wikit matrix

corriendo

7. pdf

Esta herramienta es una excelente alternativa al comando “df”. Muestra la cantidad de espacio en disco utilizado y disponible en un sistema de archivos de Linux, al igual que el comando df, pero con diferentes colores, y también le permite personalizar los resultados.

Tenga en cuenta que está escrito en Python.

URL: https://pypi.org/project/pydf/

#Ubuntu# only if you do not have phyton installed:
$ sudo apt install python3-pip
$ pip install pydf

pdf ejecutando

8. basura-cli

Trash-cli es una interfaz de línea de comandos que desecha archivos y registra la ruta absoluta original, la fecha de eliminación y los permisos.

URL: https://github.com/andreafrancia/trash-cli

Cómo instalarlo:

# Debian/Ubuntu systems
$ sudo easy_install trash-cli

Ejemplo de uso:

# We create an example file named file1
$ echo "hello world!" > file1
$ trash-put file1
#
$ trash-list

Comandos disponibles:

$ trash-put           #trash files and directories.
$ trash-list          #list trashed files.
$ trash-restore       #restore a trashed file.
$ trash-rm            #remove individual files from the trashcan.
$ trash-empty         #empty the trashcan(s).

basura-cli corriendo

9. eSpeak NG

eSpeak NG es un software gratuito y de código abierto que se puede utilizar para convertir texto a voz en inglés y otros idiomas. Se basa en el motor eSpeak creado por Jonathan Duddington.

URL: https://github.com/espeak-ng/espeak-ng

Cómo instalarlo:

# Ubuntu
$ apt-get install espeak

Ahora, digamos la línea "¡Hola, Kesk!" y grábelo en el archivo de audio hello.mp4:

$ espeak "Hi Kesk!" -w hello.mp4 -g 60 -p 70 -s 100 -v en-us

También puede especificar el archivo de texto que desea grabar.

$ espeak -f example.txt -w example.mp4 -g 60 -p 70 -s 100 -v en-us

Ahora todo lo que tienes que hacer es jugarlo con tu aplicación favorita, y listo.

10. miradas

Esta utilidad de monitoreo del sistema de línea de comandos le permite monitorear la CPU, el promedio de carga, la memoria, las interfaces de red, la E/S del disco, los procesos y la utilización del espacio del sistema de archivos.

La utilidad Glances está escrita en Python y utiliza la biblioteca psutil para obtener información del sistema y mostrarla en un formato amigable.

También nos permite establecer diferentes umbrales de alerta mediante un archivo de configuración.

Muy útil para tenerlo todo bajo control.

URL: https://nicolargo.github.io/glances/

Cómo instalarlo:

$ sudo apt install glances

Ejemplo de uso:

$ glances

miradas corriendo

11. arriba

La utilidad gtop es un monitor del sistema Linux que muestra diversa información sobre el sistema y sus procesos.

La herramienta es fácil de usar y consume muy pocos recursos, por lo que podemos tenerla funcionando sin gastar recursos. Además, muestra la información de una forma bastante llamativa y precisa ya que utiliza comandos del sistema operativo.

Es una herramienta de código abierto desarrollada en JavaScript por Can Güney Aksakalli, y necesitará tener instalado nodejs en su computadora para instalarlo y ejecutarlo.

URL: clon de git https://github.com/aksakalli/gtop.git

Cómo instalarlo:

$ sudo npm install gtop -g

Ejemplo de uso:

$ gtop

corriendo

12. factor

Al igual que la utilidad anterior, este pequeño programa viene por defecto y puede ser de ayuda en algún momento.

funcionamiento del factor

Si conoces alguna utilidad de línea de comandos de Linux o algún comando que te ayude especialmente y no sea muy conocido, te agradecería que nos lo comentaras.

¡Gracias!

Fuente: https://medium.com/codex/12-awesome-linux-commands-utilities-49ab56588a84

#linux 

12 Increíbles Comandos Y Utilidades De Linux