Posted by: xSicKxBot - 09-19-2022, 11:34 AM - Forum: Python
- No Replies
How to Find the Longest String in a NumPy Array?
5/5 – (1 vote)
Python Longest String in NumPy Array
To find the longest string in a given NumPy array, say arr, you can use the max(arr, key=len) function that determines the maximum by comparing the length of the array elements using the len() function as a key for comparison.
import numpy as np arr = np.array(['Alice', 'Bob', 'Carl'])
print(max(arr, key=len))
# Alice
You can find more about the powerful max() function in our detailed blog tutorial:
To find the length of the longest string in a NumPy array arr, use the max(arr, key=len) function to obtain the string with the maximum length and then pass this max string into the len() function to obtain the number of characters of the max string.
len(max(arr, key=len))
Here’s a more detailed code example of a simple 1D NumPy Array:
import numpy as np arr = np.array(['Alice', 'Bob', 'Carl']) # Print Longest String:
print(max(arr, key=len))
# Alice # Print Length of Longest String
print(len(max(arr, key=len)))
# 5
Get Longest String from NumPy Axis (2D, Column or Row)
To get the longest string from a certain NumPy array axis (e.g., row or column), first use simple NumPy slicing and indexing to get that axis (e.g., arr[0, :] to get the first row) and pass it into the max() function with the key argument set to the length function like so: max(arr[0, :], key=len).
Here’s an example to get the longest string of the first row of a 2D array:
import numpy as np arr = np.array([['Alice', 'Bob', 'Carl'], ['Ann', 'Zoe', 'Leonard']]) print(max(arr[0, :], key=len))
# Alice
Here’s an example to get the longest string of the third column of a 2D array:
print(max(arr[:, 2], key=len))
# Leonard
You get the idea.
If you want to get the longest string from the whole NumPy array, not only from a column or row or axis, first flatten it and then pass the flattened array into the max() function using the key=len argument.
Welcome to Meow Meow Furrington, capital city of cats, home of the world's biggest ball of yarn...and hotbed of crime. You are Cuddles Nutterbutter, feline private investigator and owner of two perfectly normal-sized paws, the doctor said so. After agreeing to take on a last-minute case for the Chief of Police, you and your plucky assistant find yourselves investigating a murder that risks upsetting the careful balance between the city's two most powerful crime families: the Montameeuws and the Catulets.
Cuddles will need to use every skill he's learned - as well as his definitely-not-smaller-than-average paws - to poke, lick and talk his way through to the heart of the mystery...before some very dangerous cats decide to take matters into their own paws. Which, to clarify, are absolutely regular-sized.
Stretch your legs, clean your whiskers, and dive into Nine Noir Lives. Enjoy a "point-and-lick" comedy-noir adventure, full of humour, crazy characters, and intriguing locations. Solve challenging puzzles and answer the immortal question: how many things need to be licked to solve a murder in this town?
Posted by: xSicKxBot - 09-19-2022, 11:34 AM - Forum: Lounge
- No Replies
How To Get Six Free Syndicate Packs In Apex Legends Mobile
Apex Legends Mobile recently held a surprise weekend event that rewarded players with three free Loba Bootlegger Packs, a special kind of Syndicate Pack that usually can only be obtained via purchase with Syndicate Coins, the game's premium currency. These packs gave players free cosmetics from the premium Bootlegger cosmetic collection.
This event proved so popular that two more have since been announced, but this time, the prize has been doubled--players who participate in the Bootlegger Bonanza and Star Spectacle events will receive a total of three Loba Bootlegger Packs and three Rhapsody Digital Star Packs. Keep reading for a closer look at both of these events, instructions on how to participate, and a list of all the prizes you can earn by taking part.
Schedule
The events each last for three days and take place on separate weekends:
Posted by: xSicKxBot - 09-18-2022, 10:23 AM - Forum: Python
- No Replies
Combine Images Using Numpy
Rate this post
Summary: You can combine images represented in the form of Numpy arrays using the concatenate function of the Numpy library as np.concatenate((numpydata_1, numpydata_2), axis=1). This combines the images horizontally. Use syntax: np.concatenate((numpydata_1, numpydata_2), axis=0) to combine the images vertically.
Problem Formulation
Consider you have two images represented as Numpy arrays of pixels. How will you combine the two images represented in the form of Numpy pixel arrays?
Combining two images that are in the form of Numpy arrays will create a new Numpy array having pixels that will represent a new combined image formed by either concatenating the two images horizontally or vertically. Let’s understand this with the help of an example:
Given: Let’s say we have two different images as given below (Both images have similar dimensions) –
img_1.JPG img_2.JPG
When you convert them to Numpy arrays this is how you can represent the two images:
So, are you up for the challenge? Well! If it looks daunting – don’t worry. This tutorial will guide you through the techniques to solve the programming challenge. So, without further delay let us dive into the solution.
Prerequisite: To understand how the solutions to follow work it is essential to understand – “How to concatenate two Numpy arrays in Python.”
NumPy’s concatenate() method joins a sequence of arrays along an existing axis. The first couple of comma-separated array arguments are joined. If you use the axis argument, you can specify along which axis the arrays should be joined. For example, np.concatenate(a, b, axis=0) joins arrays along the first axis and np.concatenate(a, b, axis=None) joins the flattened arrays.
To learn more about concatenating arrays in Python, here’s a wonderful tutorial that will guide you through numerous methods of doing so: How to Concatenate Two NumPy Arrays?
Combine Images “Horizontally” with Numpy
Approach: The concatenate() method of the Numpy library allows you combine matrices of different images along different axes. To combine the two image arrays horizontally, you must specify the axis=1.
Code: Please go through the comments mentioned in the script in order to understand how each line of code works.
from PIL import Image
import numpy as np
# Reading the given images img_1 = Image.open('img_1.JPG')
img_2 = Image.open('img_2.JPG')
# Converting the two images into Numpy Arrays
numpydata_1 = np.asarray(img_1)
numpydata_2 = np.asarray(img_2)
# Combining the two images horizontally
horizontal = np.concatenate((numpydata_1, numpydata_2), axis=1)
# Display the horizontally combined image as a Numpy Array
print(horizontal)
# converting the combined image in the Numpy Array form to an image format
data = Image.fromarray(horizontal)
# Saving the combined image
data.save('combined_pic.png')
Here’s how the horizontally combined image looks like when saved to a file:
Wonderful! Isn’t it?
Combine Images “Vertically” with Numpy
In the previous solution, we combined the images horizontally. In this soution you will learn how to combine two images represented in the form of Numpy arrays vertically.
Approach: The idea is quite similar to the previous solution with the only difference in the axis parameter of the concatenate() method. To combine the two image arrays vertically, you must specify the axis=0.
Code:
from PIL import Image
import numpy as np
# Reading the given images
img_1 = Image.open('img_1.JPG')
img_2 = Image.open('img_2.JPG')
# Converting the two images into Numpy Arrays
numpydata_1 = np.asarray(img_1)
numpydata_2 = np.asarray(img_2)
# Combining the two images horizontally
vertical = np.concatenate((numpydata_1, numpydata_2), axis=0)
# Display the vertically combined image as a Numpy Array
print(vertical)
# converting the combined image in the Numpy Array form to an image format
data = Image.fromarray(vertical)
# Saving the combined image
data.save('combined_pic.png')
Phew! That was some coding challenge! I hope you can now successfully combine images given as Numpy arrays in both dimensions – horizontally as well as vertically. With that we come to the end of this tutorial. Please subscribe and stay tuned for more interesting tutorials and solutions in the future.
Welcome to Meow Meow Furrington, capital city of cats, home of the world's biggest ball of yarn...and hotbed of crime. You are Cuddles Nutterbutter, feline private investigator and owner of two perfectly normal-sized paws, the doctor said so.
After agreeing to take on a last-minute case for the Chief of Police, you and your plucky assistant find yourselves investigating a murder that risks upsetting the careful balance between the city's two most powerful crime families: the Montameeuws and the Catulets.
Cuddles will need to use every skill he's learned - as well as his definitely-not-smaller-than-average paws - to poke, lick and talk his way through to the heart of the mystery...before some very dangerous cats decide to take matters into their own paws. Which, to clarify, are absolutely regular-sized.
Stretch your legs, clean your whiskers, and dive into Nine Noir Lives. Enjoy a "point-and-lick" comedy-noir adventure, full of humour, crazy characters, and intriguing locations. Solve challenging puzzles and answer the immortal question: how many things need to be licked to solve a murder in this town?
Posted by: xSicKxBot - 09-18-2022, 10:22 AM - Forum: Lounge
- No Replies
CoD: Warzone 2.0 Overhauls The Gulag -- Here's How It Works
The sequel to Call of Duty: Warzone was officially revealed during Call of Duty Next on September 15, featuring the brand-new Al Mazrah map and a reinvented Gulag. Here we highlight everything we learned about Warzone 2.0's updated Gulag experience.
The Gulag, Warzone's home for second chances, was originally a 1v1 arena for eliminated players to go head-to-head for the chance to return to the match. The arena itself received a few different map layouts since the original Gulag Showers arena was introduced with the launch of Verdansk, but now the rules are completely changing for Warzone 2.0.
Al Mazrah's Gulag is no longer a 1v1 arena, and eliminated players will be transported to a larger Gulag, which is set at a prison's live fire training complex. This is a multi-level arena played out in 2v2 matches, so players are temporarily paired up with another eliminated player. Players no longer spawn into the fight with a gun in hand. Everyone spawns in with their fists, weapons must now be looted, and the surviving duo will return to the match. There will be proximity chat for Al Mazrah, so players can communicate with their temporary duo partner.
Posted by: xSicKxBot - 09-17-2022, 09:33 AM - Forum: Python
- No Replies
Solidity Example – Safe Remote Purchase
5/5 – (1 vote)
This article continues on the Solidity Smart Contract Examples series, which implements a simple, but the useful process of safe remote purchase.
Here, we’re walking through an example of a blind auction (docs).
We’ll first lay out the entire smart contract example without the comments for readability and development purposes.
Then we’ll dissect it part by part, analyze it and explain it.
Following this path, we’ll get a hands-on experience with smart contracts, as well as good practices in coding, understanding, and debugging smart contracts.
Smart Contract – Safe Remote Purchase
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.4;
contract Purchase { uint public value; address payable public seller; address payable public buyer; enum State { Created, Locked, Release, Inactive } State public state; modifier condition(bool condition_) { require(condition_); _; } error OnlyBuyer(); error OnlySeller(); error InvalidState(); error ValueNotEven(); modifier onlyBuyer() { if (msg.sender != buyer) revert OnlyBuyer(); _; } modifier onlySeller() { if (msg.sender != seller) revert OnlySeller(); _; } modifier inState(State state_) { if (state != state_) revert InvalidState(); _; } event Aborted(); event PurchaseConfirmed(); event ItemReceived(); event SellerRefunded(); constructor() payable { seller = payable(msg.sender); value = msg.value / 2; if ((2 * value) != msg.value) revert ValueNotEven(); } function abort() external onlySeller inState(State.Created) { emit Aborted(); state = State.Inactive; seller.transfer(address(this).balance); } function confirmPurchase() external inState(State.Created) condition(msg.value == (2 * value)) payable { emit PurchaseConfirmed(); buyer = payable(msg.sender); state = State.Locked; } function confirmReceived() external onlyBuyer inState(State.Locked) { emit ItemReceived(); state = State.Release; buyer.transfer(value); } function refundSeller() external onlySeller inState(State.Release) { emit SellerRefunded(); state = State.Inactive; seller.transfer(3 * value); }
}
The state variables for recording the value, seller, and buyer addresses.
uint public value; address payable public seller; address payable public buyer;
For the first time, we’re introducing the enum data structure that symbolically defines the four possible states of our contract. The states are internally indexed from 0 to enum_length - 1.
enum State { Created, Locked, Release, Inactive }
The variable state keeps track of the current state. Our contract starts by default in the created state and can transition to the Locked, Release, and Inactive state.
State public state;
The condition modifier guards a function against executing without previously satisfying the condition, i.e. an expression given alongside the function definition.
The constructor is declared as payable, meaning that the contract deployment (synonyms creation, instantiation) requires sending a value (msg.value) with the contract-creating transaction.
constructor() payable {
The seller state variable is set to msg.sender address, cast (converted) to payable.
seller = payable(msg.sender);
The value state variable is set to half the msg.value, because both the seller and the buyer have to put twice the value of the item being sold/bought into the contract as an escrow agreement.
Info: “Escrow is a legal arrangement in which a third party temporarily holds money or property until a particular condition has been met (such as the fulfillment of a purchase agreement).” (source)
In our case, our escrow is our smart contract.
value = msg.value / 2;
If the value is not equally divided, i.e. the msg.value is not an even number, the function will terminate. Since the seller will always
if ((2 * value) != msg.value) revert ValueNotEven(); }
Aborting the remote safe purchase is allowed only in the Created state and only by the seller.
The external keyword makes the function callable only by other accounts / smart contracts. From the business perspective, only the seller can call the abort() function and only before the buyer decides to purchase, i.e. before the contract enters the Locked state.
function abort() external onlySeller inState(State.Created) {
Emits the Aborted event, the contract state transitions to inactive, and the balance is transferred to the seller.
emit Aborted(); state = State.Inactive;
Note: “Prior to version 0.5.0, Solidity allowed address members to be accessed by a contract instance, for example, this.balance. This is now forbidden and an explicit conversion to address must be done: address(this).balance.” (docs).
In other words, this keyword lets us access the contract’s inherited members.
Every contract inherits its members from the address type and can access these members via address(this).<a member> (docs).
seller.transfer(address(this).balance); }
The confirmPurchase() function is available for execution only in the Created state.
It enforces the rule that a msg.value must be twice the value of the purchase.
The confirmPurchase() function is also declared as payable, meaning the caller, i.e. the buyer has to send the currency (msg.value) with the function call.
The eventPurchaseConfirmed() is emitted to mark the purchase confirmation.
emit PurchaseConfirmed();
The msg.sender value is cast to payable and assigned to the buyer variable.
Info: Addresses are non-payable by design to prevent accidental payments; that’s why we have to cast an address to a payable before being able to transfer a payment.
buyer = payable(msg.sender);
The state is set to Locked as seller and buyer entered the contract, i.e., our digital version of an escrow agreement.
state = State.Locked; }
The confirmReceived() function is available for execution only in the Locked state, and only to the buyer.
Since the buyer deposited twice the value amount and withdrew only a single value amount, the second value amount remains on the contract balance with the seller’s deposit.
function confirmReceived() external onlyBuyer inState(State.Locked) {
Emits the ItemReceived() event.
emit ItemReceived();
Changes the state to Release.
state = State.Release;
Transfers the deposit to the buyer.
buyer.transfer(value); }
The refundSeller() function is available for execution only in the Release state, and only to the seller.
Since the seller deposited twice the value amount and earned a single value amount from the purchase, the contract transfers three value amounts from the contract balance to the seller.
function refundSeller() external onlySeller inState(State.Release) {
Emits the SellerRefunded() event.
emit SellerRefunded();
Changes the state to Inactive.
state = State.Inactive;
Transfers the deposit of two value amounts and the one earned value amount to the seller.
seller.transfer(3 * value); }
}
Our smart contract example of a safe remote purchase is a nice and simple example that demonstrates how a purchase may be conducted on the Ethereum blockchain network.
The safe remote purchase example shows two parties, a seller and a buyer, who both enter a trading relationship with their deposits to the contract balance.
Each deposit amounts to twice the value of the purchase, meaning that the contract balance will hold four times the purchase value at its highest point, i.e. in the Locked state.
The height of deposits is intended to stimulate the resolution of any possible disputes between the parties, because otherwise, their deposits will stay locked and unavailable in the contract balance.
When the buyer confirms that he received the goods he purchased, the contract will transition to the Release state, and the purchase value will be released to the buyer.
The seller can now withdraw his earned purchase value with the deposit, the contract balance drops to 0 Wei, the contract transitions to the Inactive state, and the safe remote purchase concludes with execution.
The Contract Arguments
This section contains additional information for running the contract. We should expect that our example accounts may change with each refresh/reload of Remix.
Our contract creation argument is the deposit (twice the purchase value). We’ll assume the purchase value to be 5 Wei, making the contract creation argument very simple:
10
Contract Test Scenario
Account 0x5B38Da6a701c568545dCfcB03FcB875f56beddC4 deploys the contract with a deposit of 10 Wei, effectively becoming a seller.
Account 0xAb8483F64d9C6d1EcF9b849Ae677dD3315835cb2 confirms the purchase by calling the confirmPurchase() function and enters the trade with a deposit of 10 Wei, effectively becoming a buyer.
The buyer confirms receiving the order by calling the confirmReceived() function.
The seller concludes the trade by calling the refundSeller() function.
Conclusion
We continued our smart contract example series with this article that implements a safe remote purchase.
First, we laid out clean source code (without any comments) for readability purposes.
Second, we dissected the code, analyzed it, and explained each possibly non-trivial segment.
Posted by: xSicKxBot - 09-17-2022, 09:33 AM - Forum: Lounge
- No Replies
Today's Wordle Answer (#454) - September 16, 2022
There's no better way to end the week than by getting the Wordle correct. If you're here, then you might be struggling to accomplish that goal. Luckily for you, we're here to make sure that you end the week with a bang and continue your streak into the weekend. Of course, it might prove difficult today, as the answer to the September 16 Wordle is quite tricky. We wouldn't be surprised if players didn't even know the answer was a word itself once they see it. If you haven't started the Wordle yet, though, you can check out our list of recommended starting words to give yourself an advantage before you've begun.
However, if you're a few guesses deep, then it might be time to seek some helpful advice. We have exactly that just below. There are two hints that should help players at least come up with guesses for today's puzzle on September 16. We will also spell out the full answer further down in the guide if players simply want to escape today unscathed with no trouble.
Today's Wordle Answer - September 16, 2022
We'll begin with two hints that directly relate to the Wordle answer, but won't immediately give the word away.
When everyday Londoners mysteriously turn into vicious killers, only the circus' lineup of Strongmen, Fire Blowers, Clowns and other performers possess the unique talents necessary to save the city.
Circus Electrique is part story-driven RPG, part tactics, part circus management, and completely enthralling - all with a steampunk twist.
Through tactical turn-based battles, these unlikely heroes face Bobbies, British Sailors gone bad, aggressive Posh Girls, and other Victorian-era archetypes stand in their way - not to mention the occasional menacing Mime or Robobear.
The game's innovative Devotion morale system affects characters' performance not only in battles, but also for actual circus shows, dutifully managed between heroic jaunts through six sprawling districts.