teleren/devto huggingface dataset:
form_with without JS
Tags: ruby
Published: 2020-03-10 20:15:33

Last week I was working on a web app to link condition reports and photos with snowpack data from the date and location of the report. The app was built entirely with Ruby on Rails, and I ran into a bug when I tried to use a search form built with `form_with`.  The generic search form solution from [RailsGuides](https://guides.rubyonrails.org/form_helpers.html) seemed like it should work great. Working from the generic form, I got to this point:
```
<%= form_with(url: "/search", method: "get") do %>
    <%= label_tag("Choose locations:") %>
    <%= collection_select(:location, :id, Location.all, :id, :name) %><br>
    <%= label_tag(:min, "Minimum Snow Depth (in):") %>
    <%= number_field_tag(:min) %><br>
    <%= label_tag(:max, "Maximum Snow Depth (in):") %>
    <%= number_field_tag(:max) %><br>
    <%= submit_tag("Search Posts") %>
<% end %>
```
Having used `form_for` and `form_tag` in the past, the syntax looked familiar, but when I submitted a search, nothing happened! I knew I was hitting the right route and my log even said that it was rendering the results page. But no new page was rendered.

Enter the `:local` option. By default, `form_with` submits are XMLHttpRequest (XHR) objects - put another way, they are AJAX requests. The main benefit of AJAX (Asynchronous JavaScript And XML) is that it communicates with the server and renders new data without a full page refresh. The first line of html generated from my original `form_with` with default options looks like this:
```html
<form accept-charset="UTF-8" action="/search" data-remote="true" method="get">
```
The `data-remote="true"` bit tells Rails to submit the data as an AJAX request. But without Javascript in the mix, this default option was causing problems.

In order to disable the default remote submits, add `local: true` as an option to the form, like so: 
```
<%= form_with(url: "/search", method: "get", local: true) do %>
```
After that, my results page rendered as expected.
Coquette: 450 icons live from 2009
Tags: icons
Published: 2020-03-10 19:58:37

I made a small modification on an old program to add a new button. Since this project is a bit old, it uses the "Coquette" icons that I liked at that time. It's a set of 450 pretty and very colorful icons, with a little casual side that made it easy to get a good quality user interface.

These icons are available in "old" formats (ICNS, ICO and PNG) and in several sizes (16x16px, 32x32px, 48x48px, 64x64px and 128x128px). I had a copy of all the icons in 24x24 pixels and I picked one from time to time. Then I changed my PC, switched to other icons and lost this backup.

As it was not easy to find all the icons proposed by [DryIcons](https://dryicons.com/), I write here the list of the 9 packs they had created:

* [https://dryicons.com/icon-packs/coquette-icons-set](https://dryicons.com/icon-packs/coquette-icons-set)
* [https://dryicons.com/icon-packs/coquette-part-2-icons-set](https://dryicons.com/icon-packs/coquette-part-2-icons-set)
* [https://dryicons.com/icon-packs/coquette-part-3-icons-set](https://dryicons.com/icon-packs/coquette-part-3-icons-set)
* [https://dryicons.com/icon-packs/coquette-part-4-icons-set](https://dryicons.com/icon-packs/coquette-part-4-icons-set)
* [https://dryicons.com/icon-packs/coquette-part-5-icons-set](https://dryicons.com/icon-packs/coquette-part-5-icons-set)
* [https://dryicons.com/icon-packs/coquette-part-6-icons-set](https://dryicons.com/icon-packs/coquette-part-6-icons-set)
* [https://dryicons.com/icon-packs/coquette-part-7-icons-set](https://dryicons.com/icon-packs/coquette-part-7-icons-set)
* [https://dryicons.com/icon-packs/coquette-part-8-icons-set](https://dryicons.com/icon-packs/coquette-part-8-icons-set)
* [https://dryicons.com/icon-packs/coquette-part-9-icons-set](https://dryicons.com/icon-packs/coquette-part-9-icons-set)

Maybe I could have upgrade to a modern set of icons, but that wasn't my goal. Plus, I realise that I still like them and that 10 years later they're almost retro...

---

This post was originally published on [blog.pagesd.info](https://blog.pagesd.info/2020/03/10/coquette-450-icons/).
Cover image: [DryIcons](https://dryicons.com/).
Nevertheless, Lorna Coded
Tags: wecoded, womenintech
Published: 2020-03-10 18:00:26

Bit late to the party, but thought I would contribute anyway. 😜

I've always felt the need to prove myself mainly due to being a woman developer. I think this is more to do with me, and me feeling the need too with being in a male dominated environment. Luckily, I’ve never felt excluded for this reason, but have however had (very few) unnecessary remarks - few years ago now.

In the past 2 years, I've had to fight for a pay rise as I never get the promotional increase going from junior to mid. Even that promotion I had to fight for it. It took over 1.5 years to get what I deserved. I found during that time I became extremely motivated to learn new things like Angular and setup some side projects in my own time. Ultimately, found a new job too. 💃

When I’ve been asked what I do for work, from men it’s always a shock (every time) and women a sense of empowerment and interest. But why is it always a shock? 😮

## Why development? 🤔

I don’t remember what sparked my interest in pursuing a software development course at college. But I do remember open day, I asked my mum to come with me as I was so nervous. I had no idea what to expect and I was so incredibly shy. There was me and another girl for the 2 year course. 

During my 4 year university course (computing BSc (Hons)), I had a placement year as a software developer and both at the job and course I was the only girl. There were 2 other girls at the start of the course but didn't go through to 2nd year. Post uni, I jumped into a junior software developer role for 1.5 years and, again, the only girl. I then joined another company for just over 3 years (where I am today, moving to a new job soon) and have worked with 2 female devs. Both were over a very short time separately - a few months.

I've always liked computers, and this passion grew. I feel fortunate to have not had the same experience in the development world compared to some of the stories I've read (on dev.to). I was shocked and saddened to see how far people go with their vile comments.

## Achievements 🎉
Things I'm proud to have achieved over the past year.

- Junior to mid level developer
- Motivation - the past year I have been able to develop side projects (not fully complete) for fun and to increase my knowledge and is now very much a hobby. I found it very difficult to get running with this as typically the last thing I wanted to do after a full day at work, is more work
- Learning .NET Core, Angular 8, Git and Netlify
- My website - almost complete and using Angular 8

## What I'm excited about 😃
Things I'm excited about in the near future.

- Starting new job as a .NET Developer within next few weeks
- Finishing off a couple side projects
- Learning new stuff like Node.js

## Final thoughts 😎

Once painfully shy, now confident, I know I have found my passion and career I want to do forever. I love programming and cannot imagine doing anything else. **I am proud to be a woman in tech.** 🙌
How to add the DayNight Theme to an Android app using Kotlin
Published: 2020-03-10 19:17:30

The DayNight functionality in AppCompat allows your app to easily switch between a dark ⚫ and light ⚪ theme.
Also, the DayNight theme gives an app the cool capability of switching color schemes based on the time of day and the device's last known location.

###*Benefits of DayNight Theme*###

1: Saves battery life 
2: reduce the risk of damaging the eyes
3: easily accessible at night 
4: increasing usability for people with reduced-vision

###*Learn to use Androidx DayNight Theme*###

Step 1 ) Update styles.xml

 ```
<style name="AppTheme" parent="Theme.AppCompat.DayNight.DarkActionBar">

```

The themes you can extend from to add day night theme switching capability are the following:

"Theme.AppCompat.DayNight"
"Theme.AppCompat.DayNight.NoActionBar"
"Theme.AppCompat.DayNight.DarkActionBar"

Step 2 ) Update MainActivity code

To switch the theme, call the AppCompatDelegate.setDefaultNightMode(int) method from your Kotlin code. (This will change the color scheme for the whole app, not just any one activity or fragment.) For example:

```
AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)
```

###*Note:*###

AppCompatDelegate.MODE_NIGHT_NO: 
this sets the default theme for your app and takes the colors defined in the res/values directory. It is recommended to use light colors for this theme.

AppCompatDelegate.MODE_NIGHT_YES: 
this sets a night theme for your app and takes the colors defined in the res/values-night directory. It is recommended to use dark colors for this theme.

AppCompatDelegate.MODE_NIGHT_AUTO: 
this auto switches the colors of the app based on the time of the day and the colors you have defined in values and values-night directories.




###*Note:*###

however, that the theme switch will not persist if you kill the app and reopen it. If you do that, the theme will switch back to AppCompatDelegate.MODE_NIGHT_AUTO, which is the default value. If you want the theme switch to persist, make sure you store the value in shared preferences and load the stored value each time the app is opened after it has been destroyed.

[GitHub](https://github.com/wise4rmgod/DayNightTheme_Example)
React Component Lifecycle Events using React Hooks
Tags: react, javascript, hooks, reacthooks
Published: 2020-03-10 19:09:36

---
title: React Component Lifecycle Events using React Hooks
published: true
description: Implement basic react component lifecycle events using react hooks in a functional component
tags: react, javascript, hooks, reacthooks
---

TL;DR: Full credit to this Stack Overflow answer:

{% stackoverflow 54655508 %}

While working on my side project, of which I wrote in my series [The Lean Startup hands on](https://dev.to/nicolasini/the-lean-startup-hands-on-1nbi), I came across a new challenge. I wanted to reload the content of a functional component when its props changed.

It is great when a side project brings you opportunities to learn new things. In this case I needed to learn how to implement what I would normally do via a Lifecycle Event in a React Class Component, but using React Hooks in a Functional Component.

As my usual way of looking for answers, I first turned to Stack Overflow. A quick search, linked above, gave me all I needed to know and more. How to implement basic lifecycle events using the `useEffect` hook. So here they are.

## componentDidMount

```javascript
useEffect(() => {
  // Your mount code here
}, []);
```

## componentDidUpdate

```javascript
useEffect(() => {
  // Your update code here
}, [yourDependency]);
```

## componentWillUnmount

```javascript
useEffect(() => {
  // Your mount code here

  return () => {
    // Your unmount code here
  }
}, []);
```
Are reducers split too specific?
Tags: react, redux
Published: 2020-03-10 19:08:52

I have `glossaryReducer`. 

This reducer is responsible for fetching the glossary, adding terms to the glossary, and removing terms from the glossary.

It's state consists of `{glossaryData:[], isFetching:false, isAddingTerm:false, isRemovingTerm:false}`

Basically, glossaryReducer handles functionality having to do with the glossary.

Alternatively, I could have three reducers: `fetchGlossaryReducer, addTermReducer, removeTermReducer`. Each reducer can have the state `{isFetching:false}`.

Does splitting up reducers this specific make sense? Imaging I am building a medium to large scale application.
How to use same state for multiple controlled components in react hooks 
Tags: javascript, react
Published: 2020-03-10 18:52:42

In React class component we can use same event handlers to update state for multiple controlled components using `event.target.name`

As below

```
class App extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      name: "",
      address: "",
      occupation: ""
    };
    this.handleEventChange = this.handleEventChange.bind(this);
  }

//Same event handler for all the three input field
  handleEventChange(event) {
    this.setState({ [event.target.name]: event.target.value });
  }

  render() {
    const { name, address, occupation } = this.state;
    return (
      <>
        <>
          Name:{" "}
          <input name="name" value={name} onChange={this.handleEventChange} />
        </>
        <>
          Address:{" "}
          <input
            name="address"
            value={address}
            onChange={this.handleEventChange}
          />
        </>
        <>
          Occupation:{" "}
          <input
            name="occupation"
            value={occupation}
            onChange={this.handleEventChange}
          />
        </>
      </>
    );
  }
}

```

But in react hooks we might not be able to use the above mentioned way if we are using different state for each of the controlled component using 'useState'

We can use the same state in hooks as well by using spread operator.

create an initialState object with the name of all the controlled component and initialise it to ourState using useState

As Below,

```
  const initialState = {
    name: "",
    address: "",
    occupation: ""
  };
  const [ourState, ourSetState] = useState(initialState);
```

We can use the spread operator to update the state using single event handler
As below,

```
  function handleEventChange(event) {
    ourSetState({ ...ourState, [event.target.name]: event.target.value });
  }

```

Hope this article helps in reducing some lines of code
The full code for react hooks is below.

```
function App() {
  //initial state for our common state
  const initialState = {
    name: "",
    address: "",
    occupation: ""
  };

  //initialise our state
  const [ourState, ourSetState] = useState(initialState);

  const { name, address, occupation } = ourState;

  //common event handler for all the controlled components.
  //using spread operator to update the state
  function handleEventChange(event) {
    ourSetState({ ...ourState, [event.target.name]: event.target.value });
  }

  return (
    <>
      <>
        Name: <input name="name" value={name} onChange={handleEventChange} />
      </>
      <>
        Address:{" "}
        <input name="address" value={address} onChange={handleEventChange} />
      </>
      <>
        Occupation:{" "}
        <input
          name="occupation"
          value={occupation}
          onChange={handleEventChange}
        />
      </>
    </>
  );
}
```

Happy Javascripting !!!
Should Twitter Have an Edit Button?
Published: 2020-03-10 18:49:19

Likely since Twitter's inception, some users have been asking for an edit button. Most people with a role in releasing software understand that user feedback is a critical part of the development process. This post serves as a list of questions that a Business Analyst or Product Manager may pose when a feature seems straightforward to external parties, but might be troublesome to implement.

* Would you indicate that a tweet had been edited?
 * If yes, how?
 * Is there a grace period, like reddit, where tweets that are edited within a certain time period aren't flagged as edited?
 * If yes, how much time do people have to make edits to tweets?

* Would you show the revision history of tweets?
 * If yes, how many times can someone edit a tweet?
 * How many versions are kept in the version history? 
 * Are other users allowed to like/retweet previous versions of a tweet?

* Regarding likes and retweets: assume User A retweets User B, and User B edits the tweet.
 * Does it stay in its original version, or does the retweet get updated with the edits? 
 * Could users have a setting that instantly un-retweets any tweet they retweeted that was edited? 
 * What happens to likes, replies, and quote-tweets?

* Should the media attached to a tweet (pictures, videos, gifs) be editable?

* If a tweet is reported, then edited, does the reported version of the tweet get reported to Twitter HQ? 
 * Can the user reporting the tweet still see the original tweet that was reported?
 * If a tweet is reported, could it be edited to remove the content that breaks Twitter’s Terms of Service?
 * If revision history is enabled, would the reported tweet show in the history, or only the versions that are not in violation of the Terms of Service?

Personally, I find utility in the permanence of Twitter, and I can only hope that this will continue.
Setting up a code formatter in an iOS project
Tags: swift, formatter, ios, git
Published: 2020-03-10 18:36:38

People come and go, but projects stay. Having a uniform and idiomatic codebase is nicer, eases the onboarding of new developers and lets them to entirely focus on what matters the most while writing code or reviewing others.

There are really good Swift code formatters out there, like [SwiftFormat](https://github.com/nicklockwood/SwiftFormat) and [swift-format](https://nshipster.com/swift-format/). We are using SwiftFormat at [The Agile Monkeys](https://theagilemonkeys.com). This is how we configure it for an iOS project as a **pre-commit hook**. 

Wait! But why adding it as a pre-commit hook?

Because we don't want this to run entirely on every local build (if the formatter was added as a build phase), but once we are going to commit new code. Besides, we want the formatter to interfere with our editor undo history the less as possible. The downside of the pre-commit approach is that every developer on the project would need to add the pre-commit hook file manually (once).

The ideal thing is to have this integrated into the CI process with [Danger](https://danger.systems/swift/) and let it commit the formatted changes for you in each Pull Request. This is how you can do it, for example, with Bitrise + Danger: https://blog.bitrise.io/danger-danger-uh-that-is-using-danger-with-bitrise

But if you don't want to pay for any extra seats in your Github account or you don't want anything else in the pipeline to be changing files on behalf of the developers, the pre-commit hook is nice too. 

Let's see how to do it!

First, you need to install the command-line tool:

```
brew install swiftformat
brew upgrade swiftformat
```
Next, add the pre-commit hook:

- Edit or create a *.git/hooks/pre-commit* file in your project folder. The .git folder is hidden but should already exist if you are using Git in your project. Open it with the terminal or the *Finder's Go > Go to Folder...* menu.

- Add the following code in the pre-commit file: 

```
git diff --diff-filter=d --staged --name-only | grep -e '\(.*\).swift$' | while read line; do
  swiftformat "${line}";
  git add "$line";
done
```

- Enable the hook:

```
chmod +x .git/hooks/pre-commit
```

The pre-commit hook will now run whenever you run *git commit*. Running *git commit --no-verify* will skip it. 

Note: GUI git clients do not know your environment/shell. I'm using Tower as my GUI git client so I needed to add this line at the top of the pre-commit file:

```
PATH="$PATH:/usr/local/bin"
```

To get default set of formatting rules (which are pretty good and idiomatic) you don't need to do anything else. In case you want to adapt it to your needs, you can create and add rules to a .swiftformat file in your project path. You can find the rules reference in: https://github.com/nicklockwood/SwiftFormat/blob/master/Rules.md

Finally, perform the first full project formatting:

```
swiftformat .
```


Enjoy the homogeneity!
Small projects for the long-term
Tags: productivity
Published: 2020-03-10 18:33:35

Many open-source enthusiasts are familiar with the name "Sindre Sorhus". [Sindre](https://sindresorhus.com) is a Norwegian developer with [more than 1,000 packages on NPM](https://www.npmjs.com/~sindresorhus) and [over 46,000 Twitter followers](https://twitter.com/sindresorhus/followers). He created [chalk](https://github.com/chalk/chalk) for coloring terminal output. His project [ava](https://github.com/avajs/ava) helps with running JavaScript tests. He also spearheads the popular [awesome lists collection](https://awesome.re) on GitHub.

When asked how he "gets so much done", he responded,
> ...I think making [small focused reusable modules](https://github.com/sindresorhus/ama/issues/10#issuecomment-117766328) has had the biggest impact on my productivity....

This statement has had a big impact on me recently. I've found that if I finish small goals often, I get more satisfaction than if I would have gotten with a large, never-ending project. I even revisited some old creations, and touched them up. I hope it makes your life more effective as well.

---

**See also:**
{% medium https://blog.sindresorhus.com/small-focused-modules-9238d977a92a %}
Pushing myself to C++
Tags: cpp, c, embedded
Published: 2020-03-10 18:31:32

I have been developing and designing embedded devices for quite a few years now. I started out using C exclusively, then started mixing in assembly (which I still love!). For quite a long time, I was one of those grumblers complaining about object oriented stuff not belonging on embedded hardware. (I still have yet to be convinced that CircuitPython or Rust on microcontrollers is a good idea, but that's another story altogether).

But then a friend of mine wrote and published a book targeted pretty much directly at developers like me -- [Hands-On Embedded Programming with C++17](https://www.amazon.ca/Hands-Embedded-Programming-versatile-solutions/dp/1788629302). I started reading it, and decided what the heck, I'll give it a try. (Maya is a great writer, by the way!) So I created a new folder in my ~/workspace folder (which is a big commitment) and created a simple C++ program for the AVR ATmega328p. I chose that processor because I have about a thousand random Arduino clones laying around, and about a hundred AVR programmer clones also, making it very easy to use a quick and dirty dev platform.

I created a (gasp) *class* for the peripheral I was using! I even made a (shock and horror) *constructor function* for that class! Typedef structs full of function pointers, this is not. Though I still struggle with understanding some of the more advanced OOP concepts, and though I still fall back to C and/or assembly when I need to get something done fast, I've been forcing myself to use C++ more and more for my personal hacking projects.

I must say, from an organizational point of view, having abstraction for peripherals in a microcontroller is very appealing to me. The classic C way of doing the same task is to create a separate .c and .h file for each peripheral, and then create a struct type with the important functions and variables that the peripheral needs. This has some obvious downsides -- primarily the fact that people seem to panic whenever function pointers are mentioned, but also that managing multiple instances of that struct type can be costly and complex, especially if it's implemented as an API for others to use.

I'm still working my way into things like inheritance and operator overloading, which seem very neat as well. What I am worried about, however, is my ability to quickly prototype new things. I find that it takes me longer to write the equivalent C++ code, though this is likely just due to being less familiar with the language features, and may disappear over time. But to get to that level of familiarity, I need to force myself to use C++ in my personal projects, which again can be difficult if I just want to get something done.

I would love to hear about other embedded developers who have transitioned to using C++ from C, and whether their initial attempts looked like C++ code that got in a trainwreck with a C codebase.