teleren/devto huggingface dataset:
Laravel 8 Eloquent firstOrNew() Example
Tags: javascript, php, laravel
Published: 2022-04-06 08:32:04

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-firstornew-example

In this post, I will explain what is the usage of **Laravel Eloquent firstOrNew()** and its importance. Laravel provides **firstOrNew()** will help us to check the record in the database by the given attributes. However, if the model does not found, a new instance will return.

 

**Note:** That model returned by **firstOrNew** has not yet been saved to the database. You will need to manually add **save()** method to save it.

 

## Example without Laravel firstOrNew()

```php
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $title = 'Post 41';
        $post = Post::where('title', $title)->first();
  
        if (is_null($post)) {
            $post = new Post(['title' => $title]);
        }
  
        $post->description = 'Description for post 41.';
        $post->body = 'Body for post 41.';
  
        $post->save();
  
        print_r($post); die;
    }
}
```

## Example with Laravel firstOrNew()

```php
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $post = Post::firstOrNew([
            'title' => 'Post 41'
        ]);

        $post->description = 'Description for post 44.';
        $post->body = 'Body for post 41.';

        $post->save();

        print_r($post);die;
    }
}
```


As you can see between the two examples above using Laravel **firstOrNew()** method we don't need additional checking if the returned instance is nulled.

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-firstornew-example if you want to download this code.

Happy coding :)
Write a language in a week - Theory
Tags: challenge, writing, programming, language
Published: 2022-04-06 08:28:00

> Warning! This article is still under construction!

To fully understand something, one must ask *why* until the most fundamental concepts unfolds.
Let's start with the most basic question.

## What is a programming language?
> A programming language is a formal language used by humans to write computer programs, consisting of a set of rules that define the structure. In addition to the languages themselves, a **compiler** is used to convert the program written in the language into a form that can be executed by a computer (a machine), or directly evaluated by an **interpreter**.

From the information given above, we can deduce that a programming language is simply the structural rules of the programs.
Like natural languages such as English, German, French, Spanish, etc., many programming languages share similar syntax and semantics, and use English as the base language for keywords and identifiers.

---

[< Previous chapter](https://dev.to/williamragstad/write-a-language-in-a-week-introduction-2el6) | **Chapter 1** | _Next chapter coming soon!_
Laravel 8 Eloquent updateOrCreate() Example
Tags: laravel, php, javascript, tutorial
Published: 2022-04-06 08:26:17

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-updateorcreate-example

In this post, I will explain what is the usage of **Laravel Eloquent updateOrCreate()** and its importance. Laravel provides **updateOrCreate()** to help us to update the record if existing and create if doesn't. This method helps us not to manually check if the record is existing then update if not then create. See below for my example below without Laravel **updateOrCreate()** and with Laravel **updateOrCreate()**.



## Example without Laravel updateOrCreate()


```php
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $title = 'Post 38';
        $description = 'Description for post 38 - updated.';
        $body = 'Body for post 38.';

        $post = Post::where('title', $title)->first();

        if(is_null($post)) {
            $post = new Post([
                'title' => $title,
                'description' => $description,
                'body' => $body
            ]);
            $post->save();
        } else {
            $post->description = $description;
            $post->body = $body;
            $post->update();
        }

        print_r($post);die;
    }
}
```

## Example with Laravel updateOrCreate()


```php
<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class PostsController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $post = Post::updateOrCreate([
            'title' => 'Post 3'
        ], [
            'description' => 'Description for post 3.',
            'body' => 'body for post 3 - updated.'
        ]);

        print_r($post);die;
    }
}
```

As you can see from the above code we have the same functionality for an update or create but with the implementation of the Laravel **updateOrCreate()** method, we shorten our code.

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/laravel/laravel-8-eloquent-updateorcreate-example if you want to download this code.

Happy coding :)
Two ways to customize material UI components...
Tags: javascript, react, design, materialu
Published: 2022-04-06 08:23:31

## Introduction
Material-Ui is a goggle's library for designing frontend of websites and webapps. Although I recommend using vanilla CSS. But for folks who are new to Material-UI customization can be a tricky part. 

You can Customize material-ui in two ways.
- Global classes
- Custom classes

## Global classes
The classes which are used globally through out the project are called global classes like primary, secondary, transitions etc.
You can find the material-ui  global classes as an object in **Default theme**.

## How to customize global classes
You can customize global classes by creating a custom object and wrapping it in `<ThemeProvider theme={variable}></ThemeProvider>`component. Please note that the object name should be same as Mui default theme object.

Example

```
const theme = createMuiTheme({
palette: {
primary: pink,
secondary: green
},

shape: {
borderRadius: 8,
},

});

export default function App()
{
<ThemeProvider theme={theme}>
<component1/>
<component2/>
.
.
.
<componentN/>
</ThemeProvider>
```

The above user defined theme object will override the material-ui theme.

## Custom styling of the components 
We can make custom objects for styling whatever we want without using predefined objects of material UI. We can use makeStyles hook for that.

Basically by providing values to the theme prop in makeStyles hook we style the components.

You can use your own names etc for styling. Then Everything wrapped up nicely in ThemeProvider component.

## Example

```
const useStyle = makeStyles(theme =>({
root :{
height: --;
width: --;
background: ==
},

slider: {
...},

header: {
...}

//The above is custom template

export default function App()
{
const classes = useStyle(); //put function in classes variable to access the objects.

return(
<ThemeProvider theme={theme}>
<div className={classes.root}>
<div className={classes.header}/>
<div className={classes.slider}/>
</div>
)}
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/wk2j9zo0l5gzb2l1t2is.jpg)
Elixir Today: Remove duplicate rows in PostgreSQL using Ecto
Tags: elixir, ecto, postgres, phoenix
Published: 2022-04-06 08:18:57

## Intro
In this tutorial, I want to share with you how to remove duplicate rows in your schema using Ecto.

## Preparation

- In your schema migration, let say you have this schema setup.

```
CREATE TABLE(:student_teacher, primary_key: false) do

     add :id, :uuid, primary_key: true
     add :student_id, references(:students, type: :uuid)
     add :teacher_id, references(:teachers, type: :uuid)

end
```

- And then let's insert a couple of duplicate record. (Supposed you are using [Ex.Machina](https://hexdocs.pm/ex_machina/ExMachina.html) for your data mock ups )

```
student = insert(:student)
teacher = insert(:teacher)
insert_list(100, :student_teacher, student: student, teacher: teacher)
```

## Check for Duplicate Rows using IEx

Run `iex -S mix` in your console and check for duplicate rows.

```
iex) query = SELECT COUNT(*), student_id, teacher_id FROM 
student_teacher group by student_id, teacher_id having count(*) > 1;

iex) Ecto.Adapter.SQL.query!(Repo, query)

iex) %Postgrex.Result{
  columns: ["count", "student_id", "teacher_id"],
  command: :select
  num_rows: 1,
  rows: [
    [
      100,
      <<student_id>>,
      <<teacher_id>>
    ],
    
  ]
}

```

## Run Query to delete Duplicate Rows

```
Repo.transaction(
      fn ->
        query = """
        DELETE FROM student_teacher s1
        USING student_teacher s2
        where s1.id < s2.id
        AND s1.student_id = s2.student_id
        AND s1.teacher_id = s2.teacher_id
        """

        Ecto.Adapters.SQL.query!(Repo, query)
      end,
      timeout: :infinity
    )

```

> Happy Coding!
Contact Center Solution Management Platform | Blackchair
Tags: telecom
Published: 2022-04-06 08:04:22

Are you looking to reduce operating costs and improve productivity in your contact center solution? Your **[CX platform](https://theblackchair.com/)** is the core of your service - it determines how productive your agents are, the quality of customer service, and your customer service satisfaction rates. You need to make sure that your CX solution is as efficient and optimized for quick business delivery.


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ikoliunmqivrvz07pi4g.jpg)
Blackchair is an automated solution designed to eliminate the barriers that make contact center solution management inefficient. For over a decade, we have been working closely with many of our customers to help their contact centers enhance infrastructure management so that they can optimize operations, improve business delivery, and stay one step ahead of competitors.
Today's Fun Joke For Developers - Daily Developer Jokes
Tags: jokes, dailydeveloperjokes
Published: 2022-04-06 08:00:12

---
title: "Today's Fun Joke For Developers - Daily Developer Jokes"
description: "Check out today's daily developer joke! (a project by Fred Adams at xtrp.io)"
series: "Daily Developer Jokes"
published: true
tags: #jokes, #dailydeveloperjokes
---

Hi there! Here's today's Daily Developer Joke. We hope you enjoy it; it's a good one.

![Joke Image](https://private.xtrp.io/projects/DailyDeveloperJokes/public_image_server/images/5e125947cfb29.png)

---

For more jokes, and to submit your own joke to get featured, check out the [Daily Developer Jokes Website](https://dailydeveloperjokes.github.io/). We're also open sourced, so feel free to view [our GitHub Profile](https://github.com/dailydeveloperjokes).

### Leave this post a ❤️ if you liked today's joke, and stay tuned for tomorrow's joke too!

_This joke comes from [Dad-Jokes GitHub Repo by Wes Bos](https://github.com/wesbos/dad-jokes) (thank you!), whose owner has given me permission to use this joke with credit._

<!--
Joke text:
___Q:___ An Agent died unexpectedly. How was the crime solved?

___A:___ By looking at the Stack Trace.
 -->
Django Tip: Use DecimalField for money
Tags: django, decimal, float
Published: 2022-04-06 07:28:02

When working with money values in Django, the first thought is to use `FloatField` to represent currency in the model. However, `FloatField` uses the `float` type internally which comes with some precision issues. 

## The problem

Take a look at this piece of code. It's just a simple operation with float numbers in Python.

```python
>>> .1 + .1 + .1 == .3
False
>>> .1 + .1 + .1
0.30000000000000004
```
Normally, you think that the addition will make sense but because of some issues with the float approximation, the equation is not equal to 3.
You can fix these issues using rounding but if you are dealing with money values and precision matters, it might be time to use decimals.

## The solution

Basically, use decimals instead of floats when precision matters. Let's rewrite the previous example but with `Decimal`.
```python
>>> from decimal import Decimal
>>> Decimal('.1') + Decimal('.1') + Decimal('.1') == Decimal('.3')
True
>>> Decimal('.1') + Decimal('.1') + Decimal('.1')
Decimal('0.3')
```
Notice that here we are initializing the decimals values with string values. You can use floats but as we said earlier, floats have their approximation issues. 

Then when working with Decimal in Django with the `DecimalField`, it's always a good habit to precise the decimal_places attribute when defining the field.
```python

class Product(models.Model):
    title = models.CharField(max_length=64)
    description = models.TextField()

    price = models.DecimalField(max_digits=6, decimal_places=2)
```

You can learn more about `DecimalField` [here](https://docs.djangoproject.com/fr/4.0/ref/models/fields/#decimalfield).

*Article posted using [bloggu.io](https://bloggu.io). Try it for free.*
Random Forest Algorithm
Tags: algorithms
Published: 2022-04-06 07:26:15

Random forest  is a supervised machine learning algorithm. It's one of the most admire algorithms due to its  features like delicacy, simplicity, and flexibility.  The [algorithm](https://insideaiml.com/blog/Random-Forest-Algorithm-1029) generates the individual decision trees through an characteristic selection suggestion. Every tree relies on an independent aimless sample. In a classification problem, every tree votes and the most popularized class is the effect.
Troubleshooting and FAQs for SUM Connectivity Security Proxies and other related settings
Tags: webmethods, sum, updatemanager, integration
Published: 2022-04-06 12:46:00

---
title: Troubleshooting and FAQs for SUM Connectivity Security Proxies and other related settings
published: true
date: 2022-04-06 07:08:26 UTC
tags: webMethods, SUM, UpdateManager, Integration
canonical_url: https://tech.forums.softwareag.com/t/troubleshooting-and-faqs-for-sum-connectivity-security-proxies-and-other-related-settings/256049
---

This technical article is targeting anybody who has a intermediate technical knowledge about SAG Update Manager (SUM) and some base knowledge about Java certificates and truststores.

Check out the [full topic](https://tech.forums.softwareag.com/t/troubleshooting-and-faqs-for-sum-connectivity-security-proxies-and-other-related-settings/256049) in the Software AG Tech Community, which covers a collection of the frequently asked questions about Software AG Update Manager (SUM) related to network, connectivity, proxies and other configurations and troubleshooting.
How To Apply For The Right Instagram Account Recovery Operation For Account Recovery?
Published: 2022-04-06 06:57:25

For the instant account recovery solution to your Instagram account, you will need to executive [Instagram Account Recovery](https://www.myaccountrecovery.com/instagram-account-recovery/) as carefully as possible to gain access to your Instagram account. In case of any hassle regarding the same, you have to get rid of all such happenings from the experts.
Istio service discovery in Kubernetes clusters
Tags: kubernetes, microservices, opensource, programming
Published: 2022-04-06 06:55:56

When we deploy multiple microservices in a kubernetes  cluster, they  need to communicate with each other with a unique host name. This feature of service discovery is taken care by Service mesh Istio. Read my below post to understand how istio does service discovery
 https://link.medium.com/fzH7Vnm2Zob
Transfer Money from Apple Pay to Cash App quickly:
Published: 2022-04-06 06:41:12

There has been a need to [Transfer Money from Apple Pay to Cash App](https://www.gonetech.net/transfer-money-from-apple-pay-to-cash-app/) on several occasions. However, the majority of people are unfamiliar with the strategies that should be used. As a result, everyone must seek the assistance of the support team for the solution aspects. They also assist their customers in transferring money without difficulty to maintain the business running at all times.
How to Verify Identity on Cash App
Published: 2022-04-06 06:39:46

[How to Verify Identity on Cash App](https://www.supporttechhelp.com/blog/how-to-verify-my-identity-on-cash-app/)? Try contacting the technical representatives to get reliable solutions. You’ll get the quick assistance of the cash app team. So, ask your experts for help on this. Whatever your issue is, you can quickly solve them anytime.
What is Context-API and purpose for using it ?
Tags: javascript, react, contextapi
Published: 2022-04-06 06:39:31

**Context API is a react structure which allows passing data from one component to another component without props drilling.** 


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0fi7le28lp8at5b3qw6u.png)
**The purpose of using context API avoids props drilling in react application.** 

Now I am explaining: First of all we have to know about components. Conceptually components are JavaScript functions. Using props data can transfer from one component to another component. When our react application becomes too large that time it becomes difficult to manage the application. To make the application easier to manage , we break it down into smaller sections called components. It has one of the biggest features called reusability. 

Now let’s discuss props drilling. We know that the React data flow system is unidirectional. When we need to pass data from one component to another component of a tree we need to use the prop drilling process. In this process, props are passed from one component to another component that does not need the data but only helps in passing it through the tree. It’s called prop drilling. 

Because of props, drilling components are re-rendered excessively, which slows down the application performance. And component re-rendering is especially damaging when developers need components to communicate with each other in a process known as prop drilling. But the context-API provides a scope that we do not need to props drilling when data passes one component to another component . We can pass the data directly Initial destination to final destination without multiple component re-rendering which component data passing should not necessary. That is why we should
avoid prop drilling, And the context API will help us to get rid of this problem. Now it is clear that to avoid the props drilling, the context-API is used in react application.
SEO Strategy vs. Tactics
Tags: seo, marketing, seotips
Published: 2022-04-06 06:09:44

Strategy is made up of multiple tactics. – Patrick Willoughby
The strategy is the planning … and the tactics are the concrete actions you take to carry out the strategy. – Claudia Miller
Strategy is the plan, and tactics are the actionable items to carry out that plan. – Megan Mars
Strategy without tactics is the slowest route to victory. Tactics without strategy is the noise before defeat
[Source](https://www.searchenginejournal.com/seo-guide/strategy-vs-tactics/#close)
How to Enable Debug mode in WordPress
Published: 2022-04-06 06:23:49

To enable debugging on your WordPress site, please follow the steps below.

1) Locating the **wp-config.php** file

2) **Editing the wp-config.php file**
Once your site files are open, you’ll need to open wp-config.php for editing. This will be located in the root folder of your site.

The wp-config file contains site-specific configuration settings, such as database information and, potentially, settings added by your hosting provider. For debugging, you’ll need to find this line of code (will generally be near bottom of file):

**define( 'WP_DEBUG', true );**

3) Adding your debug code
**Copy and paste this code snippet over the line of code mentioned in Step 2**.

`// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );
 
// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );
 
// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );
 
// Use dev versions of core JS and CSS files (only needed if you are modifying these core files)
define( 'SCRIPT_DEBUG', true );`

OR Follow Like Bellow Screen Shot:
![Enabling debug in WordPress](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6vfrs5165s9d32m7qocc.png)
.
Thank you
Happy Coding
.
osman forhad
Full-Stack Developer💻 (Mobile App & Web App)
developer.osmanforhad@gmail.com
Styling use styled-Component in React-Js
Published: 2022-04-06 06:19:58


Hii dude..
i've learnd styling use styled component and now i want to share to you, i hope this knowledge can be useful for us.

 

1.First step, we must install library of styled component...
Enter the folder of your project and open _CMD_ (Command Prompt) and write **npm install styled-components** or **yarn add styled-components** in your CMD such as picture bellow :


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ufvcrcaavjrykfuee7ag.png)
and press Enter in the keywbord.. 

2.Second step, we must import styled's library 
such as picture bellow :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w0nl184g5wwbrjy6u1iy.png)

3.Last step, we can use that library..
Make variable and declaration of variable must be styled and (kind of element) for example like picture bellow :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/z6d22dqtit655vwubp1c.png)

and using quotation mark for styling .. like this 
 
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/bmo4rv4qtgbnlwgpojkn.png)

Now, we can use that variable in our class or function..
like this picture :

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2c5lr61b9w5mog5bpymt.png)

And let's check the result..
_Code Picture :_

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/sqtdpfiq2kg4ibvjpyvp.png)

_Result Picture :_ 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3qsxmfuxghe3kledg0on.png)

## Why Styled Components?

The main purpose of using styled components is because it is modular and practical. If you use 1 css bundle, there will be many styles that are not used but are called by the browser, this is solved with styled components, the browser only calls styles that are only used by the component that has been rendered.

Another benefit is that it makes it easier for developers to map styled and component, no need to remember a lot of css selectors, because here components and styles are made at the same level, if you want to know the style of a component button, then just check the coding in the component button.

See you..