teleren/devto huggingface dataset:
Laravel 8 Eloquent firstOrCreate() Example
Tags: laravel, php, javascript
Published: 2022-03-29 07:56:09

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

In this post, I will explain what is the usage of **Laravel Eloquent firstOrCreate()** and its importance. Laravel provides **firstOrCreate()** to help us to attempt to find a record in our database if not found then create a new record and return it.

 

## Example without Laravel firstOrCreate()

```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 3';
        $post = Post::where('title', $title)->first();
  
        if (is_null($post)) {
            $post = new Post(['title' => $title]);
        }
  
        $post->description = 'Description for post 3.';
        $post->body = 'Body for post 3.';
  
        $post->save();
  
        print_r($post); die;
    }
}
 

Example with Laravel firstOrCreate()
<?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::firstOrCreate(
            ['title' => 'Post 5'],
            ['description' => 'Description for post 5.', 'body' => 'Body for post 5.']
        );
  
        print_r($post); die;
    }
}
```

As you can see of the above codes have the same functionality but using the **firstOrCreate()** method in Laravel will shorten our code.


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

Happy coding :)
Laravel 8 Eloquent pluck() Example
Tags: javascript, laravel, php
Published: 2022-03-29 07:51:58

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

**Laravel 8 Eloquent pluck()** method helps us to extract certain values into 1 dimension array. It shortens our code if we want only to get the specific field values into 1 dimension array so that we don't need to loop the result collection to get certain values using this method. In this post, we are using a **posts** table with **title, description,** and **body** fields.

 

In this example, we want to display the title only into 1 dimension array. Or should be like this:

```php
Array
(
    [0] => Post 3
    [1] => Post 1
    [2] => Post 2
    [3] => Post 3
    [4] => Post 4
)
```

But to do that in we need to use **all()** method in eloquent as you can see in the following below:

```php
$posts = Post::all();

$postsTitles = [];
foreach($posts as $post) {
    $postsTitles[] = $post->title;
}

print_r($postsTitles);die;
```
As you can see above we loop the post result then we store the post title to our array variable which is not good because our code is long.

 

And the result is the same:

```php
Array
(
    [0] => Post 3
    [1] => Post 1
    [2] => Post 2
    [3] => Post 3
    [4] => Post 4
)
```


But using the **pluck()** method in Laravel our code will be short. See the below example:

```php
$posts = Post::all()->pluck('title')->toArray();

print_r($posts);die;

```

And the result is the same above:

```php
Array
(
    [0] => Post 3
    [1] => Post 1
    [2] => Post 2
    [3] => Post 3
    [4] => Post 4
)
```

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

Happy coding :)
Type Field Authorization in GraphQL Rails with Pundit
Tags: rails, graphql
Published: 2022-03-29 07:46:54

[GraphQL-rails ](https://graphql-ruby.org/getting_started "GraphQL rails") has _PRO_ feature of [pundit integration](https://graphql-ruby.org/authorization/pundit_integration "pundit integration with GraphQL PRO") which has easy methodology but its a _PRO_ feature and paid.

Still they provide `authorized?` methods in open-source version but we have to do it manually. You can learn more about field authorization [here](https://graphql-ruby.org/authorization/authorization#field-authorization "field authorization in graphql rails").

**[Pundit](https://rubygems.org/gems/pundit/versions/1.1.0 "pundit run gem")** is a great object oriented authorization for Rails applications. It helps to separate the authorization logic from controllers so that authorization logic can be changed with time according to the current requirements of the system. 

## Field Authorization

In GraphQL rails, we want some fields to only be shown to some specific users rather than all users. Here we will first authorize the field of type if success then will show the value of the field according to type, otherwise `nil`.

I assume that pundit gem is installed and initialized in your code along with definitely GraphQL.

Let’s take an example that a user has a post, and only the owner of the post can see the number of views on the post. But as we have one post type in graphql so people other than owner have access to that field. So we will be authorizing the field for the owner of the post only.

```ruby
# app/policies/post_policy.rb
class PostPolicy < ApplicationPolicy

  # only if user is the owner of the post
  def owner?
    user.present? && record.user == user
  end

  class Scope < Scope
    def resolve
      scope.all
    end
  end
end
```

Now that we defined the post policy with owner role, we define the post type with number of view field authorization.

```ruby
# app/graphql/types/post_type.rb
module Types
  class PostType < Types::BaseObject
    field :id, ID, null: false
    # .... remaining fields
	field :number_of_views, Integer, null: true, description: 'number of times user has viewed your post' do
      def authorized?(object, args, context)
        Pundit.policy(context[:current_user], object)&.owner?
      end
    end

    # resolvers
    def number_of_views
	  object.views.count
    end
  end
end
```

`authorized?` returns true or false. So if authorization fails then `nil` is shown, otherwise value is shown. So now in future if `owner?` definition needs to be changed then it can be done easily. Also we can create the same method name of `number_of_views` in pundit policy to restriction flow completely in pundit policy.

---- 
Happy Coding!
Updated blog structure testing 2
Tags: uat
Published: 2022-03-29 07:40:13

# Steps to integrate Razorpay 

Update feature testing after updating blog structure.

* Change database structure on devto

* Storing API keys in settings.py

* Installing Razorpay library.

* Creating order using Razorpay API.

* Creating order at backend and also creating Razorpay order.

	* Show template

	* render to payment.html

	* Get info of call back URL

	* Done with creating an order.

### **Uploading a File**

There are three ways you can upload a file:

- From an `Object` instance

- From a `Bucket` instance

- From the `client`

In each case, you have to provide the `Filename`, which is the path of the file you want to upload. You’ll now explore the three alternatives. Feel free to pick whichever you like most to upload the `first_file_name` to S3.

{% gist https://gist.github.com/Nishant127/13898538d35a024b4d93a592b1b4a6ea %}

![](https://notionpack-uploads.s3.amazonaws.com/blog_images/tmp/tmpiz_1h7pw.png)

![](https://notionpack-uploads.s3.amazonaws.com/blog_images/tmp/tmpse6cef_y.png)

💡 Testing call out block
Function Currying in JavaScript
Tags: javascript, webdev, frontend, interview
Published: 2022-03-29 07:30:43

With the rapid rise of functional programming in JavaScript, a lot of attention has been given to the curried function. So in this post, let's discuss this.

⬇️ What is Function Currying ❓

Currying is a transformation that can be applied to functions to allow them to take one less argument than previously.

Okay okay, let's simplify this
 
Currying is when a function, rather than taking all arguments at once, takes the first one and returns a new function, which then takes the second one and returns a new function, and so on until all arguments are completed.

⬇️ Uses and Need of Function Currying ❓


➡️ It helps us to avoid passing the same variable again and again.
 
➡️ It separates our function into several smaller functions, each of which can handle a single duty. This ensures that our function is error-free and free of side effects.
 
➡️ It is used in functional programming to create a higher-order function.

➡️ It is extremely useful in event handling.


⬇️ How can we do Function Currying ❓


There are multiple ways by which we can do function currying, in this post we will discuss one of that methods.

⭐ Function Currying using Closures

function add (a) {
return function (b) {
console.log ( a + b );
};
}
add(2)(5);

Confused 😕❓, Let's discuss

Here, the result of add(a) is the wrapper function(b).
 
When it's called add(2), the argument is saved in the Lexical Environment, and a new wrapper is returned function(b).
 
Then this wrapper is called with ‘5’ as an argument, this wrapper will already have access to ‘a’ due to closure, which is currently equal to ‘2’, so we will get ‘7’ printed on the console.


Currying is a difficult concept to grasp. But, with time and practice, we can certainly get the hang of it.
Blazor Project Structure and Layout
Tags: blazor, aspnetcore, beginners, codenewbie
Published: 2022-03-29 07:06:16

---
title: Blazor Project Structure and Layout
published: true
description: 
tags: blazor, aspnetcore, beginners, codenewbie
//cover_image: https://direct_url_to_image.jpg
---
In this blog post we will discuss about different files and folder type in Blazor Server and Blazor WebAssembly app. We will not dive into deep details but a simple explanation so one get started in Blazor web development.

![Project Structure](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/q04n693rr9bpnbqi88ds.png)

As you can see from the above image both Blazor Server and WebAssembly project some has common file and folder structure. Now we will look into details regarding this.

####Program.cs
This file contains the *Main()* method which is the entry point for both of the project.

####Startup.cs
This file is only present in Blazor Server project. From the file name you can guess that it only contains the application's startup logic.

####App.razor
This file contains the routing mechanism which uses the built-in routing component and sets up the client side routing. Router uses following two property to display content:
* Found: When a match is found this property display the content.
* Not Found: If a match is not found it display the  message - Sorry, there's nothing at this address.

![App Razor](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/lsf9b28ovyror1gmvo7z.png)

####*Pages* folder:
This folder contains the all the web page that you see in the Blazor web application. This web pages are knows as Razor component and have .razor extension at end of each file name.

####*Shared* folder
This contains the that will be used across the project like layout, menu etc. By default you will see this folder contains MainLayout.razor, NavMenu.razor, SurveyPrompt.razor where the content in these file are utilizes in the razor components or razor files that is Pages folder.

####wwwroot
This folder contains the static files like images, stylesheets, javascript etc. 

####appsettings.json
This only contains in blazor server project and contains configuration settings. In this file, we mostly store global values so that we can read those in the entire application.


Remember everything in a Blazor application is a razor component. Components are the fundamental building blocks of a Blazor application.
Essence Of Argan : 100% Pure Organic Hair Repair
Tags: health
Published: 2022-03-29 07:00:15


I expect that you are not just going to spend a bunch of dollars on a [Essence Of Argan](https://ipsnews.net/business/2022/03/13/essence-of-argan-australia-moroccan-argan-oil-100-natural-and-effective-ingredients-pros-cons-and-how-to-use/) for nothing. It gets my goat. I believe that you are looking for this sample because it depends on where you go to. An abundance of adolescents actually think that your choice is part of the UFO conspiracy. Don't be concerned, I'm an experienced pro. I believe this is the most obvious element in the world. I need to be proactive. That provides a good way to work with doing that. Maybe you should to reassure your women. Please, risk is part of a truism. What works on this day may not work then. 

Here's how to end being anxious and live your life. Despite everything, is this only a context of a Essence Of Argan with a lousy Essence Of Argan Skin Care? I located a club of independent Essence Of Argan Skin Care professionals. I have enormous ability. That should make you feel successful. I lately found an old friend on Facebook who knows that schtick well. Nonetheless, it is the intent of this column to give you a couple of tips on this. It is hard to hold on to that scenario although I was able to get VIP access to this festival. 

I understand that difference gets recognized. It is vital survival. Let's give that the old college try. I keep banging on referring to using it. I always try to find cheap shipping. We'll cut costs. Your individual talents, or lack of talents, will determine what you can do with Essence Of Argan. Doing it helps me to unwind. I now wish I were the one who'd brought it. Strictly, my viewpoint is this: You need to experience this deduction for yourself. Some of my friends were excited with reference to Essence Of Argan. 


[https://ipsnews.net/business/2022/03/13/essence-of-argan-australia-moroccan-argan-oil-100-natural-and-effective-ingredients-pros-cons-and-how-to-use/](https://ipsnews.net/business/2022/03/13/essence-of-argan-australia-moroccan-argan-oil-100-natural-and-effective-ingredients-pros-cons-and-how-to-use/)
Leetcode Daily Challenge - Find the Duplicate Number
Tags: python, programming, leetcode, beginners
Published: 2022-03-29 06:54:38

Today's challenge on Leetcode in based on a problem oftenly asked in the interviews. It is a medium level problem and I came up with a couple of solutions for the problem using Sorting approach and Two Pointer Approach.

[Find the Duplicate Number](https://leetcode.com/problems/find-the-duplicate-number/)


##Intuition
The intuition is pretty straightforward as compared to the actual implementation. However, the time space trade off is the actual crunch in this problem as there can be various ways to solve the the best one is the foremost demand always.

##Logic: (Approach a)
This approach is the easiest of all as it takes the list and sorts it to check if we can find the element in O(nlogn), for the obvious sorting reasons.

Algorithm:

```
1. Sort the input list
2. Traverse through list
     if nums[i] == nums[i+1]
       return nums[i]
3. Return -1    
```

## Logic (Approach b)
The approach can be applied with the use of Floyd Circle algorithm which can be bifurcated into two parts. First where it is checked if there exists a cycle in the list.


Further, it is made sure with the use of indexing for the element that is repeated. 

![Floyd Cycle](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/opyfhk0es0giiv1b2bc9.jpg)
 
##Code No. 1

```
class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        nums.sort()
        for i in range(1, len(nums)):
            if nums[i] == nums[i-1]:
                return nums[i]
```

## Code No. 2
```
class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        turtle = 0
        hare = 0
        while True:
            if turtle >= len(nums):
                turtle = 0
            if hare >= len(nums):
                hare = 0
            if nums[turtle] == nums[hare] and turtle != hare:
                return nums[turtle]
            turtle += 1
            hare += 1
        return None
            
```
Which one has a better future? blockchain or full stack developer.
Tags: discuss, webdev, web3, blockchain
Published: 2022-03-29 06:34:46

Hi, as a beginner of the community I see a lot of people talking that web3.0 is the future of the developing. 

## How do you predict the future?
as a front-end developer and someone new to the community I like to stay updated and choose the path that has future ahead (either financially or regarding job opportunities), so here is my question **should I switch to blockchain developing?** like solidity or should I just don't rush to it and continue the web developing path ( web2.0 i think:) ).

Again thank you for your kind replies and helps.
How to Remove Last Element from Array in Javascript?
Tags: javascript, how, array, php
Published: 2022-03-29 06:33:18

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/javascript/how-to-remove-last-element-from-array-in-javascript

In this post, I'm sharing a short post on how to remove the last element value from an array in Javascript. If you need to remove the last value of the array before processing the data then **array.pop()** done this.

 

Here is the example solution below:

```php
<script>
var websites = ['google.com', 'facebook.com', 'youtube.com'];

websites.pop();

console.log(websites);

// result: ["google.com", "facebook.com"]
</script>
```

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/javascript/how-to-remove-last-element-from-array-in-javascript if you want to download this code.

Happy coding :)
How to Remove First Element from Array in Javascript
Tags: javascript, how, array, php
Published: 2022-03-29 06:31:27

Originally posted @ https://codeanddeploy.com visit and download the sample code: https://codeanddeploy.com/blog/javascript/how-to-remove-first-element-from-array-in-javascript


In this post, I'm sharing a short post on how to remove the first element value from an array in Javascript. If you need to remove the first value of the array before processing the data then **array.shift()** done this.

 

Here is the example solution below:

```php
<script>
var websites = ['google.com', 'facebook.com', 'youtube.com'];

websites.shift();

console.log(websites);

// result: ["facebook.com", "youtube.com"]
</script>
```

I hope this tutorial can help you. Kindly visit here https://codeanddeploy.com/blog/javascript/how-to-remove-first-element-from-array-in-javascript if you want to download this code.

Happy coding :)
Logistic Regression and Classification
Tags: machinelearning, datascience, classification
Published: 2022-03-29 06:10:37

💎 Concept of Logistic Regression
💎 Applications of Classification
💎 Concepts of True Positive, True Negative, False Positive , False Negative 
💎 Concepts of Sensitivity and Specificity
💎 Concepts of Precision and Recall and when to apply what
💎 Concepts of F [ Beta ] Score and F1 Score

{% embed https://youtu.be/s3SYWRD3i0g %}
Custom shell function in .zshrc to search strings
Tags: zsh, shell, bash
Published: 2022-03-29 05:53:48

```
seek() {
  if [ "$1" != "" ]
  then
    grep -H -r --exclude-dir=node_modules "$1" * | less
  else
    echo "need to type in a string"
  fi
}
```

I use this function when I join an existing project and I need to get familiar with the code base. I got tired of typing in `grep -H -r 'string' * | less` so I created this little function to make the process quicker.

Now we just type in `seek custom_method` and a list of files will appear from the project that contain that method or whatever string you passed. I added a flag to exclude `node_modules` because usually that's not where you need to look and it could pull up irrelevant files.

This is helpful when searching file names is not enough. I'm pretty excited about this one. I hope it helps you out!
Why IdP (Identity Provider) only is not good enough
Published: 2022-03-29 05:19:15

Even if you are employing an identity provider (SaaS-based auth service or open source), you still need to do a lot of work to implement user authentication using SDKs and APIs from identity providers:

1) learn complex OIDC/OAuth protocols
2) write integrating code using SDKs/APIs from identity provider
3) write code to manage refresh token, id token & access token
4) write code to get user info/attributes, like group or role
5) write code to manage user sessions


BTW: I am not saying Identity Providers are not good. They are very useful, like Okta/Auth0, Azure AD, Amazon Cognito, & Keycloak. I just tried to point out the extra work you need if you integrate with them via SDKs/APIs.
Create your own portfolio website (My website Demo) 🌿🌿
Tags: javascript, react, portfolio, programming
Published: 2022-03-29 05:19:03

Hi everyone, today I want to share my portfolio website and some ideas to create your own. [Official Website] (https://tejendrasrajawat.github.io/)

## Explaination
As you can see in above website, I used dark and light mode, some buttons to social media accounts, one page for my GitHub projects and one for all blogs I wrote yet. also there is a page to contact me. all the backend functionality are handled by firebase and there is nothing static.

So let's see what are we covering today - 
1. Basics of Html and CSS
2. JavaScript and React.js
3. Styles Component
4. use Context and Redux

**1. Basics of html and CSS** - 
If you want to create any website so first of all you need to have knowledge of html and CSS. Html is used as a skeleton of website and CSS is the design part. They are not difficult to learn but can be complicated to understand.

_Best way to learn basics of html and css are from [w3schools](https://www.w3schools.com/css/css_intro.asp)_

**2. React.js** -
Next part is React.js which is a framework of JavaScript, but why use React.js. well the answer is easy if your website have complex logics which can only be handled by JavaScript then react.js will make your task easy. 
To learn react.js , you want to learn JavaScript first. There are some references to learn it.

**Firebase (optional)**-
_In my portfolio, I used react to connect firebase firstore and get database from firebase._

**JavaScript -**
1. [w3school](https://www.w3schools.com/js/)
2. [code with mosh](https://youtu.be/W6NZfCO5SIk)

**React.js -**
1. [react docs](https://reactjs.org/tutorial/tutorial.html)
2. [code with mosh](https://www.youtube.com/watch?v=Ke90Tje7VS0)

**3. Styled Component** - 
If you familiar to CSS then you know that there are some limitation there like you can't use conditions directly there but in Styled component which is a module , you can use inline css and can use conditions in css. It's optional but still i want you to have a look. [styled docs](https://styled-components.com/)

**4. use Context and Redux** - 
At last but my favorite part is Redux , without going in details if you want to use same value in different component(files) then you can use Redux or use Context in Reactjs. Both will do the job but if your project is large then go for Redux or go for use Context.
_I used it to give dark and light mode functionality in my website_
Ref - [Redux](https://redux.js.org/)

## Conclusion
Well, That's all I used in my website yet and yet trying to improve it furthermore. So I need your valuable feedback.
How to resolve npmInstall error
Tags: react
Published: 2022-03-29 05:11:48

Hi Team,
I tried multiple times on this error, finally I am getting same error in below,

> Task :modules:react-corp:npmInstall FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':modules:react-conneqtcorp:npmInstall'.
> Process 'command 'cmd'' finished with non-zero exit value 1

Please help me anyone here.

Thanks.