Get Multiple Checkbox Value in React JS

In this article, we will see how to get multiple checkbox values in react js. In react, js click on the submit button and get the multiple checkbox values. Retrieve all checkbox values in react js. Sometimes, you work with forms with checkboxes fields in react js app. And at that time, you want to get all checked checkbox values on submitting in react js app.

So, let's see how to get checkbox values in react js or react js to get multiple checkbox values.

Step 1: Create React JS App

In this step, we will create a new react app.

npx create-react-app my-react-app

To run the React app, execute the following command on your terminal.

npm start

Step 2: Setup Bootstrap 4

In this step, we will install the bootstrap 4 libraries into your react app.

npm install bootstrap --save

Add the bootstrap.min.css file to src/App.js the file.

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
 
function App() {
  return (
    <div>
      <!-- Code here -->
    </div>
  );
}
 
export default App;

Step 3: Create Checkbox Form Component

In this step, we will create a checkbox form component named CheckboxForm.js.

import React from 'react'
class CheckboxForm extends React.Component{

constructor(){
	super();
	this.state = {
		hobbies:[]
	}
	this.handleInputChange = this.handleInputChange.bind(this);
}

handleInputChange(event) {
	const target = event.target;
	var value = target.value;
	if(target.checked){
		this.state.hobbies[value] = value;   
	}else{
		this.state.hobbies.splice(value, 1);
	}
}

submit(){
	console.warn(this.state)
}

render(){
	return(
	<div>
		<div class="row">
			<div class="col-md-6 offset-md-3">
				<br /><br />
				<h3>How To Get Multiple Checkbox Value In React JS - Websolutionstuff</h3><br />
				<div class="form-row">
					<div class="form-group col-md-6">
						<label>Hobbies :</label><br />
						<div class="form-check form-check-inline">
						<input class="form-check-input" type="checkbox" name="hobbies" id="inlineCheckboxh1" value="1" onChange={this.handleInputChange} />
						<label class="form-check-label" for="inlineCheckboxh1">Cricket</label>
					</div>
					<div class="form-check form-check-inline">
						<input class="form-check-input" type="checkbox" name="hobbies" id="inlineCheckboxh2" value="2" onChange={this.handleInputChange} />
						<label class="form-check-label" for="inlineCheckboxh2">Reading</label>
					</div>
					<div class="form-check form-check-inline">
						<input class="form-check-input" type="checkbox" name="hobbies" id="inlineCheckboxh3" value="3" onChange={this.handleInputChange} />
						<label class="form-check-label" for="inlineCheckboxh3">Cooking</label>
					</div>
				</div>
			</div>
			<div class="form-row">
				<div class="col-md-12 text-center">
					<button type="submit" class="btn btn-primary" onClick={()=>this.submit()}>Submit</button>
				</div>
			</div>
		</div>
	</div>
	</div>
	)  
	}
}
export default CheckboxForm;

Step 4: Add Component in App.js

In this step, we need to add the CheckboxForm.js file in src/App.js file:

import React from 'react';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import CheckboxForm from './CheckboxForm'
function App() {  
return (  
<div className="App">  
<CheckboxForm/>  
</div>  
);  
}  
export default App;

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

#react #checkbox #value 

Get Multiple Checkbox Value in React JS

Get Multiple Checkbox Value in Javascript

In this article, we will see how to get multiple checkbox values in javascript. Here, we will learn to get the selected checkbox values using jquery. We will use the :checked selector for checkboxes and radio buttons. It can retrieve the selected value of the checkbox. When clicking on the checkbox we will push the value in the array using the push() function.

So, let's see get selected checkbox values in jquery, multiple checkbox checked values in javascript, get checkbox value in javascript, and get checkbox value in the javascript array.

Example:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Get Multiple Checkbox Value In Javascript - Websolutionstuff</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<style>
  body{
  	margin:100px;
  }
</style>
<body>
  <h3>Get Multiple Checkbox Value In Javascript - Websolutionstuff</h3>
    <form>
        <h3>Select languages:</h3>
        <label><input type="checkbox" value="laravel" name="language"> Laravel </label>
        <label><input type="checkbox" value="php" name="language"> PHP </label>
      <label><input type="checkbox" value="javascript" name="language"> JavaScript </label>
        <label><input type="checkbox" value="jquery" name="language"> jQuery </label>
        <label><input type="checkbox" value="mysql" name="language"> MySQL </label>
        <label><input type="checkbox" value="css" name="language"> CSS </label>
        <label><input type="checkbox" value="python" name="language"> Python </label>
        <br><br>
        <button type="button">Get Selected Values</button><br>
      	<p></p>
    </form>
  <script>
      $(document).ready(function() {
          $("button").click(function(){
              var arr = [];
              $.each($("input[name='language']:checked"), function(){
                  arr.push($(this).val());
              });              
            $("p").text("Your selected languages are: " + arr.join(", "));
          });
      });
  </script>
</body>
</html>

Output:

how_to_get_multiple_checkbox_value_using_javascript

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

#javascript #checkbox #value 

Get Multiple Checkbox Value in Javascript

The Ultimate Guide: Value Stream Management Platform

Introduction to Value Stream Management Platform

Value Stream Management is a good idea for going around the DevOps community. We'll understand what it is all about and how to implement it. We know that in software delivery, we're always trying to get the best innovative ideas from the business delivered to the customer. Value Stream Management believes everything that happens, from ideas to customers, is essential and needs to be managed holistically.

Rather than managing the developers, testers, and business analysts separately, we optimize the flow of information across all these groups.

Let's look at an example:

We have an idea for a particular module and prioritize it before we go to the design /development team for implementation. Because we deliver to the client, there's a testing team, and we run a whole group of tests on them. Once the test team has verified the expected functionality, then we go for a release.

Now we want to start optimizing the above process to save the release times so that we can see the scope of improvement is likely to go every step, and that will mean certain time needs to be dedicated to every step of the way. There's likely to be waiting for time / unused resources that can be taken care off by amplifying their processes. They were able to remove the underlying inefficiencies.

What is Value Stream Management?

Value Stream Management (VSM) is a method used to visualize and optimize the flow of value in an organization. It is a systematic approach to identifying, analyzing, and improving the series of activities a product or service goes through from conception to delivery to the customer.

What is the Role of ValueOps in VSM?

Value Stream Management is a method used to visualize and optimize the flow of value in an organization. It is a systematic approach to identifying, analyzing, and improving the series of activities a product or service goes through from conception to delivery to the customer.

ValueOps puts "value" into it by providing a single, integrated platform that unifies the business and IT.

While with DevOps, teams can speed delivery and reduce risk, and they align with strategic business outcomes. This is where Value Stream Management (VSM) has become a critical requirement for enterprise-wide success.

With an effective VSM, teams can continuously add value to customers and eliminate wasted investment. Companies must stop focusing on optimizing separate tools, teams, and departments and start optimizing the flow of products and services across the entire value stream. For many organizations, this practice poses significant challenges.

ValueOps can provide solutions to address these challenges. With this solution, companies can effectively and efficiently deploy and manage VSM strategies, allowing teams to establish the necessary internal horizontal alignment. ValueOps seamlessly combines clarity planning features with advanced Agile management, all in an integrated, easy-to-use, and flexible platform.

What does a VSM Platform do?

A Value Stream Management Platform is a software tool that helps organizations to implement and manage their VSM process. It typically provides a visual representation of the value stream and enables users to track and analyze the flow of work through the various stages of the value stream. The platform may also provide features for managing and optimizing work flow, such as scheduling, capacity planning, and performance measurement.

VSM platforms can improve the efficiency and effectiveness of an organization's operations by reducing waste, improving flow, and increasing customer satisfaction. They can be applied to various industries, including manufacturing, software development, healthcare, and finance.

Steps for adopting the VSM Platform

To adopt the VSM platform in your organization, you can follow these steps:
 

  1. Identify the process or value stream that you want to analyze and improve. This could be a process within a department, a cross-functional process, or the entire value stream from raw materials to delivering a product or service to the customer.
  2. Identify the team responsible for conducting the VSM analysis and implementing improvements. This team should include representatives from all functions involved in the process and be led by a trained VSM facilitator.
  3. Gather data on the current state of the process. This may include information on process flow, cycle times, defects, and other metrics. You can also gather data on customer requirements and expectations.
  4. Create a current state map of the process. This visual represents the flow of materials and information through the process, including all steps, handoffs, and decision points.
  5. Identify waste and inefficiencies in the process. Look for activities that add no value to the product or service, delays or bottlenecks, and unnecessary steps or handoffs.
    Develop a future state map that shows how the process could be improved. This may include eliminating waste, streamlining steps, reducing handoffs, and improving communication and decision-making.
  6. Implement the improvements identified in the future state map. This may involve changes to the physical layout of the process, how work is organized and performed, or changes to the tools and equipment used.
  7. Monitor the process to ensure that the improvements are effective and identify any additional improvement opportunities.
  8. It's important to note that VSM is an iterative process, and it may take multiple rounds of analysis and improvement to optimize a value stream fully.

Reasons to adopt the VSM Platform

There are several reasons why organizations may want to adopt the VSM platform:

  • Increase efficiency and reduce waste: By identifying and eliminating waste and inefficiencies in a process, organizations can increase the speed and efficiency of the process, resulting in cost savings and improved customer satisfaction.
  • Improve communication and collaboration: VSM helps bring representatives from different organizational functions and levels to work together towards a common goal. This can improve communication and collaboration, leading to better decision-making and problem-solving.
  • Increase agility and responsiveness: By streamlining processes and reducing waste, organizations can become more agile and responsive to changing customer needs and market conditions.
  • Improve quality: Organizations can improve the quality of their products and services by identifying and eliminating defects and other sources of variability in a process.
  • Foster continuous improvement: VSM encourages a culture of continuous improvement by encouraging teams to identify and eliminate waste and inefficiencies on an ongoing basis.

Which industries would benefit from VSM Platform adoption?

VSM can be applied to any industry or organization that has a process that it wants to analyze and improve. It is particularly well-suited to manufacturing and service industries, where there is a need to optimize the flow of materials and information to deliver products or services to customers. Some specific industries that may benefit from adopting the VSM platform include:

  • Manufacturing: VSM can be used to analyze and improve the flow of materials and information through manufacturing processes, resulting in improved efficiency, quality, and responsiveness to changing customer needs.
  • Healthcare: VSM can be used to analyze and improve the flow of patients and information through healthcare systems, resulting in improved patient outcomes and satisfaction.
  • Finance: VSM can be used to analyze and improve the flow of financial transactions and information within financial organizations, resulting in improved efficiency and accuracy.
  • Government: VSM can be used to analyze and improve the flow of information and services within government agencies, resulting in improved efficiency and customer satisfaction.
  • Retail: VSM can be used to analyze and improve the flow of goods and information through retail organizations' supply chain and distribution networks, resulting in improved efficiency and responsiveness to changing customer needs.

What is Value Stream Delivery Platform (VSDP)?

  • Integrate or provide out-of-the-box functionality for DevOps engine functionality (to build, test, analyze, integrate, provision, configure, secure, deploy, observe, recover, etc.) ) and reduce manual tool coordination.
  • Enables business analysts and product owners to identify features with information gained from progress.
  • Navigate and stay secure with audit logs, even with distributed teams, workloads, and infrastructure.
  • Leverage multi-channel alerts on user-defined events to speed up processes and correct errors.
  • Improve time to market and app availability.
  • Collaborate effectively to review code, share, and streamline delivery.
  •  Provides transparency at all stages of CI/CD for better tracking, governance, and compliance.

What are the benefits of adopting Value Stream Delivery Platform (VSDP)?

  • Businesses need a way to scale DevOps to deliver innovation securely and quickly, and VSDP is evolving rapidly to meet the demands of increasingly complex DevOps workflows.
  • The collision between the DIY toolchain and remote working has exposed the problems faced by companies in managing software development. When the job goes silent, visibility of the progress of the work in progress fades.
  • Not integrating all the different development tools and environments reduce the ability to detect security issues before new features are released.
  • Non-integrated tools and non-standard DevOps environments prevent collaboration. Different Agile and DevOps tools limit process improvements.
  • Adopting VSDP eliminates these problems and allows you to scale. Gartner's market report shows that early adopters of VSDP are seeing exponential gains in continuous integration/delivery (CI/CD) and the ability to drive business value.

What are the future trends of VSDP?

The need for lean development and visibility in the software value stream is deeply rooted in digital transformation and the growing pressure to deliver innovation (and value) faster:

  • Mass adoption of cloud computing
  • Container-based architecture
  • Increase use fast development

Companies need scalable solutions to remove waste from their processes to ensure a steady stream of value to customers. To achieve this, organizations need visibility into shipping processes. When they can assess work quality and process quality, they can continuously improve delivery, helping to get higher quality features into the hands of business users faster pressure for DevOps to create business value.

Conclusion

Overall, the VSM platform can help organizations to deliver better products and services to their customers more efficiently and effectively, leading to improved business performance and customer satisfaction.

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

#devops #management #value #stream 

The Ultimate Guide: Value Stream Management Platform

How to Custom form inputs with ControlValueAccessor

tldr;

There are times when the default inputs available to us in the browser don’t meet our needs or need to be included in a reusable Angular component. You may want to create a custom checkbox or radio button, or just want to use a card with a button as a form input. In any of these situations, you can use the Control Value Accessor to allow an Angular component to communicate with your form. In this article, we’ll look at an example of using control value accessor.

Okay, Here’s the Situation

Bonus points if you get the reference for the heading of this section. 😉

I was recently working on a form where the user was going to need to select an option, and only one option, like you would normally use a radio button for. This is what it looked like:

Demo form inputs

The user will choose one of these items, and when they select it the form goes to another step. I needed their selection to be stored as a value in the form as well. I could have used an Output that patched the value of the form, but I wanted it to be more semantic and obvious about what was going on. To get the value to store in the form, I needed a custom form input, where each of the above cards was the input. I could wrap them in an Angular component and loop over a list of options that were available to the user.

This is where I remembered a talk from Jennifer Wadella at ng-conf 2019 that talked about using ControlValueAccessor. There is a lot of content out there, and I encourage you to read more about it (and watch the video from Jennifer’s talk). This example will not go into all the details of what ControlValueAccessor can do, but it will give you an example and get you started.

Solution

The first step in creating our custom input with control value accessor is to implement the ControlValueAccessor interface. This requires us to implement three methods: writeValue, registerOnChange, and registerOnTouched.

export class CustomInputComponent implements ControlValueAccessor {
    @Input() option: any;

  onChanged: Function = () => {};
  onTouched: Function = () => {};

  registerOnChange(fn: Function) {
    this.onChanged = fn;
  }

  registerOnTouched(fn: Function) {
    this.onTouched = fn;
  }

  writeValue(value: any): void {}
}

registerOnChange

This sets the callback function that the forms API will call when the form value changes. You must provide a function that you will call when the user interacts with the input and the value should be changed. In this case, when the user interacts with our component and we want to update the changed value, we will call this.onChanged(value);.

registerOnTouched

This is similar to the registerOnChange method, but runs when the input is touched by the user. To register the touch, we will call this.onTouched();.

onWriteValue

This method is used to write a new value to the element. In my case, I didn’t need to implement this method, but you may need to do something like this in your case:

writeValue(value: any): void {
  this._renderer.setProperty(this._elementRef.nativeElement, 'value', value);
}

This would write the value that is passed in to the method to the native input’s value in the DOM.

setDisabledState

This is an optional method that you can implement, and it allows you to run a block of code when the forms API sets the input to or from disabled.

Setting the Providers for the Component

After implementing the required methods for the ControlValueAccessor interface we need to set some providers for the component. The providers are set in an array in the component metadata:

export const CUSTOM_CONROL_VALUE_ACCESSOR: any = {
    provide: NG_VALUE_ACCESSOR,
    useExisting: forwardRef(() => CustomInputComponent),
    multi: true,
};

@Component({
  selector: 'app-custom-input',
  templateUrl: './custom-input.component.html',
  styleUrls: ['./custom-input.component.css'],
  providers: [CUSTOM_CONROL_VALUE_ACCESSOR]
}) 

Essentially this turns our component into the custom input for the forms API to interact with.

Interacting with the Component

Now that we have our card (as shown above) and the ControlValueAccessor is implemented, we need to make sure that the user can select the input by clicking on the “Choose this Option” button. This part is pretty simple, though. All we need to do is run a function when the click event occurs, something like this:

<!-- custom-input.component.html -->
<button (click)="onChanged(option.id)">Choose this Option</button>

Now when the user clicks on the button, the form’s value will update to the value of option.id.

Setting the formControlName

Now that we have our custom input, we need to implement it in the parent component with the form. This is actually easy as well after doing the other work. If you’ve set up your ControlValueAccessor, all you need to do is add the formControlName attribute to the component in the HTML file.

<!-- app.component.html -->
<form [formGroup]="form">
    <app-custom-input *ngFor="let option of options" [option]="option" formControlName="option" ></app-custom-input>
</form>

As long as your FormGroup has an attribute called option, then clicking on the card will set the option’s ID as the value in the form.

Demo App

You can check out this StackBlitz for a working example of this custom input component using control value accessor.

Conclusion

I have been working with reactive forms for a few years now, and only just implemented ControlValueAccessor for the first time. You may not need to use this technique frequently, but in the case that you do need to implement it, don’t worry about the difficulty. In just a few steps (as outlined above) you can get it working.

I’ve shown the example of using reactive forms, but the steps above should work the same if you’re using template driven forms. Instead of using formControlName on the <app-custom-input> tag, you’ll use [(ngModel)].

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

#angular #input #value 

How to Custom form inputs with ControlValueAccessor
Nat  Grady

Nat Grady

1669374540

Display A Variable Value using JavaScript Alert Dialog

How to display a variable value using JavaScript alert dialog

JavaScript provides you with the alert() method that allows you to create an alert box, where you can display some information together with an OK button to remove the alert.

You can test the alert() method by simply opening your browser’s console and type in alert() as in the screenshot below:

JavaScript alert dialog in the browserJavaScript alert dialog in the browser

The alert() method is also useful for testing your JavaScript code and see if a certain variable holds the right value. For example, you may have the isMember variable that contains true if the user has logged in to your website and false when the user is not.

You can use the alert() method to print the value of the variable as follows:

const isMember = false;
alert(isMember);

The result would be as follows:

JavaScript alert displaying variableJavaScript alert displaying variable

Be aware that the alert() method can’t print an array of objects as follows:

const users = [
  {
    name: "Nathan",
  },
  {
    name: "Daisy",
  },
  {
    name: "Abby",
  },
];
alert(users);

The above code will cause the alert box to display [Object object] as in the screenshot below:

JavaScript alert can't display objectsJavaScript alert can't display objects

To prevent this issue, you need to transform the array of objects into a JSON string first using the JSON.stringify() method:

const users = [
  {
    name: "Nathan",
  },
  {
    name: "Daisy",
  },
  {
    name: "Abby",
  },
];
alert(JSON.stringify(users));

Now the alert box will display the values without any trouble:

JavaScript alert displaying stringified objectsJavaScript alert displaying stringified objects

And that’s how you can use the alert() method to display variable values.

You can use the alert() method to display multiple variables too, just like a normal string. It’s recommended for you to use template string to ember the variables in your alert box as follows:

const email = "nathan@email.com";
const username = "nathan";
const isMember = true;
alert(`Your values: \n 
  email: ${email} \n 
  username: ${username} \n 
  isMember: ${isMember} \n 
  You can use this alert as your template for displaying values`);

The result in the browser will be similar to this:

JavaScript alert displaying multiple variables

JavaScript alert displaying multiple variables

Feel free to use the alert() call above as you require it 😉

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

#javascript #value 

Display A Variable Value using JavaScript Alert Dialog
Gordon  Murray

Gordon Murray

1669190160

How to Assign Value with Ng-change in Angular JS

What is Ng-change in Angular JS and how do assign value to it?

Hi, let’s learn about an interesting directive provided in AngularJS, i.e. ng-change directive, the name itself partially gives away the work that it performs. Programmers usually get confused between on-change and ng-change events, let’s clear out everything today in this blog. The topics we will take up today will be:

  • What is a directive?
  • What is ng-change?
  • Important points while using ng-change directive
  • Syntax
  • Example

Before proceeding with the blog, we will first have a quick look at what Directives are in AngularJS.

What is a directive?

AngularJS directives are simply extended HTML attributes with a prefix ‘ng-‘. AngularJS provides a set of built-in directives which offer various functionalities to our applications. 

AngularJS also lets us define our own directives.

What is ng-change?

Ng-change is a directive in AngularJS which is meant for performing operations when a component value or event is changed. In other words, ng-change directive tells AngularJS what to do when the value of an HTML element changes.

An ng-model directive is required by the ng-change directive.

Important points while using ng-change directive:

  • What happens to onChange event? The ng-change directive from AngularJS does not override the element’s original onchange event, both the ng-change expression and the original onchange events will be executed.
  • The ng-change event gets triggered at every change in the value. It will not wait for all the changes to be made, or for the input field to lose focus.
  • The ng-change event is only triggered if there is an actual change in the input value, and not if the change was made from a JavaScript.
  • This ng-change directive is supported by the HTML tags like <input>, <select>, and <textarea>.
  • The ngChange expression is evaluated only when a change in the input value causes a new value to be committed to the model.

It will not be evaluated:

  1. if the value returned from the $parsers transformation pipeline has not changed
  2. if the input continued to be invalid, since the model will stay null
  3. if the model is changed not by an input value but programmatically.

Note, this directive requires ngModel to be present.

Syntax:

<element ng-change=“expression”></element>  

expression: It specifies an expression that is executed when value of an element changes.

Example:

<!DOCTYPE html>  
<html>  
<script src="<a href="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js">http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js</a>"></script>  
<body ng-app="App1">  
<div ng-controller="Cng1">  
  <p>Please type in the input field:</p>  
  <input type="text" ng-change="myFunc()" ng-model="Val" />  
  <p>The input field has changed {{count}} times.</p>  
</div>  
   
<script>  
  angular.module('App1', [])  
    .controller('cng1l', ['$scope', function($scope) {  
      $scope.count = 0;  
      $scope.myFunc = function() {  
        $scope.count++;  
      };  
    }]);  
</script>  
</body>  
</html>  

Output (After 3 changes)

Please type in the input field:

The input field has changed 3 times.

I hope, by now you might have got a clear understanding of the ng-change directive, try to use it in your programs and see how much you have learned. Thanks for reading. I would recommend you to go through this Angular Tutorial Edureka video playlist to watch videos and learn how to work with the Angular applications.

Now that you know the Angular Directive, check out the Angular Course by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. Angular is a JavaScript framework which is used to create scalable, enterprise, and performance client-side web applications. With Angular framework adoption being high, performance management of the application is community driven indirectly driving better job opportunities. The Angular Certification Training aims at covering all these new concepts around Enterprise Application Development.

Original article source at: https://www.edureka.co/

#angular #value 

How to Assign Value with Ng-change in Angular JS

Creating default object from empty value in PHP

Learn how you can solve PHP warning message Creating default object from empty value.

The message PHP Warning: Creating default object from empty value appears when you assign property to an object without initializing the object first.

Here’s an example code that triggers the warning:

<?php
$user->name = "Jack";

In the code above, the $user object has never been initialized.

When assigning the name property to the $user object, the warning message gets shown:

Warning: Creating default object from empty value

To solve this warning, you need to initialize the $user object before assigning properties to it.

There are three ways you can initialize an object in PHP:

Let’s learn how to do all of them in this tutorial.

PHP initialize object with stdClass

The stdClass is a generic empty class provided by PHP that you can use for whatever purpose.

One way to initialize an object is to create a new instance of the stdClass() like this:

<?php
$user = new stdClass();
$user->name = "Jack";

After initializing the $user variable as an object instance, you can assign any property to that object without triggering the warning.

PHP initialize object by casting an array as an object

You can also cast an empty array as an object like this:

<?php
$user = (object)[];
$user->name = "Jack";

By casting an empty array as an object, you can assign properties to that object.

PHP initialize object by creating a new anonymous class instance

PHP also allows you to create a new anonymous class instance by using the new class keyword:

<?php
$user = new class {};
$user->name = "Jack";

The anonymous class instance will be an empty object, and you can assign properties to it.

Now you’ve learned how to solve the PHP Warning: Creating default object from empty value. Nice job! 👍

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

#php #value #object 

Creating default object from empty value in PHP
Bongani  Ngema

Bongani Ngema

1668674726

How to Get The Current Directory (folder) Value in Node

Learn how to use NodeJS to get the current directory (folder)

Sometimes, you need to get a string representing the current directory or folder your JavaScript code is being executed.

There are two ways you can get the current directory in NodeJS:

  • Using the special variable __dirname
  • Using the built-in method process.cwd()

This tutorial will show you how to use both ways. Let’s look at __dirname first.

Get current directory with __dirname

The __dirname variable is a special variable available when you run JavaScript code using NodeJS.

The code below shows how you can use the special variable:

console.log("Current directory:", __dirname);

The variable will print the path to the directory, starting from the root directory.

Here’s the output on my computer:

Current directory: /Users/nsebhastian/Desktop/test

And just like that, you can get the current working directory in NodeJS. Let’s look at process.cwd() method next.

Get current directory with process.cwd()

The process.cwd() method works just like the __dirname variable. It prints the path to the current working directory from the root directory:

console.log("Current directory:", process.cwd());
// Current directory: /Users/nsebhastian/Desktop/test

Exclusively get the current directory

When you need only the current directory where the script is being executed, you can use the built-in path module:

const path = require("path");

The path module has the basename() method, which returns only the last portion of a path. The last portion of the __dirname variable for my computer is test so it will be returned by the method:

const path = require("path");

const directoryName = path.basename(__dirname);
console.log(directoryName); // test

And that’s how you can get the string representing the current directory or folder in NodeJS.

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

#node #value #current 

How to Get The Current Directory (folder) Value in Node

How to Search Multidimensional Array with Key and Value in PHP

How you can search multidimensional arrays in PHP that match specific values in PHP

To handle searching a multidimensional array, you can use either the foreach statement or the array_search() function.

A PHP multidimensional array can be searched to see if it has a certain value.

Let’s see an example of performing the search. Suppose you have a multidimensional array with the following structure:

$users = [
    [
        "uid" => "111",
        "name" => "Nathan",
        "age" => 29,
    ],
    [
        "uid" => "254",
        "name" => "Jessie",
        "age" => 25,
    ],
    [
        "uid" => "305",
        "name" => "Michael",
        "age" => 30,
    ],
];

To search the array by its value, you can use the foreach statement.

You need to loop over the array and see if one of the child arrays has a specific value.

For example, suppose you want to get the array with the uid value of 111:

$id = "111";
foreach ($users as $k => $v) {
    if ($v["uid"] === $id) {
        print $users[$k];
    }
}

Note that the comparison operator in the code above uses triple equal ===.

This means the type of compared values must be the same.

The code above will produce the following output:

Array
(
    [uid] => 111
    [name] => Nathan
    [age] => 29
)

In PHP 5.5 and above, you can also use the array_search() function combined with the array_column() function to find an array that matches a condition.

See the example below:

$name = "Michael";
$key = array_search($name, array_column($users, "name"));
print_r($users[$key]);

The above code will produce the following output:

Array
(
    [uid] => 305
    [name] => Michael
    [age] => 30
)

Let’s create a custom function from the search code so that you can perform a more dynamic search based on key and value.

This custom function accepts three parameters:

  1. The key you want to search
  2. The value you want the key to have
  3. The array you want to search

The function can be written as follows:

function find_array($name, $value, $array) {
    $key = array_search($name, array_column($array, $value));
    return $array[$key];
}

To handle a case where the specific value is not found, you need to add an if condition to the function.

You can return false or null when the $key is not found:

function find_array($k, $v, $array) {
    $key = array_search($v, array_column($array, $k));
    // 👇 key is found, return the array
    if ($key !== false) {
        return $array[$key];
    }
    // 👇 key is not found, return false
    return false;
}

Now you can use the find_array() function anytime you need to search a multidimensional array.

Here are some examples:

// 👇 value exists
$result = find_array("name", "Jessie", $users);
if ($result) {
    print_r($result);
} else {
    print "Array with that value is not found!";
}

// 👇 value doesn't exists
$result = find_array("uid", "1000", $users);
if ($result) {
    print_r($result);
} else {
    print "Array with that value is not found!";
}

The code above will produce the following output:

Array
(
    [uid] => 254
    [name] => Jessie
    [age] => 25
)
Array with that value is not found!

Now you’ve learned how to search a multidimensional array in PHP.

When you need to find an array with specific values, you only need to call the find_array() function above.

Feel free to use the function in your PHP project. 👍

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

#php #search #array #key #value 

How to Search Multidimensional Array with Key and Value in PHP

Data-transfer-object: Data Transfer Objects with Batteries included

Data transfer objects with batteries included

Installation

You can install the package via composer:

composer require spatie/data-transfer-object
  • Note: v3 of this package only supports php:^8.0. If you're looking for the older version, check out v2.

Usage

The goal of this package is to make constructing objects from arrays of (serialized) data as easy as possible. Here's what a DTO looks like:

use Spatie\DataTransferObject\Attributes\MapFrom;
use Spatie\DataTransferObject\DataTransferObject;

class MyDTO extends DataTransferObject
{
    public OtherDTO $otherDTO;
    
    public OtherDTOCollection $collection;
    
    #[CastWith(ComplexObjectCaster::class)]
    public ComplexObject $complexObject;
    
    public ComplexObjectWithCast $complexObjectWithCast;
    
    #[NumberBetween(1, 100)]
    public int $a;
    
    #[MapFrom('address.city')]
    public string $city;
}

You could construct this DTO like so:

$dto = new MyDTO(
    a: 5,
    collection: [
        ['id' => 1],
        ['id' => 2],
        ['id' => 3],
    ],
    complexObject: [
        'name' => 'test',
    ],
    complexObjectWithCast: [
        'name' => 'test',
    ],
    otherDTO: ['id' => 5],
);

Let's discuss all possibilities one by one.

Named arguments

Constructing a DTO can be done with named arguments. It's also possible to still use the old array notation. This example is equivalent to the one above.

$dto = new MyDTO([
    'a' => 5,
    'collection' => [
        ['id' => 1],
        ['id' => 2],
        ['id' => 3],
    ],
    'complexObject' => [
        'name' => 'test',
    ],
    'complexObjectWithCast' => [
        'name' => 'test',
    ],
    'otherDTO' => ['id' => 5],
]);

Value casts

If a DTO has a property that is another DTO or a DTO collection, the package will take care of automatically casting arrays of data to those DTOs:

$dto = new MyDTO(
    collection: [ // This will become an object of class OtherDTOCollection
        ['id' => 1],
        ['id' => 2], // Each item will be an instance of OtherDTO
        ['id' => 3],
    ],
    otherDTO: ['id' => 5], // This data will be cast to OtherDTO
);

Custom casters

You can build your own caster classes, which will take whatever input they are given, and will cast that input to the desired result.

Take a look at the ComplexObject:

class ComplexObject
{
    public string $name;
}

And its caster ComplexObjectCaster:

use Spatie\DataTransferObject\Caster;

class ComplexObjectCaster implements Caster
{
    /**
     * @param array|mixed $value
     *
     * @return mixed
     */
    public function cast(mixed $value): ComplexObject
    {
        return new ComplexObject(
            name: $value['name']
        );
    }
}

Class-specific casters

Instead of specifying which caster should be used for each property, you can also define that caster on the target class itself:

class MyDTO extends DataTransferObject
{
    public ComplexObjectWithCast $complexObjectWithCast;
}
#[CastWith(ComplexObjectWithCastCaster::class)]
class ComplexObjectWithCast
{
    public string $name;
}

Default casters

It's possible to define default casters on a DTO class itself. These casters will be used whenever a property with a given type is encountered within the DTO class.

#[
    DefaultCast(DateTimeImmutable::class, DateTimeImmutableCaster::class),
    DefaultCast(MyEnum::class, EnumCaster::class),
]
abstract class BaseDataTransferObject extends DataTransferObject
{
    public MyEnum $status; // EnumCaster will be used
    
    public DateTimeImmutable $date; // DateTimeImmutableCaster will be used
}

Using custom caster arguments

Any caster can be passed custom arguments, the built-in ArrayCaster implementation is a good example of how this may be used.

Using named arguments when passing input to your caster will help make your code more clear, but they are not required.

For example:

    /** @var \Spatie\DataTransferObject\Tests\Foo[] */
    #[CastWith(ArrayCaster::class, itemType: Foo::class)]
    public array $collectionWithNamedArguments;
    
    /** @var \Spatie\DataTransferObject\Tests\Foo[] */
    #[CastWith(ArrayCaster::class, Foo::class)]
    public array $collectionWithoutNamedArguments;

Note that the first argument passed to the caster constructor is always the array with type(s) of the value being casted. All other arguments will be the ones passed as extra arguments in the CastWith attribute.

Validation

This package doesn't offer any specific validation functionality, but it does give you a way to build your own validation attributes. For example, NumberBetween is a user-implemented validation attribute:

class MyDTO extends DataTransferObject
{
    #[NumberBetween(1, 100)]
    public int $a;
}

It works like this under the hood:

#[Attribute(Attribute::TARGET_PROPERTY | Attribute::IS_REPEATABLE)]
class NumberBetween implements Validator
{
    public function __construct(
        private int $min,
        private int $max
    ) {
    }

    public function validate(mixed $value): ValidationResult
    {
        if ($value < $this->min) {
            return ValidationResult::invalid("Value should be greater than or equal to {$this->min}");
        }

        if ($value > $this->max) {
            return ValidationResult::invalid("Value should be less than or equal to {$this->max}");
        }

        return ValidationResult::valid();
    }
}

Mapping

You can map a DTO property from a source property with a different name using the #[MapFrom] attribute.

It works with a "dot" notation property name or an index.

class PostDTO extends DataTransferObject
{
    #[MapFrom('postTitle')]
    public string $title;
    
    #[MapFrom('user.name')]
    public string $author;
}

$dto = new PostDTO([
    'postTitle' => 'Hello world',
    'user' => [
        'name' => 'John Doe'
    ]
]);
class UserDTO extends DataTransferObject
{

    #[MapFrom(0)]
    public string $firstName;
    
    #[MapFrom(1)]
    public string $lastName;
}

$dto = new UserDTO(['John', 'Doe']);

Sometimes you also want to map them during the transformation to Array. A typical usecase would be transformation from camel case to snake case. For that you can use the #[MapTo] attribute.

class UserDTO extends DataTransferObject
{

    #[MapFrom(0)]
    #[MapTo('first_name')]
    public string $firstName;
    
    #[MapFrom(1)]
    #[MapTo('last_name')]
    public string $lastName;
}

$dto = new UserDTO(['John', 'Doe']);
$dto->toArray() // ['first_name' => 'John', 'last_name'=> 'Doe'];
$dto->only('first_name')->toArray() // ['first_name' => 'John'];

Strict DTOs

The previous version of this package added the FlexibleDataTransferObject class which allowed you to ignore properties that didn't exist on the DTO. This behaviour has been changed, all DTOs are flexible now by default, but you can make them strict by using the #[Strict] attribute:

class NonStrictDto extends DataTransferObject
{
    public string $name;
}

// This works
new NonStrictDto(
    name: 'name',
    unknown: 'unknown'
);
use \Spatie\DataTransferObject\Attributes\Strict;

#[Strict]
class StrictDto extends DataTransferObject
{
    public string $name;
}

// This throws a \Spatie\DataTransferObject\Exceptions\UnknownProperties exception
new StrictDto(
    name: 'name',
    unknown: 'unknown'
);

Helper functions

There are also some helper functions provided for working with multiple properties at once.

$postData->all();

$postData
    ->only('title', 'body')
    ->toArray();
    
$postData
    ->except('author')
    ->toArray();

Note that all() will simply return all properties, while toArray() will cast nested DTOs to arrays as well.

You can chain the except() and only() methods:

$postData
    ->except('title')
    ->except('body')
    ->toArray();

It's important to note that except() and only() are immutable, they won't change the original data transfer object.

Immutable DTOs and cloning

This package doesn't force immutable objects since PHP doesn't support them, but you're always encouraged to keep your DTOs immutable. To help you, there's a clone method on every DTO which accepts data to override:

$clone = $original->clone(other: ['name' => 'a']);

Note that no data in $original is changed.

Collections of DTOs

This version removes the DataTransferObjectCollection class. Instead you can use simple casters and your own collection classes.

Here's an example of casting a collection of DTOs to an array of DTOs:

class Bar extends DataTransferObject
{
    /** @var \Spatie\DataTransferObject\Tests\Foo[] */
    #[CastWith(FooArrayCaster::class)]
    public array $collectionOfFoo;
}

class Foo extends DataTransferObject
{
    public string $name;
}
class FooArrayCaster implements Caster
{
    public function cast(mixed $value): array
    {
        if (! is_array($value)) {
            throw new Exception("Can only cast arrays to Foo");
        }

        return array_map(
            fn (array $data) => new Foo(...$data),
            $value
        );
    }
}

If you don't want the redundant typehint, or want extended collection functionality; you could create your own collection classes using any collection implementation. In this example, we use Laravel's:

class Bar extends DataTransferObject
{
    #[CastWith(FooCollectionCaster::class)]
    public CollectionOfFoo $collectionOfFoo;
}

class Foo extends DataTransferObject
{
    public string $name;
}
use Illuminate\Support\Collection;

class CollectionOfFoo extends Collection
{
    // Add the correct return type here for static analyzers to know which type of array this is 
    public function offsetGet($key): Foo
    {
        return parent::offsetGet($key);
    }
}
class FooCollectionCaster implements Caster
{
    public function cast(mixed $value): CollectionOfFoo
    {
        return new CollectionOfFoo(array_map(
            fn (array $data) => new Foo(...$data),
            $value
        ));
    }
}

Simple arrays of DTOs

For a simple array of DTOs, or an object that implements PHP's built-in ArrayAccess, consider using the ArrayCaster which requires an item type to be provided:

class Bar extends DataTransferObject
{
    /** @var \Spatie\DataTransferObject\Tests\Foo[] */
    #[CastWith(ArrayCaster::class, itemType: Foo::class)]
    public array $collectionOfFoo;
}

Testing

composer test

Changelog

Please see CHANGELOG for more information on what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail security@spatie.be instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

External tools

  • json2dto: a GUI to convert JSON objects to DTO classes (with nesting support). Also provides a CLI tool for local usage.
  • Data Transfer Object Factory: Intelligently generates a DTO instance using the correct content for your properties based on its name and type.

Credits

Our Arr class contains functions copied from Laravels Arr helper.

Download Details:

Author: Spatie
Source Code: https://github.com/spatie/data-transfer-object 
License: MIT license

#php #data #object #value 

Data-transfer-object: Data Transfer Objects with Batteries included
Rupert  Beatty

Rupert Beatty

1666547460

ReactiveSwift: Streams Of Values Over Time

ReactiveSwift

Streams of values over time. Tailored for Swift.

What is ReactiveSwift in a nutshell?

ReactiveSwift offers composable, declarative and flexible primitives that are built around the grand concept of streams of values over time.

These primitives can be used to uniformly represent common Cocoa and generic programming patterns that are fundamentally an act of observation, e.g. delegate pattern, callback closures, notifications, control actions, responder chain events, futures/promises and key-value observing (KVO).

Because all of these different mechanisms can be represented in the same way, it’s easy to declaratively compose them together, with less spaghetti code and state to bridge the gap.

References

API Reference

API Contracts

Contracts of the ReactiveSwift primitives, Best Practices with ReactiveSwift, and Guidelines on implementing custom operators.

Debugging Techniques

RxSwift Migration Cheatsheet

Installation

ReactiveSwift supports macOS 10.9+, iOS 9.0+, watchOS 2.0+, tvOS 9.0+ and Linux.

Carthage

If you use Carthage to manage your dependencies, simply add ReactiveSwift to your Cartfile:

github "ReactiveCocoa/ReactiveSwift" ~> 6.1

If you use Carthage to build your dependencies, make sure you have added ReactiveSwift.framework to the "Linked Frameworks and Libraries" section of your target, and have included them in your Carthage framework copying build phase.

CocoaPods

If you use CocoaPods to manage your dependencies, simply add ReactiveSwift to your Podfile:

pod 'ReactiveSwift', '~> 6.1'

Swift Package Manager

If you use Swift Package Manager, simply add ReactiveSwift as a dependency of your package in Package.swift:

.package(url: "https://github.com/ReactiveCocoa/ReactiveSwift.git", from: "6.1.0")

Git submodule

  1. Add the ReactiveSwift repository as a submodule of your application’s repository.
  2. Run git submodule update --init --recursive from within the ReactiveCocoa folder.
  3. Drag and drop ReactiveSwift.xcodeproj into your application’s Xcode project or workspace.
  4. On the “General” tab of your application target’s settings, add ReactiveSwift.framework to the “Embedded Binaries” section.
  5. If your application target does not contain Swift code at all, you should also set the EMBEDDED_CONTENT_CONTAINS_SWIFT build setting to “Yes”.

Playground

We also provide a Playground, so you can get used to ReactiveCocoa's operators. In order to start using it:

  1. Clone the ReactiveSwift repository.
  2. Retrieve the project dependencies using one of the following terminal commands from the ReactiveSwift project root directory:
    • git submodule update --init --recursive OR, if you have Carthage installed
    • carthage checkout
  3. Open ReactiveSwift.xcworkspace
  4. Build ReactiveSwift-macOS scheme
  5. Finally open the ReactiveSwift.playground
  6. Choose View > Show Debug Area

Getting Started

Learn about the Core Reactive Primitives in ReactiveSwift, and Basic Operators available offered by these primitives.

Extended modules

ModuleRepositoryDescription
ReactiveCocoaReactiveCocoa/ReactiveCocoa 
Extend Cocoa frameworks and Objective-C runtime APIs with ReactiveSwift bindings and extensions.
LoopReactiveCocoa/Loop 
Composable unidirectional data flow with ReactiveSwift.
ReactiveSwift Composable Architecturetrading-point/reactiveswift-composable-architecture 
The Pointfree Composable Architecture using ReactiveSwift instead of Combine.

🚄 Release Roadmap

Have a question?

If you need any help, please visit our GitHub issues or Stack Overflow. Feel free to file an issue if you do not manage to find any solution from the archives.

Release Roadmap

Current Stable Release:
GitHub release

Plan of Record

ABI stability release

ReactiveSwift has no plan to declare ABI and module stability at the moment. It will continue to be offered as a source only dependency for the foreseeable future.

Download Details:

Author: ReactiveCocoa
Source Code: https://github.com/ReactiveCocoa/ReactiveSwift 
License: MIT license

#swift #stream #value 

ReactiveSwift: Streams Of Values Over Time

FlexFloat.jl: These Floating Point Values Stretch to Maintain Accuracy

FlexFloat.jl

These are values that stretch preserve accuracy.

The underlying representation is an interval with bounds that may be closed (exact) or open (inexact). An exact bound takes the floating point value given at that boundry to be a precisely accurate quantity. Two examples of exact quantities are counts and monetary balances. An inexact bound takes the floating point value given at the lower [higher] boundry to be largest [smallest] possible quantity to be included in the bounding value's span. An inexact bound bound extendes away from the center of the interval, almost reaching the next lower [higher] floating point value. Inexact bounds cover a real span that is not fully representable with machine floats -- and from that fact tend to follow results with relatively tight bounds.

The package internals handle all of that without additional guidance. There are four kinds of intervals:

  (a) both bounds are exact (closed): clcl(1,2)
  (b) both bounds are inexact (open): oppp(1,2)
  (c) only the lower bound is exact : clop(1,2)
  (d) only the upper bound is exact : opcl(1,2)

An exact value of 1 is entered as Exact(1). Exact is a synonym for clcl.
An interval with exact bounds of zero and one is entered as Exact(0,1).
An inexact value of 3 is entered as Inexact(3). Inexact is a synonym for opop.
     this indicates any value within the Real range that extends from prevfloat(3) to nextfloat(3) without including either.
The inexact interval Inexact(1,2) indicates any value within the Real range from prevfloat(1) to nextfloat(2), exclusively.

Any values may exist in one of two states

states 'exact', 'inexact' are exported; 'situated', 'enhanced' are the internal names.

This capability exists transparently -- apps that do not need it do not see it.

Each Flex may be [re]assigned either of two states and the statefulness persists unless reassigned. There is no limit on state changes, nor any requirement that states change. The state is independant of the kind of interval (ClCl, OpOp, ClOp, OpCl); one may create some logical dependance in code. To simplify use,

        clcl(), opop(), clop(), opcl() create values in the 'inexact' stat
        ClCl(), OpOp(), ClOp(), OpCl() create values in the 'exact' state
        (lowercase is used with situated values, titlecase with enhanced values)

   Assignment, determination and utilization of statefulness is entirely given to your application.
   
              op(a,b) where isexact(a)&isinexact(b) and a,b are not of the same sculpture
              is not predefinded, nor are associated conversions .. **encode your intent**.

The file 'src/type/cvtqualia.jl' has the comparison and conversion defaults for statefulness.

###Quick Guide

#=
   a closed boundry (an exact bound)  is shown with single angle brackets
   an open boundry (an inexact bound) is shown with double angle brackets

   when the lower bound and the upper bound are equal one number is shown
   when the lower bound and the upper bound are equal, one may use it alone
   
   values in the 'exact' state are tied with '⌁', '~' ties 'inexact' values
=#

julia> opop(1.2345,1.2346), ClCl(1), clcl(1,1), OpOp(1.2,1.2)
(⟪1.2345⌁1.2346⟫,⟨1.0⌁⟩,⟨1.0~⟩,⟪1.2~⟫)

# different sorts of values may be intermixed for arithmetic
julia> a=clcl(2.0); b=opcl(1.5, 2.0); a-b, a*b, a/b
(⟪0.0⌁0.5⟩,⟪3.0⌁4.0⟩,⟪1.0⌁1.3333333333333335⟩)

# Flex64 is a typealias, it works like clcl()
julia> Flex64(1.0)
⟨1.0⌁2.0⟩
julia> Flex64(1.0,2.0)
⟨1.0⌁2.0⟩

###And More


# elementary functions of FlexFloat values
julia> using FlexFloat

julia> exp(OpOp(1.0))
⟨2.7182818284590446~2.7182818284590455⟩ # diameter: 8.88e-16

# optionally using CRlibm for more accuracy
julia> using CRlibm      # must preceed using FlexFloat
julia> using FlexFloat

julia> exp(OpOp(1.0))
⟨2.718281828459045~2.7182818284590455⟩ # diameter: 4.44e-16

# polynomial evaluation at FlexFloat values
julia> using Polynomials
julia> using FlexFloat

julia> p = Poly([4.0,8,1,-5,-1,1]);
julia> polyval(p,OpOp(2.5,2.5+eps(2.5)))
⟪10.718749999999991~10.718750000000039⟫

# cdf, pdf, quantile at FlexFloat values
# for continuous univariate distributions
julia> using Distributions  # must preceed using FlexFloat
julia> using FlexFloat

julia> ND=normal();
julia> pdf(ND, ClCl(0.999,0.9995))
⟨0.24209170987131956~0.24221269516298546⟩
julia> pdf(ND, OpOp(0.999,0.9995))
⟨0.24209170987131953~0.24221269516298546⟩


supports

         (==), (!=), (<), (<=), (>=), (>),
         (+), (-), (*), (/),
         sqrt, exp, log,
         sin, cos, tan, csc, sec, cot,
         asin, acos, atan, acsc, asec, acot,
         sinh, cosh, tanh, csch, sech, coth,
         asinh, acosh, atanh, acsch, asech, acoth,
         erf, erfinv

         when the Distributions package is pre-loaded:
            cdf, pdf, quantile for univariate continuous distributions

References

(please see doc/References.md for all referenced material and links)

John L. Gustafson, The End of Error: Unum Computing
Ulrich Kulisch, Up-to-date Interval Arithmetic

Download Details:

Author: J-Sarnoff
Source Code: https://github.com/J-Sarnoff/FlexFloat.jl 
License: MIT license

#julia #value 

FlexFloat.jl: These Floating Point Values Stretch to Maintain Accuracy

FieldDefaults.jl: Flexible, Overridable Default Field Values

FieldDefaults 

A lightweight package that adds keyword defaults to (the also lightweight!) FieldMetadata.jl.

The @default_kw macro adds a keyword arg constructor to a type:

@default_kw struct MyStruct
    foo::Int | 1
    bar::Int | 2
end

julia> m = MyStruct()
julia> m.foo
1

julia> m.bar
2

It has a similar outcome (though entirely difference mechanism) to Parameters.jl. It has some limitations: presently it only adds an outside constructor, and defaults can't use the other default values.

But it has some other nice features. Defaults can be added to a struct that has already been defined by prefixing re to the macro name, as in FieldMetadata.jl:

struct SomeoneElseDefined
    foo::Int
    bar::Int
end

@redefault struct SomeoneElseDefined
    foo | 7
    bar | 19
end

Each default value can also be overridden by declaring a new function:

default(::YourType, ::Type{Val{:fieldname}}) = 99

The u@default_kw behaves as @default_kw but combines defaults with the units metadata field in the constructor.

Additional info

Extra metadata fields are easy to add to a struct at definition time or afterwards, using a @metadata macro.

Default values of single structs or more complex composite types can be flattened to tuples or vectors using Flatten.jl. This can be combined with fieldnames, other metadata and current field values for generating tabular displays, or other uses.

Download Details:

Author: Rafaqz
Source Code: https://github.com/rafaqz/FieldDefaults.jl 
License: View license

#julia #value 

FieldDefaults.jl: Flexible, Overridable Default Field Values

AutoTypeParameters.jl: A Julia Library to Reversibly Encode "any"

AutoTypeParameters

A Julia library to reversibly encode "any" value so that it can be used as a type parameter.

Do I Need This?

You need this if you have an error like:

ERROR: TypeError: apply_type: in Val, expected Type{T}, got XXX

when you try to create a "complicated" dependent type.

That error is (partly) explained here - it occurs because the kinds of things that can be types in Julia is limited. Partly for sensible reasons (you don't want a mutable type), but also because of arbitrary implementation details.

What Does It Do?

This package has two functions - freeze() and thaw() - that translate arbitrary values back and forth into a form that is accepted by Julia.

How Does It Work?

You can choose between two encondings.

Using showall()

By default, freeze() takes the output from showall() and converts it into a Symbol, while thaw() uses eval() to convert it back into a "real" value:

julia> using AutoTypeParameters

julia> freeze("a string")
symbol("ATP \"a string\"")

julia> thaw(eval, symbol("ATP \"a string\""))
"a string"

The advantage of the default approach is that the type parameter is readable. The disadvantage, of course, is that it requires showall() to generate output that eval() can handle.

Using serialize()

Alternatively (eg for values which do not have a useful showall() function), the base64 encoded output from serialize() can be used:

julia> using AutoTypeParameters

julia> freeze("a string"; format=:serialize)
symbol("ATP=JhWGYSBzdHJpbmc=")

julia> thaw(eval, symbol("ATP=JhWGYSBzdHJpbmc="))
"a string"

Warnings

Because this package uses eval() it should not be passed arbitrary values rom an untrusted user.

Example

julia> using AutoTypeParameters

julia> type MyType{N}
           x
       end

julia> MyType{"strings not allowed"}(42)
ERROR: TypeError: apply_type: in MyType, expected Type{T}, got ASCIIString

julia> MyType(N, x) = MyType{freeze(N)}(x)
MyType{N}

julia> MyType("strings not allowed", 42)
MyType{symbol("ATP \"strings not allowed\"")}(42)

julia> extract_type{N}(x::MyType{N}) = thaw(eval, N)
extract_type (generic function with 1 method)

julia> extract_type(MyType("strings not allowed", 42))
"strings not allowed"

Download Details:

Author: Andrewcooke
Source Code: https://github.com/andrewcooke/AutoTypeParameters.jl 
License: View license

#julia #value #type 

AutoTypeParameters.jl: A Julia Library to Reversibly Encode "any"
Gordon  Taylor

Gordon Taylor

1662040680

Obj-str: A Tiny (96B) Library for Serializing Object Values to Strings

obj-str

A tiny (96B) library for serializing Object values to Strings.

This module's intended use is for converting an Object with CSS class names (as keys) to a space-delimited className string. Other modules have similar goals (like classnames), but obj-str only does one thing. This is why it's only 100 bytes gzipped!

PS: I made this because Preact 8.0 removed this built-in behavior and I wanted a quick, drop-in replacement.

Install

$ npm install --save obj-str

Usage

import objstr from 'obj-str';

objstr({ foo:true, bar:false, baz:isTrue() });
//=> 'foo baz'

React

With React (or any of the React-like libraries!), you can take advantage of any props or state values in order to express conditional classes as an object.

import React from 'react';
import objstr from 'obj-str';

const TodoItem = ({ text, isDone, disabled }) => (
  <li className={ objstr({ item:true, completed:isDone, disabled }) }>
    <input type="checkbox" disabled={ disabled } checked={ isDone } />
    <label>{ text }</label>
  </li>
);

Preact

For simple use, the React example will work for Preact too. However, you may also define a custom vNode "polyfill" to automatically handle Objects when used inside className.

Note: For users of Preact 7.1 and below, you do not need this module! Your version includes this behavior out of the box!

import objstr from 'obj-str';
import { options } from 'preact';

const old = options.vnode;

options.vnode = vnode => {
  const props = vnode.attributes;
  if (props != null) {
    const k = 'class' in props ? 'class' : 'className';
    if (props[k] && typeof props[k]=='object') {
      props[k] = objstr(props[k]);
    }
  }
  old && old(vnode);
}

API

objstr(input)

input

Type: Object

A hashmap of keys & their truthy/falsey values. Booleans are preferred when speed is critically important.

Related

babel-plugin-optimize-obj-str - Babel plugin to transform obj-str calls into optimized expressions.

clsx - Drop-in replacement for obj-str and classnames – handles all (and multiple) input types.

Download Details:

Author: lukeed
Source Code: https://github.com/lukeed/obj-str 
License: MIT license

#javascript #object #value #strings 

Obj-str: A Tiny (96B) Library for Serializing Object Values to Strings