teleren/devto huggingface dataset:
Learn Dart #5: Read and Write files in under 30 seconds
Tags: dart, showdev, beginners, webdev
Published: 2018-11-01 12:15:59

---
title: Learn Dart #5: Read and Write files in under 30 seconds
published: true
description: Learn how to use the File object to read and write files
tags: dart, showdev, beginners, webdev
cover_image: https://thepracticaldev.s3.amazonaws.com/i/ejz8st55kgd8gjexnqoe.png
series: Dart in under 30 seconds
canonical_url: https://creativebracket.com/read-and-write-files-in-under-30-seconds/
---

In today's quick tip, we will learn how easy it is to read and write files in Dart. We will use the `File` object of the 'dart:io' library to achieve this.

To follow along, generate the **console-full** project with stagehand:

```bash
$ mkdir my_app && cd my_app
$ stagehand console-full
```

See the solution in action below:

{% youtube UmmSXFFMjFU %}

Here's the full solution:

```dart
import 'dart:io';

main() async {
  var file = File('data.txt');
  var contents;

  if (await file.exists()) {
    // Read file
    contents = await file.readAsString();
    print(contents);

    // Write file
    var fileCopy = await File('data-copy.txt').writeAsString(contents);
    print(await fileCopy.exists());
    print(await fileCopy.length());
  }
}

```
---

# Extending the example

## 1. How to better specify the file path

Install the `path` package by adding the dependency to your `pubspec.yaml` file:

```yaml
dependencies:
  path: ^1.6.2
```
And running `pub get` in your terminal.

Import this at the top of `bin/main.dart` and amend the path as follows:

```dart
import 'dart:io';
import 'package:path/path.dart';

void main() async {
  var pathToFile = join(dirname(Platform.script.toFilePath()), '..', 'data.txt');
  var file = File(pathToFile);
  ..
  ..
}
```

## 2. How to read the file line by line

We can create a stream to read the file:

```dart
import 'dart:convert'; // Contains the `Utf8Decoder` and `LineSplitter` stream transformers
..
..
  if (await file.exists()) {
    // Read file
    contents = StringBuffer();
    var contentStream = file.openRead();

    contentStream
      .transform(Utf8Decoder())
      .transform(LineSplitter())
      .listen((String line) => contents.write(line), // Add line to our StringBuffer object
        onDone: () => print(contents.toString()), // Call toString() method to receive the complete data
        onError: (e) => print('[Problems]: $e'));
    ..
    ..
  }
..
..
```
A good use case for this would be processing a file containing environment variables, like the file contents below:

```dart
PORT=8080
API_KEY=lkjsk453lkslfkl5
API_USER=jermaineo
```

---

Please leave your feedback in the comments, and let me know what you would like to see demonstrated next!

**Subscribe to [the Youtube channel](https://www.youtube.com/channel/UCHSRZk4k6e-hqIXBBM4b2iA?view_as=subscriber) for upcoming videos on Dart**. Thanks!

Like, share and follow me 😍 for more content on Dart.

Further reading:

1. [The File class](https://api.dartlang.org/stable/2.0.0/dart-io/File-class.html)
2. [**Free Dart screencasts on Egghead.io**](Free Dart Screencasts on Egghead.io)
Challenge yourself this #codevember!
Tags: challenge, webdev, css, javascript
Published: 2018-11-01 10:16:38

---
title: Challenge yourself this #codevember!
published: true
description: Over the last few years in the developer world, November has been taken over by a creative coding challenge called Codevember. I'm attempting Codevember myself this year, and hopefully, after reading this you will challenge yourself too!
tags: challenge, webdev, css, javascript
cover_image: https://thepracticaldev.s3.amazonaws.com/i/jx96j01thukjaaz5v8b2.png
---

Over the last few years in the developer world, November has been taken over by a creative coding challenge called Codevember. I'm attempting Codevember myself this year, and hopefully, after reading this you will challenge yourself too!

## What is Codevember?
Codevember is a challenge by [Arthur Rob](https://twitter.com/Arth_Rob) and [Valentin Daguenet](https://twitter.com/vdaguenet) which invites developers to post a new creative piece of code for every day of November.

![Codevember website](https://thepracticaldev.s3.amazonaws.com/i/hp16pcso4228zcm5gvfd.png)

The [Codevember website](http://codevember.xyz) has a list of hints for each day of the month, e.g. *1. Infinity*, *2. Time* and *3. Carrot*. Using the hint, participants come up with a creative bit of code inspired by the word. For example, for the hint *Music*, you could create a usable piano with JavaScript.

## Why should I do Codevember?
Here are a few reasons why you should partake:
- Gives you a chance to experiment with new technologies that you might not always have a chance to
- Helps expand your knowledge of HTML, CSS and JavaScript whilst having fun
- After 30 days you will have a collection of code creations that you can be proud of

## How can I do Codevember?
The Codevember team aim to make the challenge as accessible as possible and allow you to submit your creations using any platform/tool you like.

![Codevember on Codier](https://thepracticaldev.s3.amazonaws.com/i/ndpdcff7j4jcmmwepwli.png)

If you want to get your work featured on the Codevember website, you can do so in a few ways. To attempt [Codevember on Codier](https://codier.io/challenge/codevember-2018), post a solution each day with the hashtag #codevember and the day of the month e.g. *#codevember - 12 - My awesome work*. CodePen users can get their pen's featured with the same title format. Alternatively, you can [submit your work](http://codevember.xyz/about) directly to the Codevember site.

And don't worry if you have missed a day or two, you can join in whenever!
Canary Deploy to AmazonECS / Fargate
Tags: amazonecs, fargate, canarydeploy
Published: 2018-11-01 09:34:56

---
title: Canary Deploy to AmazonECS / Fargate
published: true
description: Introducing the way to deploy to AmazonECS/Fargate, and the script for deployment.
tags: AmazonECS, Fargate, CanaryDeploy
---


I tried very hard to configure canary deploy to AmazonECS/Fargate. This is how I implemented this.

Full version of the deploy script is here. [HiromuMasuda/ecs-deploy](https://github.com/HiromuMasuda/ecs-deploy)

# App Architecture on ECS

Main app is DSP, and datadog and flume are run with DSP. Request from SSP goes to ELB and is distributed to DSPs in three tasks.

![ECSdeploy1](https://thepracticaldev.s3.amazonaws.com/i/dgbxjjl35157nvtjsdu2.png)


# About Deployment

Deploy flow is shown below. First, do canary deploy to check whether the latest version of image works well.

![ECSDeploy2](https://thepracticaldev.s3.amazonaws.com/i/thfyiossqjuw9os65cqb.png)

# Canary Deploy

1. Build latest image from Dockerfile.
2. Push the image to ECR with timestamp and git commit hash tags.
3. Make new revision of task definition with the image.
4. Run one task with the task definition. This task is separated from service.
5. Add the private IP of the task to target group.

![ECSDeploy3](https://thepracticaldev.s3.amazonaws.com/i/hafj9c0coievr2c58oro.png)

# Canary Rollback

1. Stop and destroy the canary deployed task.
2. Remove the IP from target group.

![ECSDeploy4](https://thepracticaldev.s3.amazonaws.com/i/9mq2xf1z1lvb4ifomawo.png)

# Deploy

1. Update service using the latest revision of task definition.
2. Stop and destroy the canary deployed task.
3. Remove the IP from target group.

![ECSDeploy5](https://thepracticaldev.s3.amazonaws.com/i/9xcjomr792sdh483lcd8.png)

# Rollback

1. Update service using the previous revision of task definition.

![ECSDeploy6](https://thepracticaldev.s3.amazonaws.com/i/3l8esdxh8rc44qs82ier.png)
Step by step React, NodejS and MySQL Simple Full Stack Application 2018 (part: 2)
Tags: intro, mysql, database, tables
Published: 2018-11-01 09:12:28

---
title: Step by step React, NodejS and MySQL Simple Full Stack Application 2018 (part: 2)
published: true
description: in this article I describe about making new database and tables in MySQL database.
tags: # intro #MySQL #database #tables
---
<h4>in this article I describe about making new database and tables in MySQL database.</h4>
* To make a new database on MySQL workbench press database icon in top navbar.It’s like:<h5> writing  CREATE SCHEMA nameOf_db;</h5>  command on mysql command line
<img src="https://thepracticaldev.s3.amazonaws.com/i/47qe84u14mpbmrbrndwh.png"/>
* Then insert your new database name and press apply button:
<img src="https://thepracticaldev.s3.amazonaws.com/i/z7s70ce3zuoe5gdk0jz6.png"/>
* Now in sidebar find name of your database and right click on it to see create tables option, then click on it:
<img src="https://thepracticaldev.s3.amazonaws.com/i/g1753ykuqim0xbulzz87.png"/>
* in opened window write table name and name of fields in that table and type of data for each field:
<img src="https://thepracticaldev.s3.amazonaws.com/i/bilf44fs2qjdmrvlrywv.png"/>
Before continue it's useful to know about data type in sql:
* CHARACTER [(length)] or CHAR [(length)] --->  strings, including Unicode
* VARCHAR (length) ---> string
* NVARCHAR (lenght) ---> string with other language string
* BOOLEAN --->  TRUE or FALSE
* SMALLINT ---> integer value between the range 2^ -15 and 2^15 -1
* INTEGER or INT ---> integer value between the range 2^ -31 and 2^31 -1
* DECIMAL ---> Precision defaults to 38, Scale defaults to 0
* DECIMAL(p) ---> Scale defaults to 0
* DECIMAL(p, s) ---> Precision and Scale are defined by the user
* NUMERIC [(p[,s])] ---> same way as the DECIMAL data type
* REAL ---> approximate numeric values, up to a precision of 64
* FLOAT(p) ---> approximate numeric values
* DOUBLE PRECISION ---> approximate numeric values
* DATE ---> date values  YYYY-MM-DD
* TIME --->  time values HH:MM:SS
* TIMESTAMP ---> timestamp values YYYY-MM-DD HH:MM:SS
* CLOB [(length)] or CHARACTER LARGE OBJECT [(length)] or CHAR LARGE OBJECT [(length)] ---> character strings longer than those that are allowed in the CHARACTER [(length)] or VARCHAR (length) data types
* BLOB [(length)] or BINARY LARGE OBJECT [(length)] ---> binary values
we can also use MySQL command prompt to add below codes and create this table without workbranch:
<img src="https://thepracticaldev.s3.amazonaws.com/i/ddgxy6y40suy9wuhf2nl.png"/>









resources:
http://www.cs.toronto.edu/~nn/csc309-20085/guide/pointbase/docs/html/htmlfiles/dev_datatypesandconversionsFIN.html
How to Organize Your CSS with a Modular Architecture (OOCSS, BEM, SMACSS)
Tags: css, showdev, discuss
Published: 2018-11-10 16:58:35

---
title: How to Organize Your CSS with a Modular Architecture (OOCSS, BEM, SMACSS)
published: true
tags: css, showdev, discuss
canonical_url: https://snipcart.com/blog/organize-css-modular-architecture
---

![How to Organize Your CSS with a Modular Architecture (OOCSS, BEM, SMACSS)](https://snipcart.com/media/203929/oocss-css-architecture.png)

> This is a guest post on our blog by [Claudio Mendonca](https://www.linkedin.com/in/claudioccm/), a frontend designer based in Montréal. He really did a solid job with it, so I wanted to give it some exposure here! Enjoy. 🙇‍♂️

I loved Lego blocks.

They were by far my favorite toys—had loads of ‘em!

See, I’m a designer, son of a designer. Lego blocks were our first creativity sandbox: they allowed us to assemble all sorts of crazy things.

I didn’t know why I loved them so much back then. But now I do.

It wasn’t their colors, or their 7K pieces Millennium Falcon. Nope.

![millennium-falcon-lego-2000](https://snipcart.com/media/203928/millennium-falcon-lego-2000.jpg)

It was how *perfectly* each piece fit together, in every possible way.

*What if we could create interface pieces that behaved more like Lego blocks?*

This would speed up our frontend development, making it more robust, more organized. Our HTML would get smaller, and our CSS would get MUCH more manageable.

**In this article, I’ll show you how to organize your CSS architecture into HTML/CSS blocks that behave more like Lego blocks.** 

To do so, I’ll introduce three important modular CSS methodologies:

- OOCSS
- [BEM](https://snipcart.com/blog/cart-customization-sass-bem-low-specificity)
- SMACSS

These will help us create interface components that are easier to understand, maintain and reuse.

I’m betting these will become part of your workflow, regardless of the frontend framework you’re using. [*If*](https://snipcart.com/blog/learn-vanilla-javascript-before-using-js-frameworks) you’re using one, that is.

## Know thy acronyms (OOCSS, BEM, SMACSS)

> Ancient CSS Joke - Two CSS rules enter a bar. A bottle falls in a totally different bar.

### What is OOCSS?

![OOCSS CSS architecture](https://snipcart.com/media/203929/oocss-css-architecture.png)

Object Oriented CSS (OOCSS)—and everything that comes with this paradigm shift—is the conceptual foundation for better interface design and development. It states that interfaces are made of multiple components, which should be re-used as much as possible.

[...]   

→ Read the full post [here](https://snipcart.com/blog/organize-css-modular-architecture)
How to find word in string in mLab and MongoDB
Tags: index, mlab, mongodb, querywordinstring
Published: 2018-11-01 06:06:44

---
title: How to find word in string in mLab and MongoDB
published: true
description: How to use indexing in mLab and MongoDB as well as setting it up in your routes
tags: index, mLab, MongoDB, query-word-in-string
---

If you are new to programming, you may not know what indexing is. It's actually everywhere around you, if a website has a database, it probably has indexing of some type enabled.

Let me present indexing! Indexing is a process that is run on a database in order to look for things more efficiently, much more efficiently! It does this by looking through all of the database and <i>map</i> the desired fields. Then these new "values/link pairs" are sorted in alphanumeric order. When you hit a keyword, it will go through this <i>ordered</i> list of mapped values and quickly look for your query (Google Big O notation for more details).


<h2>Now to the actual code that makes this work:</h2>
Example: We want to search for a word in fields "itemName" and "itemDescription" in our MongoDB database. There are other fields defined in our schema but you should not index more than you need as it will create redundant values/links and that would impact your database's query speed. We will use $text notation to look for word(s) in our indexed fields.

First, we have to have a function to run the $text query:
```javascript
const Inventory = require("./../models/inventory");

const queryResult = function(searchQuery) {
  Inventory.find({ $text: { $search: searchQuery } });
};

console.log(queryResult("shoes"));
```

Then, we have to our to our mLab/MongoDB database management, requires login (either through Heroku or mLab), select your collection > Indexes tab > Add Index:

![alt text](https://thepracticaldev.s3.amazonaws.com/i/mp0sfmmi3hkbj8sjvkh4.PNG)

Fill out the desired fields to index, in our case, we are indexing "itemName" and "itemDescription" fields in our database collection; "text" is required to enable the $text notation.

![alt text](https://thepracticaldev.s3.amazonaws.com/i/kcxguolabyfljedl70tx.PNG)

Finally, hit Create in Background, you will get a popup prompting it may take a few minutes to several hours, depending on the size of your database and number of indexing fields.

That's it! Your site is still operational but until the indexing operation is still going on, you may notice performance issue, so best is to wait.

Thank you for reading my first post, let me know any questions/input/comments!
My experience with Development Cycles
Published: 2020-08-05 02:53:57

---
title: My experience with Development Cycles
published: true
tags: 
canonical_url: https://jmoore53.com/2018/11/01/dev-cycles.html
---

The first release of any my dev cycle feels like garbage. Whether it’s integrating a new api or library to building on an idea that’s not all the way flushed out, I often find my first iteration of a project gets thrown out.

This post describes some of the reasons why my first attempt on a proof of concept application isn’t a masterpiece.

## Unfamiliarity

Being unfamiliar with tools and new libraries has forced me to read more documentation and learn more about deploying multiple types of applications. This unfamiliarity has ultimately made me look at projects in a new way.

The unfamiliarity with libraries has made my applications delicate rather than hardened, and I often find myself searching deep in github issues on projects attempting to fix mangled together parts of an application. By the time I am in production, most of the tools are mangled together and on the edge of breaking.

## Library Versions featuring Brokenness

I often stay very up to date on library versions and pull most source code from repositories right off of github. With all these dependencies on other applications being tossed around, I sometimes find myself and my applications in a broken state because of dependency issues.

The most recent time I ran into an issue was upgrading a ruby project and running into some backwards compatability problems with methods. Methods were deleted that my application used and I essentially downgraded back to the older version to get the application back on track.

## Perfection

I have a high standard for production applications, and I prefer to have most of my application tested before tossing it into the wild. It also helps to have a web app with decent views, so I tend to spend a lot more time working on frontend pieces than I would prefer.

This often holds the processes of releases up as I like to ensure the application works before I push it out the door.

## Pipelines

I was bad about pipelines in the past and didn’t truly value them for what they do and how much time they save compared to `scp`-ing code to a machine and praying a deploy works and the libraries are the same. Looking ahead to containres, I now see the value in containerized releases. I am able to push my application to a container and run it on any machine. (Containers of today are the Java of Yesterday - Write Once, Run Anywhere)
Dynamic Nginx Configuration for Internal Proxy
Tags: nginx, puppet, erb, dns
Published: 2018-11-01 04:30:19

---
title: Dynamic Nginx Configuration for Internal Proxy
published: true
description: Creating a dynamic nginx configuration that allows for internal dns resolution
tags: nginx, puppet, erb, dns
---

Working around a home network can be challenging at times, especially when it comes to a secular ip address. Doing web and api development, this introduces an even greater problem in the fact that now theres only one entry point. To solve this I considered many options, the main being setting up a VPN, which would solve the problem, but would require additional setup on each client device. Instead I decided to investigate nginx and its reverse proxy ability. 

The design is simple, have a singular domain, with a wildcard mask that resolves to individual hosts inside the network. I then wanted to ensure https everywhere from the outside so utilizing [Blockchain Debugger guide](https://levelup.gitconnected.com/how-to-get-certbot-wildcard-certificates-3d25618a81e0), I set up a wildcard certificate at edge, and then allowed for non-certified traffic inside my network.

![Concept Design](https://www.lucidchart.com/publicSegments/view/b1562db2-2055-4746-808b-a0ff0dc63e1e/image.png)

I then utilized Puppet as a configuration management tool to deploy and ensure the nginx service is continually running. This also gave me templated configuration ability. Written in erb, the nginx config is a standard text file with variable input, but the key component is the the proxy_pass statement: 
```
proxy_pass https://$subdomain.<%= @internaldomain %>;
```Once this template gets laid down the `<%= @internaldomain %>` will resolve to my internal domain name. For example, let say my internal dns domain was home.com, and my external domain was example.com. If I attempted to send an http request to foo.example.com, the external dns would resolve to my home, which would then port forward to the nginx server. From there the proxy_pass statement would first derive the hostname foo, and proxy my request to foo.home.com.

{% gist https://gist.github.com/danquack/cc5d736af1378f6f17b9dd25bc30c0ac %}

Overall this design provides many benefits. The first being security, such that as long as the walls on the outside are sturdy, there is only one port in, and all traffic is secure. The second benefit is the ability to now have more domains accessible outside, alleviating the once blocker of external resources not able to get in.
Practicality Beats Purity - Pure SQL vs ORMs
Tags: practicality, engineering, sql, orm
Published: 2019-07-05 03:35:59

---
title: Practicality Beats Purity - Pure SQL vs ORMs
published: true
tags: practicality, engineering, sql, orm
canonical_url: https://tryexceptpass.org/article/practicality-beats-purity-4/
cover_image: https://tryexceptpass.org/images/spiral.jpeg
---

I’ve been using some form of a database throughout the entirety of my career. Sometimes single-file databases, sometimes full servers. Sometimes testing them, sometimes designing them, but a lot of times I was optimizing them. Even when learning programming with my dad, most of the apps I built were about storing and managing some type of data.

With all those years of experience, I definitely understand enough to know that I’m by no means an expert at any of it. There are several (an understatement) mechanisms by which folks make the best use of their database servers, almost all of them are tradeoffs in memory usage, space, look-up times, results retrieval, backup mechanisms, etc.

As expected, each database mechanism has their own quirks and optimizations, but the common theme is the language which you use to retrieve information: Structured Query Language (SQL). Different database engines implement different extensions to this language, some of which add powerful functionality, some of which just add confusion. But in general, SQL has been very successful in standardization across the industry.

This next chapter in the [Practicality Beats Purity](https://tryexceptpass.org/article/practicality-beats-purity-1) series covers the tradeoffs when using direct SQL queries to a database vs programming language abstractions that do it for you, like ORMs.

[Read on ...](https://tryexceptpass.org/article/practicality-beats-purity-4/)