String

String

A string is a finite sequence of symbols, commonly used for text, though sometimes for arbitrary data.
Gordon  Matlala

Gordon Matlala

1669612996

How to Use Kotlin String.format() Method To format Your String Values

Kotlin String format() method example

Kotlin borrows the String.format() method from the Java language, so you can format your string values with it.

For example, suppose you want to format the PI value into a two-digit format (3.14)

Here’s how you can format the digits:

val PI = 3.14159265358979323
val myStr = String.format("The PI value is %.2f", PI)

print(myStr)// The PI value is 3.14

Like in Java, the first argument of the format() function will be the string format, while the rest would be the values to put into the string.

The %f inside the string is used to format a floating value. The .2 is added to limit the floating-point to 2 digits.

If you want to pass a String value to the format, you can use the %s specifier as follows:

val name = "Nathan"
val myStr = String.format("My name is %s", name)

print(myStr)// My name is Nathan

Here’s a full list of specifiers you can use in Kotlin:

  • %b - Boolean
  • %c - Character
  • %d - Signed Integer
  • %e - Float in Scientific Notation
  • %f - Float in Decimal Format
  • %g - Float in Decimal or Scientific Notation, depending on the value
  • %h - Hashcode of the supplied argument
  • %n - Newline separator
  • %o - Octal Integer (base 8)
  • %s - String
  • %t - Date or Time
  • %x - Hexadecimal Integer (base 16)

You can use as many specifiers as you need in your String.format() method.

Here’s an example of using 3 specifiers in the string format (a Boolean, a String, and an Integer):

val myStr = String.format("%b | %s | %d", false, "Morning", 90)

print(myStr)// false | Morning | 90

Kotlin will run the formatter from left to right, taking the second argument as the first value for the string format and so on.

And that’s how you can format string values using Kotlin String.format() method 👍

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

#kotlin #string #method 

How to Use Kotlin String.format() Method To format Your String Values
Gordon  Taylor

Gordon Taylor

1669470540

How to Code A Random String Generator Program using JavaScript

Code recipe: JavaScript random string generator

There are several ways to generate a random string with JavaScript, depending on the requirements you need to meet.

You can generate both random alphanumeric string, which is a combination of letter and numbers, and you can also generate a letter-only string. This tutorial will help you to learn both.

JavaScript random alphanumeric string

You can generate a random alphanumeric string with JavaScript by first creating a variable that contains all the characters you want to include in the random string.

For example, the following characters variable contains the numbers 0 to 9 and letters A to Z both in upper and lower cases:

const characters =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

Once you settled on the characters you want to include in your random string, you need to determine the length of the random string. For this tutorial, let’s generate a random string with 9 characters :

const characters =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const length = 9;

Now you need to create another variable that contains the random string. Just initialize the variable with an empty string like this:

const characters =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const length = 9;
let randomStr = "";

It’s time to generate the random string. Write a for loop that will iterate as long as the value of length variable as shown below:

const characters =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const length = 9;
let randomStr = "";

for (let i = 0; i < length; i++) {}

In each iteration, you need to generate a random number between 0 and characters.length - 1. You will use this number to pick a character from the characters variable that you will add to the randomStr variable.

The code inside the for loop will be as follows:

const characters =
  "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
const length = 9;
let randomStr = "";

for (let i = 0; i < length; i++) {
  const randomNum = Math.floor(Math.random() * characters.length);
  randomStr += characters[randomNum];
}

console.log(randomStr); // will be different with each execution

And that’s how you generate an alphanumeric random string using JavaScript. You can change the length variable value to change how many characters you have in the random string.

JavaScript random letter-only string

To generate a letter-only string, you can use the same method as generating a random alphanumeric string above. You just need to remove the numbers 0 to 9 from the characters variable:

const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
const length = 9;
let randomStr = "";

for (let i = 0; i < length; i++) {
  const randomNum = Math.floor(Math.random() * characters.length);
  randomStr += characters[randomNum];
}

console.log(randomStr); // will be different with each execution

And that’s how you can generate a random letter-only string 😉

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

#javascript #string #random 

How to Code A Random String Generator Program using JavaScript
Sheldon  Grant

Sheldon Grant

1669447821

How to Perform String interpolation using JavaScript

String interpolation in JavaScript tutorial

When you need to add JavaScript variable values and expressions to complete a string, your first intuition might be to concatenate the string using unary operators + as in the following example:

const name = "Nathan";
const age = 29;
console.log("My name is " + name + " and I'm " + age + " years old.");
// "My name is Nathan and I'm 29 years old."

But JavaScript ES6 actually provides you with a cleaner method to add expressions to a string. Instead of using single quotes '' or double quotes "" to form the string, you can use the backticks \``\ and the placeholder symbol ${expression} to form your string.

Forming a string using backticks is known as template literals or template string, and here’s how it works:

const name = "Nathan";
const age = 29;
console.log(`My name is ${name} and I'm ${age} years old.`);
// "My name is Nathan and I'm 29 years old."

A template string works just like ordinary string literals (single quote and double quote mark) with the addition of embedding JavaScript expressions into the string.

In the code example above, the printed string has the variable name and age values embedded into it, but you can actually perform some JavaScript expression evaluation as follows:

console.log(`10 - 5 equals ${10 - 5}`); // "10 - 5 equals 5"

You can even use ternary operator to evaluate conditions as follows:

let name;
console.log(`Hello, ${name ? name : "World"}!`);
// "Hello, World!"

name = "John";
console.log(`Hello, ${name ? name : "World"}!`);
// "Hello, John!"

Finally, when you need to write a literal placeholder syntax "${}" into your template string, you need to escape the placeholder syntax by putting the backslash \ symbol before the syntax as follows:

console.log(`My name is \${John Smith}`);
// "My name is ${John Smith}"

Without the backslash, JavaScript will consider the text "${John Smith}" as an expression instead of literal values.

String interpolation from template string is one of the most useful features of ES6 JavaScript. Modern web applications tend to be complex and have conditional outputs, So when you need to log an error or certain variable values into the screen, the template string will definitely help you out.

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

#javascript #string 

How to Perform String interpolation using JavaScript

How to Remove The First Character From A String in PHP

Learn how you can remove the first character from a string in PHP

To remove the first character from a string, you can use the ltrim() or substr() function.

The ltrim() function is used to strip whitespace from the beginning of a string.

To use the function, you need to pass the string and the character(s) to remove.

Consider the example below:

<?php
$str = "-Hello World!";
// 👇 remove the dash in front of H
$new_string = ltrim($str, "-");

print $new_string; // Hello World!
?>

But keep in mind that the ltrim() function removes all occurrences of the character(s) you specified as its second parameter:

<?php
$str = "---Hello World!";
// 👇 remove dashes in front of H
$new_string = ltrim($str, "-");

print $new_string; // Hello World!

If you explicitly want to remove only the first character, you need to use the substr() function instead.

The substr() function is used to return a portion of a string. You can use it to cut the first character as shown below:

<?php
$str = "---Hello World!";
// 👇 remove the first dash in front of H
$new_string = substr($str, 1);

print $new_string; // --Hello World!
?>

The second parameter of the substr() function determines the offset position where the function begins to cut the string.

Because a string index starts from 0, passing 1 as the offset position will cause the function to remove the first character from the string.

And that’s how you remove the first character in PHP. Nice! 👍

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

#php #remove #string 

How to Remove The First Character From A String in PHP

How to Reverse A String with JavaScript

Reversing a string is one of the most common programming exercises, and since JavaScript String object doesn’t have the reverse() method, you need to create a work around to get the job done.

There are two easy ways you can reverse a string:

  • Transform the string to array and call the Array.reverse() method
  • Use a for loop statement and create a new reversed string from the original string

This tutorial will help you learn how to do both. Let’s start with transforming the string to an array.

Reverse a string using Array reverse() method

You can reverse a string by first transforming that string to an array with String.split() method.

The String.split() method is a built-in method of the String object that allows you to split a string into several array elements.

When you pass an empty string ("") as an argument to the method, it will return an array with each character as a separate element.

let str = "Hello";

console.log(str.split("")); // ["H", "e", "l", "l", "o"]

Once you have the string split into an array, call the Array.reverse() method on the array to reverse the elements:

let str = "Hello";

console.log(str.split("").reverse()); // ["o", "l", "l", "e", "H"]

Next, call the Array.join() method so that the array will be transformed back to string.

You need to pass an empty string as an argument to the join() method or the string will be concatenated with a comma:

let str = "Hello";

console.log(str.split("").reverse().join("")); // "olleH"

You can reverse any kind of string using the combination of split(), reverse(), and join() methods.

Reverse a string using a for loop

To reverse a string using a for loop, you need to use the string length - 1 as the initial expression value and decrement the loop value in each iteration as long as it’s greater than or equal to zero:

for (let i = str.length - 1; i >= 0; i--)

Next, create a new empty string and add each character from the original string backwards using its index.

The following code example shows how you do it:

let str = "hello";
let reverseStr = "";

for (let i = str.length - 1; i >= 0; i--) {
  reverseStr += str[i];
}

console.log(reverseStr); // "olleh"

And that’s how you can reverse a string using a for loop statement.

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

#javascript #string 

How to Reverse A String with JavaScript
Oral  Brekke

Oral Brekke

1669198518

How to Use The Parseint() JavaScript Function

Extract integer from a string value using JavaScript parseInt() function

The JavaScript parseInt() function is used to get an integer value that can be extracted from other value types.

One of the most common uses of the parseInt() function is to get an integer from a string value as shown below:

let parsed = parseInt("50");

console.log(parsed); // 50
console.log(typeof parsed); // "number"

As you can see, the type of parsed variable is a number instead of a string.

The parseInt() method will return a NaN value when the given argument doesn’t have a valid integer representation.

The example below shows the parseInt() result of a boolean value and an empty string:

let parseA = parseInt(true);
let parseB = parseInt("");

console.log(parseA); // NaN
console.log(parseB); // NaN

When you pass an array of numbers, the parseInt() function will return the first element only.

This is because the function immediately returns the first integer value it can found from your argument:

let parseA = parseInt([28, 37, 61]);
console.log(parseA); // 28

let parseB = parseInt("32 years 8 months old");
console.log(parseB); // 32

The parseInt() function accepts a second number argument between 2 and 36 representing the base (or radix) numeral system used by the first argument.

For example, when you want to convert a binary number string to an integer, you can pass 2 as the function’s second argument:

let parseA = parseInt("1101", 2);
console.log(parseA); // 13

let parseB = parseInt("010", 2);
console.log(parseB); // 2

The binary numbers 1101 and 010 are converted to their base 10 representation with the parseInt() function.

When you omit the base number argument, the parseInt() function will consider the strings to be base 10 numbers.

You can also make the function think the argument is a base 16 number by adding 0X before the string as shown below:

let parseA = parseInt("FE8");
console.log(parseA); // NaN

let parseB = parseInt("0XFE8");
console.log(parseB); // 4072

The hexadecimal number FE8 represents the number 4072 in the base 10 system.

Without 0X in front of the values, parseInt() will consider the string to be a base 10 number. And the result is a NaN value.

Finally, the parseInt() function always return a whole number from any value you specify as its argument:

let parseA = parseInt("5.962");
console.log(parseA); // 5

let parseB = parseInt("32.07");
console.log(parseB); // 32

If you want a number with decimal points, you need to use the parseFloat() function instead of parseInt().

Consider the example below:

let parseA = parseFloat("5.962");
console.log(parseA); // 5.962

let parseB = parseFloat("21");
console.log(parseB); // 21

Now you’ve learned how to use the JavaScript parseInt() function. Great job! 😉

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

#javascript #string #function 

How to Use The Parseint() JavaScript Function
Hunter  Krajcik

Hunter Krajcik

1669196823

Create A String with All Lowercase Letters in JavaScript

JavaScript toLowerCase() method explained

Create a string with all lowercase letters in JavaScript with toLowerCase() method

The JavaScript toLowerCase() method is used to convert a string into its lowercase version.

The method can be called from any valid string value you may have in your source code.

Here’s an example of using the toLowerCase() method:

let str = "GOOD MORNING FROM MARS!";

console.log(str.toLowerCase());
// good morning from mars!

The toLowerCase() method returns a new value, so the original value is not affected.

You can use the toLowerCase() method to make a lowercase string except for the first letter with the help of the charAt() method:

function lowerCaseExceptFirstLetter(str) {
  return str.charAt(0) + str.substring(1).toLowerCase();
}

let str = "GOOD MORNING FROM MARS!";

console.log(lowerCaseExceptFirstLetter(str));
// Good morning from mars!

The method above only leaves the first letter of the sentence with an uppercase letter.

If you want to capitalize the first letter of every word, you need to create a function that uses split() to split the string into an array first.

Let’s name this function as lowerCaseWords() function:

function lowerCaseWords(str) {
  // 1. Create an array out of the string
  let strArray = str.split(" ");
}

Next, you use the map() method to iterate over the array.

Inside the map, use the same charAt() and toLowerCase() methods to convert the string to lowercase except for the first letter. Assign the returned values from the mapping operation back to the strArray:

function lowerCaseWords(str) {
  // 1. Create an array out of the string
  let strArray = str.split(" ");

  // 2. Lowercase the words except the first letter
  strArray = strArray.map((str) => {
    return lowerCaseExceptFirstLetter(str);
  });
}

Finally, call the join() method to put the array of words back into a single sentence string and return it from the function.

Here’s the full function code and its test result:

function lowerCaseExceptFirstLetter(str) {
  return str.charAt(0) + str.substring(1).toLowerCase();
}

function lowerCaseWords(str) {
  // 1. Create an array out of the string
  let strArray = str.split(" ");

  // 2. Lowercase the words except the first letter
  strArray = strArray.map((str) => {
    return lowerCaseExceptFirstLetter(str);
  });

  // 3. Put the array back into a string and return it
  return strArray.join(" ");
}

// Test the function
let str = "GOOD MORNING FROM MARS!";

console.log(lowerCaseWords(str));
// Good Morning From Mars!

Now you’ve learned how the JavaScript toLowerCase() method works and how it can be useful to convert strings into lowercase letters.

The toLowerCase() method is available from JavaScript ES1 version. It’s fully supported by all browsers today.

Feel free to use the code in this tutorial for your project. 😉

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

#javascript #string 

Create A String with All Lowercase Letters in JavaScript
Nigel  Uys

Nigel Uys

1669125600

How to format, insert Variables, Expressions To A String In JavaScript

Learn how to format and insert variables and expressions to a string in JavaScript

This tutorial will help you learn how to insert variables and expressions from your JavaScript code into a string.

JavaScript allows you to format a string with variables and expressions from your code in three ways:

  • Using string concatenation with + symbol
  • Using template literals with backticks (` `) symbol
  • Using a custom string you define yourself

Let’s learn how to format a string using the three techniques above, starting with string concatenation.

Format JavaScript string with concatenation

When used in JavaScript strings, a plus + symbol is treated as a concatenation operator that joins your variables and values as a string.

The code below shows how you can concatenate values together as a string:

let name = "Nathan";
let role = "Software Developer";

let aString = "Hello! My name is " + name + " and I'm a " + role;

console.log(aString);
// "Hello! My name is Nathan and I'm a Software Developer"

As you can see, the variable name and role are inserted into the string using the + symbol.

But using the + symbol can produce the wrong result if you’re using a more advanced format with expressions, such as number calculations and ternary conditionals.

For example, the following number expression produces the wrong output:

console.log("The sum of 5 + 2 is " + 5 + 2);
// "Sum of 5 + 2 is 52"

As you can see, adding the numbers 5 + 2 produces 52 instead of 7.

To produce the correct output, you need to wrap the expression using round brackets as follows:

console.log("The sum of 5 + 2 is " + (5 + 2));
// "The sum of 5 + 2 is 7"

Next, using ternary operators also produce the wrong result as follows:

let married = false;

console.log("You are " + married == true ? "married" : "single");
// "single"

Like with the numbers, you need to wrap the ternary operation in a round bracket as follows:

console.log("You are " + (married == true ? "married" : "single"));
// "You are single"

And that’s how you can insert variables and values using the string concatenation technique.

Since 2015, a new syntax called template literals was added to the JavaScript language. This new syntax improves JavaScript’s ability to embed expressions into a string.

Format JavaScript string with template literals

The template literals are used for creating multi-line strings and inserting expressions into strings.

Template literals are also called template strings because they are used for creating strings with placeholders.

Template literals use the backtick symbol ` as the delimiters.

Here’s an example of a template literal in action:

let name = "Nathan";
let role = "Software Developer";

let aString = `Hello! My name is ${name} and I'm a ${role}`;

console.log(aString);
// "Hello! My name is Nathan and I'm a Software Developer"

Note how the aString variable above starts with a backtick instead of a single or double quotes.

In a template string, you insert an expression into the string using the dollar sign and curly braces symbol (${}).

You can also include numbers and ternary operations inside the ${} symbol as shown below:

console.log(`The sum of 5 + 2 is ${5 + 2}`);
// "The sum of 5 + 2 is 7"

let married = false;

console.log(`You are ${married == true ? "married" : "single"}`);
// "You are single"

As you can see, it’s easier to format a string using template literals than string concatenations.

Since its release, the template literal has been the default technique used in formatting JavaScript strings.

Format JavaScript string with a custom function

In other programming languages like Python, the string has a format() method that you can use to format a string with expressions.

The code below shows how the Python format() method works:

name = "Nathan"
role = "Software Developer"
aString = "My name is {0}, I'm {1}".format(name, role)

print(aString)
# My name is Nathan, I'm Software Developer

In the example above, the {0} and {1} template is replaced with the expressions put in the format() function call.

Following the Python implementation, you can add a format() method to the JavaScript String prototype as follows:

if (!String.prototype.format) {
  String.prototype.format = function () {
    var args = arguments;
    return this.replace(/{(\d+)}/g, function (match, number) {
      return typeof args[number] != "undefined" ? args[number] : match;
    });
  };
}

The format() method above uses a regular expression to search and replace the template numbers like {0} and {1} with the arguments you pass into the method.

Once you’ve added the string method above, you can call it from any string you define in your code:

let name = "Nathan"
let role = "Software Developer"
let aString = "My name is {0}, I'm a {1}".format(name, role);

console.log(aString);
// My name is Nathan, I'm a Software Developer

In general, it’s not recommended to add a custom method to the prototype object unless you have a strong reason.

For most cases, using the template literal is enough to format a string with expressions and variables.

Now you’ve learned how to format a string with JavaScript in three different ways. Great job! 👍

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

#javascript #string 

How to format, insert Variables, Expressions To A String In JavaScript
Gordon  Taylor

Gordon Taylor

1668856339

Best 9 Ways You Can Convert A String to A Number Type with JavaScript

Learn how you can convert a string to a number type natively using JavaScript

Depending on the conditions you have in your project, there are 9 ways to convert a string type into a number type in JavaScript

When you want a rounded number out of the string, then you can use these functions and methods:

  • parseInt()
  • Math.round()
  • Math.floor()
  • Math.ceil()

When you want a number with floating points, then you can use these functions and operators:

  • Number()
  • parseFloat()
  • The unary + operator
  • The unary - operator
  • Implicit conversion with the minus, multiplication, division, or remainder operator

Let’s see an example of these functions in action next.

Create a rounded number from the string

The parseInt() function parses a value you passed as its argument and tries to return a number that represents that value.

When you pass a string into the function, it will return a whole number as shown below:

parseInt("23"); // 23

// parsing a floating number string:
parseInt("7.31"); // 7

// rounded down even when the floating number > .49
parseInt("7.91"); // 7

// String with no number representative
parseInt("a"); // NaN

Note that strings with floating numbers are always rounded down, even when the floating number is greater than .49.

You can use the Math.round() method to round the string with floating numbers up or down depending on the floating number’s value:

Math.round("2.17"); // 2

// rounded up when floating number >= .5
Math.round("2.5"); // 3

// rounded down when floating number < .5
Math.round("2.49"); // 2

To always round the floating number down, use the Math.floor() method:

Math.floor("2.17"); // 2

Math.floor("2.5"); // 2

Math.floor("2.49"); // 2

To always round the floating number up, use the Math.ceil() method:

Math.ceil("2.17"); // 3

Math.ceil("2.5"); // 3

Math.ceil("2.49"); // 3

And that’s how you create a rounded number when converting a string into a number.

Next, let’s learn how to convert a string into a number and preserve the floating points.

Create a decimal number from the string

Decimal numbers are numbers with floating points. The native Number() function in JavaScript will convert your string into its number representation without rounding the floating points:

Number("7"); // 7

Number("7.22"); // 7.22

Number("7.52"); // 7.52

Number("7.52.447"); // NaN

Next, the parseFloat() function is a native JavaScript function to return a floating-point number from a value.

The code below shows how the parseFloat() function works:

parseFloat("7"); // 7

parseFloat("7.52"); // 7.52

// still parse number in wrong format:

parseFloat("7.52.447"); // 7.52
parseFloat("7.52aabcs"); // 7.52

When encountering an incorrect number format, the parseFloat() function still tries to return a number that represents the string.

On the other hand, the Number() function immediately returns a NaN when the number format is unrecognized.

The Number() function is more strict than the parseFloat() function.

Besides these two functions, you can also convert a string of decimal numbers using the unary plus (+) and minus (-) operator.

The + operator evaluates the operand you added next to the operator and tries to return a number as shown below:

+"7.22"; // returns 7.22
+"777"; // returns 777

+"-52"; // -52

+"ab"; // NaN

The - operator evaluates the given operand and negates the number, creating a negative number in the process:

The code below shows how the - operator works:

-"7.22"; // -7.22
-"777"; // -777

// negative number string will return a positive number
-"-52"; // 52
-"-52.89"; // 52.89

-"ab"; // NaN

And that’s how the - operator can be used to convert a string into a number.

JavaScript implicit type conversion with minus / multiplication / division / remainder operator

JavaScript automatically converts a string into a number when you use an arithmetic operator except for the unary + operator.

Consider the following code examples:

"55" - 1; // 54

"5" * 2; // 10

"20" / 5; // 4

"100" % 6; // 4

"-7" - 3; // -10

When you use the + operator, JavaScript will concatenate the string and the number instead of converting the string.

In the following code examples, the expressions produce a string instead of a number:

// returns a string:

"50" + 1; // "501"
"3.2" + 1; // "32.1"

// returns a number:

Number("5.7") + 3; // 8.7
+"6.1" + 3; // 9.1

You need to manually convert the string into a number before using the + operator as shown above.

And that’s how you can convert a string into a number in JavaScript.

Depending on the requirements you have in your project, you can use one of the nine ways mentioned in this tutorial.

Thank you for reading. I hope this tutorial has been useful for you. 🙏

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

#javascript #string #number 

Best 9 Ways You Can Convert A String to A Number Type with JavaScript

How to Convert A String To A Boolean Value in PHP

See how you can convert a string to a boolean value in PHP

To convert string value to boolean value in PHP, you need to use the filter_var() function.

The filter_var() function can be used to validate whether a string is true or false depending on its value:

filter_var(
    mixed $value,
    int $filter = FILTER_DEFAULT,
    array|int $options = 0
): mixed

To convert a string to a boolean, you need to pass two parameters to the function:

  1. The string as $value
  2. FILTER_VALIDATE_BOOLEAN as the $filter argument

The FILTER_VALIDATE_BOOLEAN flag will return true for “1”, “true”, “on”, and “yes” string values. Otherwise, it returns false.

Here are some examples of converting strings to boolean values:

<?php
var_dump(filter_var("true", FILTER_VALIDATE_BOOLEAN));
var_dump(filter_var("false", FILTER_VALIDATE_BOOLEAN));
var_dump(filter_var("yes", FILTER_VALIDATE_BOOLEAN));
var_dump(filter_var("no", FILTER_VALIDATE_BOOLEAN));

The output of the code above will be:

bool(true)
bool(false)
bool(true)
bool(false)

As you can see, the filter_var() function returns boolean when you use the FILTER_VALIDATE_BOOLEAN flag.

And that’s how you convert a string to a boolean using PHP.

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

#php #string #boolean 

How to Convert A String To A Boolean Value in PHP

OpenSoundControl.jl: Open Sound Control for Julia

OSC.jl -- Implementation of the Open Sound Control Serialization Format

OSC.jl provides an implementation of the OSC binary format commonly used in networked control of musical applications. The code is based on a relatively straightforward translation of librtosc(https://github.com/fundamental/rtosc)

Sample Usage

i = Int32(          42         ); #integer
f = Float32(        0.25;      ); #float
s =                "string"       #string
b =                 s;            #blob
h = Int64(          -125;      ); #long integer
t = UInt64(         22412;     ); #timetag
d = Float64(        0.125;     ); #double
S =                 "Symbol"      #symbol
c = Char(           'J'        ); #character
r = Int32(          0x12345678 ); #RGBA
m = Array{UInt8,1}( [0x12,0x23,   #midi
                     0x34,0x45]);
#true
#false
#nil
#inf

msg = OscMsg("/dest", "[ifsbhtdScrmTFNI]", i,f,s,b,h,t,d,S,c,r,m);
show(msg)

This produces:

OSC Message to /dest
    Arguments:
    # 1 i:Int32 - 42
    # 2 f:Float32 - 0.25
    # 3 s:String - string
    # 4 b:Blob - Uint8[115 116 114 105 110 103]
    # 5 h:Int32 - -125
    # 6 t:Uint64 - 22412
    # 7 d:Float64 - 0.125
    # 8 S:Symbol - Symbol
    # 9 c:Char - J
    #10 r:RBG - 305419896
    #11 m:Midi - Uint8[18 35 52 69]
    #12 T: - true
    #13 F: - false
    #14 N:Nothing - nothing
    #15 I:Inf - nothing

Accessing the fields is done via the [] operator.

Networked Usage

Most of the usage is going to involve sending the OSC messages over UDP to another program. To do this, first start two julia instances. In the first one run

using Sockets
using OpenSoundControl
sock2 = UDPSocket()
bind(sock2, ip"127.0.0.1", 7777)
msg2 = OscMsg(recv(sock2))
show(msg2)

The first instance will now wait for the second to send an OSC message. To send the an OSC message, in the second window type.

using Sockets
using OpenSoundControl
sock1 = UDPSocket()
msg1 = OpenSoundControl.message("/hello world", "sSif", "strings", "symbols", Int32(234), Float32(2.3))
send(sock1, ip"127.0.0.1", 7777, msg1.data)

TODO

  • Port bundle message support from librtosc

Download Details:

Author: fundamental
Source Code: https://github.com/fundamental/OpenSoundControl.jl 
License: LGPL-3.0 license

#julia #open

OpenSoundControl.jl: Open Sound Control for Julia
Hunter  Krajcik

Hunter Krajcik

1665144426

Ota_string: Flutter Over The Air String

Flutter Over The Air String

Update String Over the air but free...

Installing

1. Get the package

Add this to your pubspec.yaml file:

dependencies:
  ota_string: ^0.0.1
  
dev_dependencies:
  ota_generator: ^0.0.1  

2. Install

Install with:

flutter pub get

How to use

Check README.md on ota_generator

Use this package as a library

Depend on it

Run this command:

With Dart:

 $ dart pub add ota_string

With Flutter:

 $ flutter pub add ota_string

This will add a line like this to your package's pubspec.yaml (and run an implicit dart pub get):

dependencies:
  ota_string: ^0.0.3

Alternatively, your editor might support dart pub get or flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:ota_string/ota_string.dart';

Download Details:

Author: Aldychris
Source Code: https://github.com/aldychris/ota_string/ 
License: GPL-3.0 license

#flutter #dart #string 

Ota_string: Flutter Over The Air String

Stringinterpolation.jl: Interpolation for Non-standard String Literals

StringInterpolation.jl

String interpolation is an awesome feature of Julia, but string interpolation for non-standard string literals is not automatic and requires significant boilerplate code to make it work.

This package simply ressurects an old Base method interp_parse and adds a macro @interpolate. For example:

julia> Pkg.clone("https://github.com/EricForgy/StringInterpolation.jl.git")
julia> using StringInterpolation
julia> x = "World"
julia> @interpolate "Hello \$x"
"Hello World"

Note the $ is escaped in the string we want to interpolate.

The intended use for this package is when building non-standard string literals. For example:

macro test_str(s)
    return quote
        str = @interpolate $s
        # Do what you want to do with interpolated string here.
        sprint(print,str)
    end
end

Example

The following non-standard string literal simply makes 3 copies of the interpolated string:

macro triple_str(s)
    return quote
        str = @interpolate $s
        sprint(print,str^3)
    end
end

Then, you can use the macro as follows:

julia> x = "World"; println(triple"Hello \$x\n")
Hello World
Hello World
Hello World

Download Details:

Author: EricForgy
Source Code: https://github.com/EricForgy/StringInterpolation.jl 
License: View license

#julia #string 

Stringinterpolation.jl: Interpolation for Non-standard String Literals

StringUtils.jl: String Utilities for Julia

StringUtils

The StringUtils package in a work-in-progress, where I am placing various improvements on the String functionality in Julia language.

Currently, it adds a Swift style string macro, u"...", which uses the Swift syntax for interpolation, i.e. \(expression). This means that you never have to worry about strings with the $ character in them, which is rather frequent in some applications. Also, Unicode sequences are represented as in Swift, i.e. as \u{hexdigits}, where there can be from 1 to 6 hex digits. This syntax eliminates having to worry about always outputting 4 or 8 hex digits, to prevent problems with 0-9,A-F,a-f characters immediately following. Finally, I have added four ways of representing characters in the literal string, \:emojiname:, \<latexname>, \&htmlname; and \N{UnicodeName}. This makes life a lot easier when you want to keep the text of a program in ASCII, and also to be able to write programs using those characters that might not even display correctly in their editor.

This now has some initial formatting capability, based on Tom Breloff's wonderful PR #10 to the JuliaIO/Formatting.jl package (by Dahua Lin and other contributors).

\%(arguments) is interpolated as a call to fmt(arguments). This is especially useful when defaults have been set for the type of the first argument.

fmt_default!{T}(::Type{T}, syms::Symbol...; kwargs...) sets the defaults for a particular type. fmt_default!(syms::Symbol...; kwargs...) sets the defaults for all types. Symbols that can currently be used are: :ljust or :left, :rjust or :right, :commas, :zpad or :zeropad, and :ipre or :prefix. reset!{T}(::Type{T}) resets the defaults for a particular type. defaultSpec(x) will return the defaults for the type of x, and defaultSpec{T}(::Type{T}) will return the defaults for the given type.

This also adds support for \%ccc(arguments), where ccc is one or more characters of a single C style format specification, which is interpolated as a call to cfmt("ccc", arguments).

I'm also experimenting with adding Python style syntax (as much as possible), as u"{pythonformat}"

Download Details:

Author: ScottPJones
Source Code: https://github.com/ScottPJones/StringUtils.jl 
License: View license

#julia #string #utils 

StringUtils.jl: String Utilities for Julia

Implement Improved String Literals with Swift-style Syntax

StringLiterals

The StringLiterals package is an attempt to bring a cleaner string literal syntax to Julia, as well as having an easier way of producing formatted strings, borrowing from both Python and C formatted printing syntax. It also adds support for using LaTex, Emoji, HTML, or Unicode entity names that are looked up at compile-time.

Currently, it adds a Swift style string macro, f"...", which uses the Swift syntax for interpolation, i.e. \(expression). This means that you never have to worry about strings with the $ character in them, which is rather frequent in some applications. Also, Unicode sequences are represented as in Swift, i.e. as \u{hexdigits}, where there can be from 1 to 6 hex digits. This syntax eliminates having to worry about always outputting 4 or 8 hex digits, to prevent problems with 0-9,A-F,a-f characters immediately following. Finally, I have added four ways of representing characters in the literal string, \:emojiname:, \<latexname>, \&htmlname; and \N{UnicodeName}. This makes life a lot easier when you want to keep the text of a program in ASCII, and also to be able to write programs using those characters that might not even display correctly in their editor.

It also adds a string macro that instead of building a string, can print the strings and interpolated values directly, without having to create a string out of all the parts. Finally, there are uppercase versions of the macros, which also supports the legacy sequences, $ for string interpolation, \x followed by 1 or 2 hex digits, \u followed by 1 to 4 hex digits, and \U followed by 1 to 8 hex digits.

This uses a fork of the https://github.com/JuliaIO/Formatting.jl package to provide formatting capability, as well as Tom Breloff's PR https://github.com/JuliaIO/Formatting.jl/pull/10, which provides the capability of using settable printing defaults based on the types of the argument. The formatting code has been extensively modified, see https://github.com/JuliaString/Format.jl.

\ can be followed by: 0, $, ", ', , a, b, e, f, n, r, t, u, v, N, %, (, <, {, : or &. In the legacy modes, x and U are also allowed after the \. Unlike standard Julia string literals, unsupported characters give an error (as in Swift).

\0 outputs a nul byte (0x00) (note: as in Swift, octal sequences are not supported, just the nul byte)

\a outputs the "alarm" or "bell" control code (0x07)

\b outputs the "backspace" control code (0x08)

\e outputs the "escape" control code (0x1b)

\f outputs the "formfeed" control code (0x0c)

\n outputs the "newline" or "linefeed" control code (0x0a)

\r outputs the "return" (carriage return) control code (0x0d)

\t outputs the "tab" control code (0x09)

\v outputs the "vertical tab" control code (0x0b)

\u{<hexdigits>} is used to represent a Unicode character, with 1-6 hex digits.

\< followed by a LaTeX entity name followed by > outputs that character or sequence if the name is valid.

\: followed by an Emoji name followed by : outputs that character or sequence (if a valid name)

\& followed by an HTML entity name followed by ; outputs that character or sequence (if a valid name)

\N{ followed by a Unicode entity name (case-insensitive!) followed by a } outputs that Unicode character (if a valid name)

\(expression) simply interpolates the value of the expression, the same as $(expression) in standard Julia string literals.

\%<ccc><formatcode>(arguments) is interpolated as a call to cfmt("<cccc><formatcode>",arguments), where <ccc><formatcode> is a C-style format string.

\%(arguments) is interpolated as a call to fmt(arguments). This is especially useful when defaults have been set for the type of the first argument.

fmt_default!{T}(::Type{T}, syms::Symbol...; kwargs...) sets the defaults for a particular type.

fmt_default!(syms::Symbol...; kwargs...) sets the defaults for all types.

Symbols that can currently be used are: :ljust or :left, :rjust or :right, :commas, :zpad or :zeropad, and :ipre or :prefix.

  • reset!{T}(::Type{T}) resets the defaults for a particular type.
  • defaultSpec(x) will return the defaults for the type of x, and
  • defaultSpec{T}(::Type{T}) will return the defaults for the given type.

There is currently support for Python style formatting, although that is a work-in-progress, and I am intending to improve the syntax to make it as close as possible to Python's 3.6 format strings. Currently, the syntax is \{<formatstring>}(expression), however I plan on changing it shortly to \{expression} (equivalent to pyfmt("", expression), and \{expression;formatstring} (equivalent to pyfmt("formatstring", expression).

Download Details:

Author: JuliaString
Source Code: https://github.com/JuliaString/StringLiterals.jl 
License: View license

#julia #string 

Implement Improved String Literals with Swift-style Syntax