text stringlengths 1 2.12k | source dict |
|---|---|
java, functional-programming
currentPartition is scoped incorrectly. It is only used in tryAdvance, and does not persist beyond a single call. It should be moved into that method. There is also no value in setting it to null.
The while loop in tryAdvance is technically correct, but it is harder on readers to understand the important bit is the side effect of the tryAdvance call. Strongly consider rewriting it to just repeatedly call tryAdvance. This is very easy to read and should be highly performant. If, later, performance testing shows this is a bottleneck (it won't), put the tryAdvance call into the while block and break if the boolean comes back false.
Since you know the size of the partition, you can presize the ArrayList. This will usually not matter, but in some cases it might be somewhat more performant, and there's no readability impact. Note that you may still see one resize depending on the JDK's implementation.
PartitionSpliterator's size check calls the variable size, but the parameter name is partitionSize.
PartitionSpliterator should be private and final.
By convention, public members appear before private members in a class, and also methods appear before nested classes.
Partitioner is not designed for extension and should be final.
Partitioner is not designed to be instantiated, and should have a private constructor to prevent instantiation. (By convention, constructors appear before other methods, even if the constructor is private and the method is public).
The first argument (est) to super in PartitionSpliterator() is very hard to read and also incorrect. If the passed-in spliterator returns MAX_VALUE, you will assign a very large and probably very bad estimate. Either use MAX_VALUE always here, or add a private static method which correctly computes the estimate.
Then note that it only needs an estimated value, and being off by 1 is fine. Just divide the sizes and add 1. This will be right in every case except where they divide evenly, in which case it will be 1 too large. | {
"domain": "codereview.stackexchange",
"id": 43199,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, functional-programming",
"url": null
} |
java, functional-programming
If you made all these changes, your code might look more like:
public final class Partitioner { | {
"domain": "codereview.stackexchange",
"id": 43199,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, functional-programming",
"url": null
} |
java, functional-programming
private Partitioner() {}
public static <V> Stream<List<V>> partition(final Stream<V> values, final int size) {
if (size < 1) {
throw new IllegalArgumentException("Size must be a positive integer");
}
return StreamSupport.stream(
new PartitionSpliterator<>(values.spliterator(), size),
values.isParallel()
);
}
private static final class PartitionSpliterator<T> extends Spliterators.AbstractSpliterator<List<T>> {
private final Spliterator<T> values;
private final int partitionSize;
public PartitionSpliterator(final Spliterator<T> values, final int partitionSize) {
super(computeEstimatedSize(values.estimateSize(), partitionSize),
ORDERED | IMMUTABLE | SIZED | SUBSIZED
);
if (partitionSize < 1) {
throw new IllegalArgumentException("Size must be a positive integer");
}
this.values = values;
this.partitionSize = partitionSize;
}
@Override
public boolean tryAdvance(Consumer<? super List<T>> action) {
List<T> currentPartition = new ArrayList<>(partitionSize);
while (currentPartition.size() < partitionSize) {
values.tryAdvance(currentPartition::add);
/*
boolean addedValue = values.tryAdvance(currentPartition::add));
if (!addedValue) {
break;
}
*/
}
if (currentPartition.isEmpty()) {
return false;
} | {
"domain": "codereview.stackexchange",
"id": 43199,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, functional-programming",
"url": null
} |
java, functional-programming
if (currentPartition.isEmpty()) {
return false;
}
action.accept(currentPartition);
return true;
}
private static long computeEstimatedSize(long estimatedValuesSize, int partitionSize) {
if (estimatedValuesSize == Long.MAX_VALUE) {
return Long.MAX_VALUE;
}
return (estimatedValuesSize / partitionSize) + 1;
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43199,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "java, functional-programming",
"url": null
} |
c#, object-oriented, unit-testing, comparative-review, abstract-factory
Title: A refactored payment service, handling several payment schemes
Question: I was asked to refactor a class, to make it adhere to SOLID principles, with testability and readability. I thought I had done a decent job, only my feedback was:
a) Unnecessary introduction of AccountExists() method [I thought it increased readability]
b) Breach of SOLID principles using "switch", "new" keywords
c) Backward compatibility not maintained [I was told I should not change the method signature of the MakePayment method]
Here is my refactored code:
I've left out most of the interface definitions because they are obvious, all methods implemented are defined on the interface:
public class NewPaymentService : IPaymentService
{
private readonly IAccountDataStore _accountDataStore;
private readonly IPaymentValidatorFactory _paymentValidatorFactory;
public NewPaymentService(
IAccountDataStore accountDataStore,
IPaymentValidatorFactory paymentValidatorFactory)
{
_accountDataStore = accountDataStore;
_paymentValidatorFactory = paymentValidatorFactory;
}
public MakePaymentResult MakePayment(MakePaymentRequest request)
{
if (!_accountDataStore.AccountExists(request.DebtorAccountNumber))
{
return new MakePaymentResult()
{
Success = false,
FailureReason = "Account does not exist"
};
}
var account = _accountDataStore.GetAccount(request.DebtorAccountNumber);
var paymentValidator = _paymentValidatorFactory.GetPaymentValidator(request.PaymentScheme);
bool isValid = paymentValidator.ValidatePayment(request, account);
if (!isValid)
{
return new MakePaymentResult()
{
Success = false,
FailureReason = "Payment is invalid"
};
}
account.Balance -= request.Amount;
_accountDataStore.UpdateAccount(account); | {
"domain": "codereview.stackexchange",
"id": 43200,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, unit-testing, comparative-review, abstract-factory",
"url": null
} |
c#, object-oriented, unit-testing, comparative-review, abstract-factory
account.Balance -= request.Amount;
_accountDataStore.UpdateAccount(account);
return new MakePaymentResult()
{
Success = true
};
}
}
public class PaymentValidatorFactory : IPaymentValidatorFactory
{
public IPaymentValidator GetPaymentValidator(PaymentScheme paymentScheme)
{
switch (paymentScheme)
{
case PaymentScheme.Bacs:
return new BacsPaymentValidator();
case PaymentScheme.FasterPayments:
return new FasterPaymentValidator();
case PaymentScheme.Chaps:
return new ChapsPaymentValidator();
default:
throw new ArgumentException($"No payment validator available for {paymentScheme}");
}
}
}
public class FasterPaymentValidator : IPaymentValidator
{
public bool ValidatePayment(MakePaymentRequest request, Account account)
{
if (!account.AllowedPaymentSchemes.HasFlag(AllowedPaymentSchemes.FasterPayments))
{
return false;
}
if (account.Balance < request.Amount)
{
return false;
}
return true;
}
}
public class AccountDataStore : IAccountDataStore
{
public bool AccountExists(string accountNumber)
{
throw new System.NotImplementedException();
}
public Account GetAccount(string accountNumber)
{
// Access database to retrieve account, code removed for brevity
return new Account();
}
public void UpdateAccount(Account account)
{
// Update account in database, code removed for brevity
}
}
public class BackupAccountDataStore : IAccountDataStore
{
public bool AccountExists(string accountNumber)
{
throw new System.NotImplementedException();
} | {
"domain": "codereview.stackexchange",
"id": 43200,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, unit-testing, comparative-review, abstract-factory",
"url": null
} |
c#, object-oriented, unit-testing, comparative-review, abstract-factory
public Account GetAccount(string accountNumber)
{
// Access backup data base to retrieve account, code removed for brevity
return new Account();
}
public void UpdateAccount(Account account)
{
// Update account in backup database, code removed for brevity
}
}
Here is the old method I was asked to refactor:
public class OldPaymentService : IPaymentService
{
public MakePaymentResult MakePayment(MakePaymentRequest request)
{
var dataStoreType = ConfigurationManager.AppSettings["DataStoreType"];
Account account = null;
if (dataStoreType == "Backup")
{
var accountDataStore = new BackupAccountDataStore();
account = accountDataStore.GetAccount(request.DebtorAccountNumber);
}
else
{
var accountDataStore = new AccountDataStore();
account = accountDataStore.GetAccount(request.DebtorAccountNumber);
}
var result = new MakePaymentResult();
switch (request.PaymentScheme)
{
case PaymentScheme.Bacs:
if (account == null)
{
result.Success = false;
}
else if (!account.AllowedPaymentSchemes.HasFlag(AllowedPaymentSchemes.Bacs))
{
result.Success = false;
}
break;
case PaymentScheme.FasterPayments:
if (account == null)
{
result.Success = false;
}
else if (!account.AllowedPaymentSchemes.HasFlag(AllowedPaymentSchemes.FasterPayments))
{
result.Success = false;
}
else if (account.Balance < request.Amount)
{
result.Success = false;
}
break; | {
"domain": "codereview.stackexchange",
"id": 43200,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, unit-testing, comparative-review, abstract-factory",
"url": null
} |
c#, object-oriented, unit-testing, comparative-review, abstract-factory
case PaymentScheme.Chaps:
if (account == null)
{
result.Success = false;
}
else if (!account.AllowedPaymentSchemes.HasFlag(AllowedPaymentSchemes.Chaps))
{
result.Success = false;
}
else if (account.Status != AccountStatus.Live)
{
result.Success = false;
}
break;
}
if (result.Success)
{
account.Balance -= request.Amount;
if (dataStoreType == "Backup")
{
var accountDataStore = new BackupAccountDataStore();
accountDataStore.UpdateAccount(account);
}
else
{
var accountDataStore = new AccountDataStore();
accountDataStore.UpdateAccount(account);
}
}
return result;
}
}
public class AccountDataStore
{
public Account GetAccount(string accountNumber)
{
// Access database to retrieve account, code removed for brevity
return new Account();
}
public void UpdateAccount(Account account)
{
// Update account in database, code removed for brevity
}
}
public class BackupAccountDataStore
{
public Account GetAccount(string accountNumber)
{
// Access backup data base to retrieve account, code removed for brevity
return new Account();
}
public void UpdateAccount(Account account)
{
// Update account in backup database, code removed for brevity
}
} | {
"domain": "codereview.stackexchange",
"id": 43200,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, unit-testing, comparative-review, abstract-factory",
"url": null
} |
c#, object-oriented, unit-testing, comparative-review, abstract-factory
I cannot understand how the feedback was so critical. AccountExists(), it may be an extra database call, but it is better than returning null, which the reader has to assume means that the account doesn't exist.
I inverted the dependencies so that IAccountDataStore type could be defined in a configuration startup class that does the DI, rather than having to check the app settings in the method.
I can't see how using 'new' to instantiate a DTO (MakePaymentResult) is a violation of SOLID, not using 'new' is meant to apply to behaviour implementations. And they said not to change the signature, how else can you return a MakePaymentResult?!
I used switch in a Factory class to get the right IPaymentValidator. That's the only place it was used, and I thought a Factory class was exactly the kind of place where you'd convert an enum to an implementation, for using the strategy pattern.
Can you give me any feedback on the feedback? What have I missed so badly?
Answer: Overall I agree with you, not the review you've been given. I think the sole exception here is their feedback on your AccountExists introduction.
I cannot understand how the feedback was so critical. AccountExists(), it may be an extra database call, but it is better than returning null, which the reader has to assume means that the account doesn't exist. | {
"domain": "codereview.stackexchange",
"id": 43200,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, unit-testing, comparative-review, abstract-factory",
"url": null
} |
c#, object-oriented, unit-testing, comparative-review, abstract-factory
I get your reasoning but I don't agree that the extra call was justified here. Good practice is a guideline, and sometimes you have to make reasonable compromises for ulterior reasons such as performance. Doubling the amount of database calls is a step in the wrong direction here.
While there is much to say about null and putting whether you do/don't like it aside, a "return it if it exists" which returns null is generally considered to be a valid approach. If it is contextually clear that a null is an expected possible outcome, this isn't something you have to particularly avoid.
You're also not really improving the consumer's handling of the code. In either case, their logic remains:
if(/* not exists */)
{
/* return failure */
}
You've changed how you confirm the existence, but you haven't really changed how consumers will use your datastore.
As an alternative, you could change your approach to a bool TryGetAccount(string accountNumber, out Account account). This is more explicitly telling the consumer that there may not be an account (hence "try"), and while you'd still be returning null if there isn't one, the consumer doesn't really have to actively perform a null check anymore.
I also want to point out that an "entity exists" type of method is perfectly fine to implement when there are cases where you need to know if something exists but have no interest in fetching it afterwards anyway. In this case, it would be a single database call either way, and AccountExists would indeed be more descriptive than a GetAccount call with an explicit null check.
I inverted the dependencies so that IAccountDataStore type could be defined in a configuration startup class that does the DI, rather than having to check the app settings in the method. | {
"domain": "codereview.stackexchange",
"id": 43200,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, unit-testing, comparative-review, abstract-factory",
"url": null
} |
c#, object-oriented, unit-testing, comparative-review, abstract-factory
Your approach is good, and for the right reasons. No further comment needed.
Tangential aside: "inverted dependencies" are something different. This is not your fault, as Dependency Inversion/DI is not a great name. "Dependency Inversion" is very easy to mistake for inverted dependencies. DI (i.e. Dependency Inversion) is also very easy to mistake for Dependency Injection (also labeled DI). While these two concepts are often used at the same time, they are different.
This is why a lot of people have started referring to Dependency Inversion (DI) as Inversion of Control (IoC), to avoid the ambiguity.
I can't see how using 'new' to instantiate a DTO (MakePaymentResult) is a violation of SOLID, not using 'new' is meant to apply to behaviour implementations. And they said not to change the signature, how else can you return a MakePaymentResult?!
This seems to be a mistake on the reviewer's part where they've misapplied the advice for avoiding new for a class' dependencies (i.e. because of IoC) and ended up telling you to avoid new to instantiate a result object. They're wrong, you're right.
I'm also not sure what they mean with "not changing the signature" since the old version also returned a MakePaymentResult.
I used switch in a Factory class to get the right IPaymentValidator. That's the only place it was used, and I thought a Factory class was exactly the kind of place where you'd convert an enum to an implementation, for using the strategy pattern. | {
"domain": "codereview.stackexchange",
"id": 43200,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, unit-testing, comparative-review, abstract-factory",
"url": null
} |
c#, object-oriented, unit-testing, comparative-review, abstract-factory
Note: There are a few variations on factory implementations. I'm only focusing on the one you're using here.
A factory is a good way to abstract the instantiation process, whether it is based on an enum or something else. It is not the only way, but it is the most straightforward way to abstract it.
I agree with your approach here, with one potential caveat: the enum is found in MakePaymentRequest request. This might suggest that you could've made the decision on what payment validator to use at an earlier stage (still using a factory), and then you could've injected the validator itself (instead of the factory) into the NewPaymentService instance. But this is highly contextual and I can't definitively tell you what makes the most sense for your codebase.
One tiny thing I would've done differently here is to also introduce a secondary interface to account for the concrete types of payment validators, i.e.:
public interface IPaymentValidator { /* as is */ }
public interface IFasterPaymentValidator : IPaymentValidator {}
public class FasterPaymentValidator : IFasterPaymentValidator {}
public interface IBacsPaymentValidator : IPaymentValidator {}
public class BacsPaymentValidator : IBacsPaymentValidator {}
The reason for this is testability and mockability. This enables your test logic to also mock a specific kind of validator. This can be useful in cases where other services might use a specific validator directly instead of delegating the choice of what validator to use to the factory.
However, this is again contextual. If all your usages of payment validator always delegate this decision to the factory, then the IPaymentValidator could suffice here. I tend to err on the side of implementing the extra interface anyway so I can be prepared for the future, but YAGNI might apply. | {
"domain": "codereview.stackexchange",
"id": 43200,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, object-oriented, unit-testing, comparative-review, abstract-factory",
"url": null
} |
programming-challenge, haskell
Title: Haskell solution to Day 2 problem of Advent of Code '21
Question: I won't restate the problem in full, but in a nutshell you have to parse a file with a "direction" and a "magnitude", for instance:
forward 8
forward 3
down 8
down 2
up 1 | {
"domain": "codereview.stackexchange",
"id": 43201,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, haskell",
"url": null
} |
programming-challenge, haskell
forward affects your horizontal position and up and down your vertical position. There are no other directions.
At the end, you're asked to multiply your final coordinates.
And this is my solution. It finds the right solution, but can it be improved?
Anything that screams "not idiomatic Haskell"?
I'm not fond of the toTuple function... but I had no idea how to do parse them better.
data Direction = Up | Down | Forward
instance Show Direction where
show Up = "up"
show Down = "down"
show Forward = "forward"
instance Read Direction where
readsPrec _ "up" = [(Up, "")]
readsPrec _ "down" = [(Down, "")]
readsPrec _ "forward" = [(Forward, "")]
type HorizontalPosition = Int
type VerticalPosition = Int | {
"domain": "codereview.stackexchange",
"id": 43201,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, haskell",
"url": null
} |
programming-challenge, haskell
data Position = Position {
hPos :: HorizontalPosition,
vPos :: VerticalPosition }
deriving Show
move :: Position -> Direction -> Int -> Position
move p Up n = Position (hPos p) (vPos p - n)
move p Down n = Position (hPos p) (vPos p + n)
move p Forward n = Position (hPos p + n) (vPos p)
toTuple :: [String] -> (Direction, Int)
toTuple [d, n] = (read d :: Direction, read n :: Int)
main = do
content <- readFile "input02"
let moves = map (toTuple . words) $ lines content
position = foldl (\p (d, n) -> move p d n) (Position 0 0) moves
putStrLn $ show $ hPos position * vPos position | {
"domain": "codereview.stackexchange",
"id": 43201,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, haskell",
"url": null
} |
programming-challenge, haskell
Answer:
The general preference is for Show/Read instances that produce and parse (text that looks like) Haskell code. The expectation is that you should be able to paste the result of show x into code and get the same value out. That's to say: I don't like how you define a "weird" Read Direction instance. Also note that it "requires" you to define a compatible Show, which simply isn't contributing to solving the problem. Just define a freestanding parser.
readDirection :: String -> Maybe Direction
readDirection "up" = Just Up
readDirection "down" = Just Down
readDirection "forward" = Just Forward
readDirection _ = Nothing
Using two different type aliases for the components of Position is pointless, since they are constrained to be the same by move, and you're also forced to have "bare" Int in move and direction. If you want an alias, make one that can be used in all the parts that are "connected" (so that a change to the alias doesn't immediately break the program.)
type Coordinate = Int
-- see note about foldl later; using foldl' does almost nothing for a record unless it has strict fields
data Position = Position { hPos :: !Coordinate, vPos :: !Coordinate }
You may as well define
data Command = Command { commandDirection :: Direction, commandDistance :: Coordinate }
move :: Command -> Position -> Position -- writing it this way allows thinking of move :: Command -> (Position -> Position)
move (Command Up n) p = p { vPos = vPos p - n } -- record update syntax is a thing!
move (Command Down n) p = p { vPos = vPos p + n }
move (Command Forward n) p = p { hPos = hPos p + n }
instead of using a tuple/two separate arguments. (This also removes the need to clumsily adapt between those two representations.) | {
"domain": "codereview.stackexchange",
"id": 43201,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, haskell",
"url": null
} |
programming-challenge, haskell
You can now use the monadic/applicative nature of Maybe to define a parseLine nicely, instead of toTuple. Note that we should avoid runtime errors on invalid input (so no partial patterns allowed and no read allowed).
parseLine :: String -> Maybe Command
parseLine line = do
[dir, n] <- return $ words line -- partial match left of <- in Maybe simply short circuits to Nothing instead of erroring
Command <$> readDirection dir <*> readMaybe n -- read as "'Command (readDirection dir) (readMaybe n)' but with something funky going on"; in this case "something funky" is "maybe failing over to Nothing"
I would recommend just taking input from stdin instead of hardcoding a filename. At least on reasonable shells (so not Windows...) you can write something like ./executable < input02 to connect stdin to the file input02.
Now we can write main
-- I like having something like this
orDie :: String -> Maybe a -> IO a
orDie msg Nothing = hPutStrLn stderr msg >> exitFailure
orDie msg (Just x) = return x
main :: IO ()
main = do
input <- orDie "failed to parse" =<< (traverse parseLine <$> lines <$> getContents)
-- foldl is almost always wrong; it should be either foldr (the idiomatic one) or foldl' (the performant one)
let finalPos = foldl' (flip move) (Position 0 0) input -- even though we have to flip move, I consider it more idiomatic to have move the way it is and chalk this flip up to "foldl is annoying"
print $ hPos finalPos * vPos finalPos -- print = putStrLn . show
The collected imports:
import Text.Read(readMaybe)
import System.Exit(exitFailure)
import Data.List(foldl')
import System.IO(hPutStrLn, stderr) | {
"domain": "codereview.stackexchange",
"id": 43201,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "programming-challenge, haskell",
"url": null
} |
c#, beginner, classes, constructor
Title: Tiny Validity class
Question: Here is a part of my new code replacing the old and deprecated old-school one.
Let's get to business right away:
I document everything with Documentation comments, which are proving very useful so far.
I present you my new tiny class called Validity, of which goal is to indicate if something is valid or not, and if not, then there should be specified a reason for it.
Note: I actually tried to use struct instead, but as it appears, parameterless constructors are from C# >= 10 or something like that there.
There shall be absolutely no problem for you to review as I documented, well, everything. I welcome all of your tips to make it perfect as in more effective or better to use, safer, or whatsoever...
/* I have a bunch of localized strings to my language. */
private const string INPUT_EMPTY = "Input is empty";
/// <summary>
/// <para>
/// Generic storage object for valid bools and various invalidity reasons.
/// </para>
/// </summary>
public class Validity
{
/// <summary>
/// <para>
/// This indicates if something is valid or not.
/// </para>
/// </summary>
public bool IsValid { get; set; }
/// <summary>
/// <para>
/// If something is invalid, this indicates a reason for it.
/// </para>
/// </summary>
public string ReasonForInvalid { get; set; }
/// <summary>
/// <para>
/// The default parameterless constructor assumes:
/// <code>
/// IsValid == true
/// </code>
/// and expects no reason for it whatsoever.
/// </para>
/// </summary>
public Validity()
{
IsValid = true;
ReasonForInvalid = "";
} | {
"domain": "codereview.stackexchange",
"id": 43202,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, classes, constructor",
"url": null
} |
c#, beginner, classes, constructor
/// <summary>
/// <para>
/// The second constructor assumes:
/// <code>
/// IsValid == false
/// </code>
/// and expects a reason for being invalid.
/// </para>
/// </summary>
public Validity(in string aReasonForInvalid)
{
IsValid = false;
ReasonForInvalid = aReasonForInvalid;
}
}
/* Just to try it out, and declare something! :) */
Validity InputValidity = new Validity(INPUT_EMPTY);
Answer: Unnecessary in parameter
The in string parameter modifier is what sticks out the most. I'm not sure what benefit this has over a regular string parameter. Strings are allocated on the heap in C#, so all you ensure with the in modifier is that you get the same pointer... which you get anyways by passing it as a regular string. Furthermore, strings are immutable.
Specifying the in modifier is useful for value types where you do want to pass by value, but prevent the code in this constructor from modifying it.
If you desire immutability in your Validity class, refactor your properties to have a readonly backing field:
public bool IsValid { get; }
public string ReasonForInvalid { get; }
// ^ (no 'set;' between the curly braces)
Unnecessarily Verbose Comments
The second thing that stands out are the comments. The comments seem rather verbose for what the class does. Consider rewriting the comments as quick one-liners. For example, the comment for the parameterless constructor is:
/// <summary>
/// <para>
/// The default parameterless constructor assumes:
/// <code>
/// IsValid == true
/// </code>
/// and expects no reason for it whatsoever.
/// </para>
/// </summary>
This can be rewritten as:
/// <summary>
/// Initialize a new Validity object marking it valid with no reason provided.
/// </summary> | {
"domain": "codereview.stackexchange",
"id": 43202,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, classes, constructor",
"url": null
} |
c#, beginner, classes, constructor
Much more clear and concise. Likewise, the other constructor comment can be rewritten from:
/// <summary>
/// <para>
/// The second constructor assumes:
/// <code>
/// IsValid == false
/// </code>
/// and expects a reason for being invalid.
/// </para>
/// </summary>
To:
/// <summary>
/// Initialize a new Validity object marking it invalid for the given reason.
/// </summary>
Class Constraints Are Not Enforced
If a reason is required, then the following code should throw an exception:
new Validity(null);
new Validity("");
new Validity(" \t ");
Consider checking if (string.IsNullOrWhiteSpace(aReasonForInvalid)) and throwing an ArgumentNullException if it returns true.
On a related note, aReasonForInvalid doesn't need the a at the beginning. Simply calling it reasonForInvalid is enough. The phrase "reason for invalid" is also not grammatically correct. It could be reasonForInvalidity or simply reason would work as well. Even naming the parameter message and the property Message would work.
All "Valid" Objects Are The Same
Consider the case where you want a "valid" validity object. Code will initialize a new object each time. Consider adding a public static field to represent a valid validity object:
public class Validity
{
/// <summary>
/// Returns a Validity object representing a valid value.
/// </summary>
public static readonly Validity Valid = new Validity();
private Validity()
{
IsValid = true;
}
/// <summary>...</summary>
public Validity(string reasonForInvalid)
{
...
Since the original code requires calling two different constructors (new Validitory() versus new Validity(string)) the static field allows you to give it a good name.
var validity = x > 5 ? Validity.Valid
: new Validity("x must be more than 5"); | {
"domain": "codereview.stackexchange",
"id": 43202,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, classes, constructor",
"url": null
} |
c#, beginner, classes, constructor
This allows your code to reuse the "valid" validity object, since the state of each "valid" object is the same. No need to allocate more memory to store the same exact values. | {
"domain": "codereview.stackexchange",
"id": 43202,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c#, beginner, classes, constructor",
"url": null
} |
array, go
Title: in_array() in Go
Question: This function's objective is very simple. It takes array and checks if val is a value inside of this array. It returns whether val exists and which is the index inside the array that contains val.
Could this be coded in a better way? How would I implement this to work with any kind of array (the code below works only with arrays of strings)?
package main
import "fmt"
func in_array(val string, array []string) (exists bool, index int) {
exists = false
index = -1;
for i, v := range array {
if val == v {
index = i
exists = true
return
}
}
return
}
func main() {
names := []string{ "Mary", "Anna", "Beth", "Johnny", "Beth" }
fmt.Println( in_array("Jack", names) )
}
Go probably provides a similar function, but this is for study purposes only.
Answer: Rather than tie yourself to only one type (string), you could use the reflect package as well as interfaces to make it somewhat type indifferent. The following is my reworking of your code:
package main
import "fmt"
import "reflect"
func in_array(val interface{}, array interface{}) (exists bool, index int) {
exists = false
index = -1
switch reflect.TypeOf(array).Kind() {
case reflect.Slice:
s := reflect.ValueOf(array)
for i := 0; i < s.Len(); i++ {
if reflect.DeepEqual(val, s.Index(i).Interface()) == true {
index = i
exists = true
return
}
}
}
return
} | {
"domain": "codereview.stackexchange",
"id": 43203,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, go",
"url": null
} |
array, go
return
}
Note that we now import the reflect package. We also changed the types of val and array to interface{} so that we may pass any type in. We then use the reflect.Typeof() to glean the reflection reflect.Type of the value in the array interface{}. We then glean the type with Kind(), and use a case to fall into our inner code if its a slice (can add more cases to extend this).
In our inner code, we get the value of the array argument, and store it in s. We then iterate over the length of s, and compare val to s at the index i declared as an interface with Interface() and check for truthiness. If its true, we exit with a true and the index.
Running the main function with both a slice of strings and a slice of integers, as follows, works:
func main() {
names := []string{"Mary", "Anna", "Beth", "Johnny", "Beth"}
fmt.Println(in_array("Anna", names))
fmt.Println(in_array("Jon", names))
ints := []int{1, 4, 3, 2, 6}
fmt.Println(in_array(3, ints))
fmt.Println(in_array(95, ints))
}
The above example gets us:
true 1
false -1
true 2
false -1
EDIT: June 2021 - refactored the above code as follows:
func inArray(val interface{}, array interface{}) (index int) {
values := reflect.ValueOf(array)
if reflect.TypeOf(array).Kind() == reflect.Slice || values.Len() > 0 {
for i := 0; i < values.Len(); i++ {
if reflect.DeepEqual(val, values.Index(i).Interface()) {
return i
}
}
}
return -1
}
with the runner function:
func main() {
name := "Mary Anna"
fmt.Println(inArray("Anna", name))
var empty []string
fmt.Println(inArray("Anna", empty))
names := []string{"Mary", "Anna", "Beth", "Johnny", "Beth"}
fmt.Println(inArray("Anna", names))
fmt.Println(inArray("Jon", names))
ints := []int{1, 4, 3, 2, 6}
fmt.Println(inArray(3, ints))
fmt.Println(inArray(95, ints))
} | {
"domain": "codereview.stackexchange",
"id": 43203,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "array, go",
"url": null
} |
javascript, typescript, iteration
Title: flatten API response, and renaming prop - is there a solution by iterating key/value pair?
Question: I want to sum up and flatten the structure of an API response. Since I didn't succeed by iterating over the key/value pairs of input.statistic I came up with another solution which does the job but I'm not happy with it.
What I do recieve is:
input = {
"data": some unimportant stuff,
"statistic": [
{
"valueId": 111,
"statistic": {
"min": 0,
"max": 0,
"average": 0.12
}
},
{
"valueId": 222,
"statistic": {
"min": 0,
"max": 1,
"average": 0.14
}
}
]
}
At this point I'm only interested in the statistic data and I want to change it to something like that:
{
"stat111": [
{name: "min", value: 0},
{name: "max", value: 0},
{name: "average", value: 0.12}
],
"stat222": [
{name: "min", value: 0},
{name: "max", value: 1},
{name: "average", value: 0.14}
]
}
What I do is:
const statDat = {};
for (const item of input.statistic) {
const nameTop = 'stat' + item.valueId.toString();
const props = [];
for (let key in item.statistic) {
props.push({name: key, value: item.statistic[key]});
}
statDat[nameTop] = props;
}
So statDat looks the way I want it but once more I'm sure that there is a better and newer way of flatten and renaming the structure. Any hints?
Answer: If you're looking for "newer", then I would recommend familiarizing yourself with a good Javascript api, such as the Mozilla Developer Network's. That has such entries as array's forEach, Object.entries, destructuring assignments, and arrow functions. Those (and the new object notation) combine to change your code to
const statDat = {};
input.statistic.forEach( (item) => {
const nameTop = 'stat' + item.valueId; // toString() unnecessary
statDat[nameTop] = Object.entries(item.statistic).map( ([name,value]) => ({name,value}) );
}); | {
"domain": "codereview.stackexchange",
"id": 43204,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, iteration",
"url": null
} |
javascript, typescript, iteration
we can also use Object.fromEntries as in Jonah's answer to get these five lines down to one command (which I break into 4 lines for readability).
const statDat2 = Object.fromEntries( input.statistic.map( ({valueId,statistic}) => [
'stat'+valueId,
Object.entries(statistic).map( ([name,value]) => ({name,value}) )
] ) );
const input = {
"data": "some unimportant stuff",
"statistic": [
{
"valueId": 111,
"statistic": {
"min": 0,
"max": 0,
"average": 0.12
}
},
{
"valueId": 222,
"statistic": {
"min": 0,
"max": 1,
"average": 0.14
}
}
]
};
const statDat = {};
input.statistic.forEach( (item) => {
const nameTop = 'stat' + item.valueId;
statDat[nameTop] = Object.entries(item.statistic).map( ([name,value]) => ({name,value}) );
});
console.log(statDat);
// or
const statDat2 = Object.fromEntries( input.statistic.map( ({valueId,statistic}) => [
'stat'+valueId,
Object.entries(statistic).map( ([name,value]) => ({name,value}) )
] ) );
console.log(statDat2);
Compressing five lines of code into one usually makes that one line a bit harder to understand than any of the five original lines, but much easier to understand overall. | {
"domain": "codereview.stackexchange",
"id": 43204,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript, typescript, iteration",
"url": null
} |
python, parsing, csv, pandas, email
Title: Fetch CSV file into PANDAS and send report of Spotify statistics
Question: I'm relatively new and self taught in Python. I've written this code which gets a CSV file from a website, plays around with the data then creates an email with information gleaned.
I know this is too long and clunky, I'm just not sure how to bring it down. Not looking for exact code from you, rather a nudge in the right direction that I can go and research/learn myself. For example, can I use a for loop to build the variables and/or email sends.
Any help greatly appreciated!
### Open website to click CSV
import webbrowser
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time
import datetime
now = datetime.datetime.now()
date_string = now.strftime('%Y-%m-%d')
url = ("https://app.chartmetric.com/charts/spotify_legacy#chartType=spotify_daily_top&country=nz&date=" + date_string)
webbrowser.get("C:/Program Files/Google/Chrome/Application/chrome.exe %s").open(url)
input("Download CSV then press 'Enter' to continue...")
### Convert to excel and move
from pyexcel.cookbook import merge_all_to_a_book
import glob
import shutil
import os
merge_all_to_a_book(glob.glob("//Downloads/Spotify Daily Top 200.csv"), ("//Daily Song Spikes/spotify_daily_spikes.xlsx"))
time.sleep(2)
os.remove("//Downloads/Spotify Daily Top 200.csv")
### Parse Data
import pandas as pd
df = pd.read_excel("//Daily Song Spikes/spotify_daily_spikes.xlsx", sheet_name='Spotify Daily Top 200.csv')
df["Release Date"] = df["Release Date"].str.split(', ').str[1]
df.loc[df["Change"] == "New", "Change"] = 99999
df = df[(df['Streams']>=7000) & (df['Change']>=5) & (df['Release Date']<="2021") & (df['Rank']<=100)]
df.drop(axis=1, labels="Label", inplace=True)
df.drop(axis=1, labels="Internal Link", inplace=True)
df.drop(axis=1, labels="Album", inplace=True)
df.drop(axis=1, labels="7-Day Velocity", inplace=True)
df.drop(axis=1, labels="ISRC", inplace=True) | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
df.to_excel('spotify_daily_spikes.xlsx', sheet_name='Filtered Data')
print(len(df.index), "songs returned")
value = input("How many songs to send: ",)
if value == "1":
artist1 = df.iloc[0,4]
song1 = df.iloc[0,2]
change1 = df.iloc[0,1]
link1 = df.iloc[0,3]
streams1 = df.iloc[0,6]
year1 = df.iloc[0,5]
rank1 = df.iloc[0,0]
### Send email
def spotifydailyspike(text, subject, recipient):
import win32com.client as win32
import os
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = recipient
mail.Subject = subject
mail.HtmlBody = text
mail.Display(True)
MailSubject = "Spotify Daily Spike"
MailAdress =""
MailInput = """\
<html>
<head></head>
<body>
<h1 style="font-family:calibri;font-size:30px">TODAY'S SPIKEY SONGS</h1>
<i><h4 style="font-family:calibri-light;font-size:12px;color:red">THIS IS AN AUTOMATED EMAIL</h4></i>
<p style="font-family:calibri light">
""" +str(artist1)+ """ - <a href=""" +link1+ """>""" +str(song1)+ """</a> | First released in """ +str(year1)+ """. """ +str(streams1)+ """ streams in the past 24 hours, up """ +str(change1)+ """ places to #""" +str(rank1)+ """<br>
</p>
</body>
</html>
"""
spotifydailyspike(MailInput, MailSubject, MailAdress)
elif value == "2":
artist1 = df.iloc[0,4]
song1 = df.iloc[0,2]
change1 = df.iloc[0,1]
link1 = df.iloc[0,3]
streams1 = df.iloc[0,6]
year1 = df.iloc[0,5]
rank1 = df.iloc[0,0]
artist2 = df.iloc[1,4]
song2 = df.iloc[1,2]
change2 = df.iloc[1,1]
link2 = df.iloc[1,3]
streams2 = df.iloc[1,6]
year2 = df.iloc[1,5]
rank2 = df.iloc[1,0]
def spotifydailyspike(text, subject, recipient):
import win32com.client as win32
import os
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = recipient
mail.Subject = subject
mail.HtmlBody = text
mail.Display(True) | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
MailSubject = "Spotify Daily Spike"
MailAdress =""
MailInput = """\
<html>
<head></head>
<body>
<h1 style="font-family:calibri;font-size:30px">TODAY'S SPIKEY SONGS</h1>
<i><h4 style="font-family:calibri-light;font-size:12px;color:red">THIS IS AN AUTOMATED EMAIL</h4></i>
<p style="font-family:calibri light">
""" +str(artist1)+ """ - <a href=""" +link1+ """>""" +str(song1)+ """</a> | First released in """ +str(year1)+ """. """ +str(streams1)+ """ streams in the past 24 hours, up """ +str(change1)+ """ places to #""" +str(rank1)+ """<br>
""" +str(artist2)+ """ - <a href=""" +link2+ """>""" +str(song2)+ """</a> | First released in """ +str(year2)+ """. """ +str(streams2)+ """ streams in the past 24 hours, up """ +str(change2)+ """ places to #""" +str(rank2)+ """<br>
</p>
</body>
</html>
"""
spotifydailyspike(MailInput, MailSubject, MailAdress)
elif value == "3":
artist1 = df.iloc[0,4]
song1 = df.iloc[0,2]
change1 = df.iloc[0,1]
link1 = df.iloc[0,3]
streams1 = df.iloc[0,6]
year1 = df.iloc[0,5]
rank1 = df.iloc[0,0]
artist2 = df.iloc[1,4]
song2 = df.iloc[1,2]
change2 = df.iloc[1,1]
link2 = df.iloc[1,3]
streams2 = df.iloc[1,6]
year2 = df.iloc[1,5]
rank2 = df.iloc[1,0]
artist3 = df.iloc[2,4]
song3 = df.iloc[2,2]
change3 = df.iloc[2,1]
link3 = df.iloc[2,3]
streams3 = df.iloc[2,6]
year3 = df.iloc[2,5]
rank3 = df.iloc[2,0]
def spotifydailyspike(text, subject, recipient):
import win32com.client as win32
import os
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = recipient
mail.Subject = subject
mail.HtmlBody = text
mail.Display(True) | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
MailSubject = "Spotify Daily Spike"
MailAdress =""
MailInput = """\
<html>
<head></head>
<body>
<h1 style="font-family:calibri;font-size:30px">TODAY'S SPIKEY SONGS</h1>
<i><h4 style="font-family:calibri-light;font-size:12px;color:red">THIS IS AN AUTOMATED EMAIL</h4></i>
<p style="font-family:calibri light">
""" +str(artist1)+ """ - <a href=""" +link1+ """>""" +str(song1)+ """</a> | First released in """ +str(year1)+ """. """ +str(streams1)+ """ streams in the past 24 hours, up """ +str(change1)+ """ places to #""" +str(rank1)+ """<br>
""" +str(artist2)+ """ - <a href=""" +link2+ """>""" +str(song2)+ """</a> | First released in """ +str(year2)+ """. """ +str(streams2)+ """ streams in the past 24 hours, up """ +str(change2)+ """ places to #""" +str(rank2)+ """<br>
""" +str(artist3)+ """ - <a href=""" +link3+ """>""" +str(song3)+ """</a> | First released in """ +str(year3)+ """. """ +str(streams3)+ """ streams in the past 24 hours, up """ +str(change3)+ """ places to #""" +str(rank3)+ """<br>
</p>
</body>
</html>
"""
spotifydailyspike(MailInput, MailSubject, MailAdress)
elif value == "4":
artist1 = df.iloc[0,4]
song1 = df.iloc[0,2]
change1 = df.iloc[0,1]
link1 = df.iloc[0,3]
streams1 = df.iloc[0,6]
year1 = df.iloc[0,5]
rank1 = df.iloc[0,0]
artist2 = df.iloc[1,4]
song2 = df.iloc[1,2]
change2 = df.iloc[1,1]
link2 = df.iloc[1,3]
streams2 = df.iloc[1,6]
year2 = df.iloc[1,5]
rank2 = df.iloc[1,0]
artist3 = df.iloc[2,4]
song3 = df.iloc[2,2]
change3 = df.iloc[2,1]
link3 = df.iloc[2,3]
streams3 = df.iloc[2,6]
year3 = df.iloc[2,5]
rank3 = df.iloc[2,0]
artist4 = df.iloc[3,4]
song4 = df.iloc[3,2]
change4 = df.iloc[3,1]
link4 = df.iloc[3,3]
streams4 = df.iloc[3,6]
year4 = df.iloc[3,5]
rank4 = df.iloc[3,0]
def spotifydailyspike(text, subject, recipient):
import win32com.client as win32
import os | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = recipient
mail.Subject = subject
mail.HtmlBody = text
mail.Display(True)
MailSubject = "Spotify Daily Spike"
MailAdress =""
MailInput = """\
<html>
<head></head>
<body>
<h1 style="font-family:calibri;font-size:30px">TODAY'S SPIKEY SONGS</h1>
<i><h4 style="font-family:calibri-light;font-size:12px;color:red">THIS IS AN AUTOMATED EMAIL</h4></i>
<p style="font-family:calibri light">
""" +str(artist1)+ """ - <a href=""" +link1+ """>""" +str(song1)+ """</a> | First released in """ +str(year1)+ """. """ +str(streams1)+ """ streams in the past 24 hours, up """ +str(change1)+ """ places to #""" +str(rank1)+ """<br>
""" +str(artist2)+ """ - <a href=""" +link2+ """>""" +str(song2)+ """</a> | First released in """ +str(year2)+ """. """ +str(streams2)+ """ streams in the past 24 hours, up """ +str(change2)+ """ places to #""" +str(rank2)+ """<br>
""" +str(artist3)+ """ - <a href=""" +link3+ """>""" +str(song3)+ """</a> | First released in """ +str(year3)+ """. """ +str(streams3)+ """ streams in the past 24 hours, up """ +str(change3)+ """ places to #""" +str(rank3)+ """<br>
""" +str(artist4)+ """ - <a href=""" +link4+ """>""" +str(song4)+ """</a> | First released in """ +str(year4)+ """. """ +str(streams4)+ """ streams in the past 24 hours, up """ +str(change4)+ """ places to #""" +str(rank4)+ """<br>
</p>
</body>
</html>
"""
spotifydailyspike(MailInput, MailSubject, MailAdress)
elif value == "5":
artist1 = df.iloc[0,4]
song1 = df.iloc[0,2]
change1 = df.iloc[0,1]
link1 = df.iloc[0,3]
streams1 = df.iloc[0,6]
year1 = df.iloc[0,5]
rank1 = df.iloc[0,0] | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
artist2 = df.iloc[1,4]
song2 = df.iloc[1,2]
change2 = df.iloc[1,1]
link2 = df.iloc[1,3]
streams2 = df.iloc[1,6]
year2 = df.iloc[1,5]
rank2 = df.iloc[1,0]
artist3 = df.iloc[2,4]
song3 = df.iloc[2,2]
change3 = df.iloc[2,1]
link3 = df.iloc[2,3]
streams3 = df.iloc[2,6]
year3 = df.iloc[2,5]
rank3 = df.iloc[2,0]
artist4 = df.iloc[3,4]
song4 = df.iloc[3,2]
change4 = df.iloc[3,1]
link4 = df.iloc[3,3]
streams4 = df.iloc[3,6]
year4 = df.iloc[3,5]
rank4 = df.iloc[3,0]
artist5 = df.iloc[4,4]
song5 = df.iloc[4,2]
change5 = df.iloc[4,1]
link5 = df.iloc[4,3]
streams5 = df.iloc[4,6]
year5 = df.iloc[4,5]
rank5 = df.iloc[4,0]
def spotifydailyspike(text, subject, recipient):
import win32com.client as win32
import os
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = recipient
mail.Subject = subject
mail.HtmlBody = text
mail.Display(True) | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
MailSubject = "Spotify Daily Spike"
MailAdress =""
MailInput = """\
<html>
<head></head>
<body>
<h1 style="font-family:calibri;font-size:30px">TODAY'S SPIKEY SONGS</h1>
<i><h4 style="font-family:calibri-light;font-size:12px;color:red">THIS IS AN AUTOMATED EMAIL</h4></i>
<p style="font-family:calibri light">
""" +str(artist1)+ """ - <a href=""" +link1+ """>""" +str(song1)+ """</a> | First released in """ +str(year1)+ """. """ +str(streams1)+ """ streams in the past 24 hours, up """ +str(change1)+ """ places to #""" +str(rank1)+ """<br>
""" +str(artist2)+ """ - <a href=""" +link2+ """>""" +str(song2)+ """</a> | First released in """ +str(year2)+ """. """ +str(streams2)+ """ streams in the past 24 hours, up """ +str(change2)+ """ places to #""" +str(rank2)+ """<br>
""" +str(artist3)+ """ - <a href=""" +link3+ """>""" +str(song3)+ """</a> | First released in """ +str(year3)+ """. """ +str(streams3)+ """ streams in the past 24 hours, up """ +str(change3)+ """ places to #""" +str(rank3)+ """<br>
""" +str(artist4)+ """ - <a href=""" +link4+ """>""" +str(song4)+ """</a> | First released in """ +str(year4)+ """. """ +str(streams4)+ """ streams in the past 24 hours, up """ +str(change4)+ """ places to #""" +str(rank4)+ """<br>
""" +str(artist5)+ """ - <a href=""" +link5+ """>""" +str(song5)+ """</a> | First released in """ +str(year5)+ """. """ +str(streams5)+ """ streams in the past 24 hours, up """ +str(change5)+ """ places to #""" +str(rank5)+ """<br>
</p>
</body>
</html>
"""
spotifydailyspike(MailInput, MailSubject, MailAdress)
elif value == "6":
artist1 = df.iloc[0,4]
song1 = df.iloc[0,2]
change1 = df.iloc[0,1]
link1 = df.iloc[0,3]
streams1 = df.iloc[0,6]
year1 = df.iloc[0,5]
rank1 = df.iloc[0,0] | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
artist2 = df.iloc[1,4]
song2 = df.iloc[1,2]
change2 = df.iloc[1,1]
link2 = df.iloc[1,3]
streams2 = df.iloc[1,6]
year2 = df.iloc[1,5]
rank2 = df.iloc[1,0]
artist3 = df.iloc[2,4]
song3 = df.iloc[2,2]
change3 = df.iloc[2,1]
link3 = df.iloc[2,3]
streams3 = df.iloc[2,6]
year3 = df.iloc[2,5]
rank3 = df.iloc[2,0]
artist4 = df.iloc[3,4]
song4 = df.iloc[3,2]
change4 = df.iloc[3,1]
link4 = df.iloc[3,3]
streams4 = df.iloc[3,6]
year4 = df.iloc[3,5]
rank4 = df.iloc[3,0]
artist5 = df.iloc[4,4]
song5 = df.iloc[4,2]
change5 = df.iloc[4,1]
link5 = df.iloc[4,3]
streams5 = df.iloc[4,6]
year5 = df.iloc[4,5]
rank5 = df.iloc[4,0]
artist6 = df.iloc[5,4]
song6 = df.iloc[5,2]
change6 = df.iloc[5,1]
link6 = df.iloc[5,3]
streams6 = df.iloc[5,6]
year6 = df.iloc[5,5]
rank6 = df.iloc[5,0]
def spotifydailyspike(text, subject, recipient):
import win32com.client as win32
import os
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = recipient
mail.Subject = subject
mail.HtmlBody = text
mail.Display(True) | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
MailSubject = "Spotify Daily Spike"
MailAdress =""
MailInput = """\
<html>
<head></head>
<body>
<h1 style="font-family:calibri;font-size:30px">TODAY'S SPIKEY SONGS</h1>
<i><h4 style="font-family:calibri-light;font-size:12px;color:red">THIS IS AN AUTOMATED EMAIL</h4></i>
<p style="font-family:calibri light">
""" +str(artist1)+ """ - <a href=""" +link1+ """>""" +str(song1)+ """</a> | First released in """ +str(year1)+ """. """ +str(streams1)+ """ streams in the past 24 hours, up """ +str(change1)+ """ places to #""" +str(rank1)+ """<br>
""" +str(artist2)+ """ - <a href=""" +link2+ """>""" +str(song2)+ """</a> | First released in """ +str(year2)+ """. """ +str(streams2)+ """ streams in the past 24 hours, up """ +str(change2)+ """ places to #""" +str(rank2)+ """<br>
""" +str(artist3)+ """ - <a href=""" +link3+ """>""" +str(song3)+ """</a> | First released in """ +str(year3)+ """. """ +str(streams3)+ """ streams in the past 24 hours, up """ +str(change3)+ """ places to #""" +str(rank3)+ """<br>
""" +str(artist4)+ """ - <a href=""" +link4+ """>""" +str(song4)+ """</a> | First released in """ +str(year4)+ """. """ +str(streams4)+ """ streams in the past 24 hours, up """ +str(change4)+ """ places to #""" +str(rank4)+ """<br>
""" +str(artist5)+ """ - <a href=""" +link5+ """>""" +str(song5)+ """</a> | First released in """ +str(year5)+ """. """ +str(streams5)+ """ streams in the past 24 hours, up """ +str(change5)+ """ places to #""" +str(rank5)+ """<br>
""" +str(artist6)+ """ - <a href=""" +link6+ """>""" +str(song6)+ """</a> | First released in """ +str(year6)+ """. """ +str(streams6)+ """ streams in the past 24 hours, up """ +str(change6)+ """ places to #""" +str(rank6)+ """<br>
</p>
</body>
</html>
"""
spotifydailyspike(MailInput, MailSubject, MailAdress) | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
elif value == "7":
artist1 = df.iloc[0,4]
song1 = df.iloc[0,2]
change1 = df.iloc[0,1]
link1 = df.iloc[0,3]
streams1 = df.iloc[0,6]
year1 = df.iloc[0,5]
rank1 = df.iloc[0,0]
artist2 = df.iloc[1,4]
song2 = df.iloc[1,2]
change2 = df.iloc[1,1]
link2 = df.iloc[1,3]
streams2 = df.iloc[1,6]
year2 = df.iloc[1,5]
rank2 = df.iloc[1,0]
artist3 = df.iloc[2,4]
song3 = df.iloc[2,2]
change3 = df.iloc[2,1]
link3 = df.iloc[2,3]
streams3 = df.iloc[2,6]
year3 = df.iloc[2,5]
rank3 = df.iloc[2,0]
artist4 = df.iloc[3,4]
song4 = df.iloc[3,2]
change4 = df.iloc[3,1]
link4 = df.iloc[3,3]
streams4 = df.iloc[3,6]
year4 = df.iloc[3,5]
rank4 = df.iloc[3,0]
artist5 = df.iloc[4,4]
song5 = df.iloc[4,2]
change5 = df.iloc[4,1]
link5 = df.iloc[4,3]
streams5 = df.iloc[4,6]
year5 = df.iloc[4,5]
rank5 = df.iloc[4,0]
artist6 = df.iloc[5,4]
song6 = df.iloc[5,2]
change6 = df.iloc[5,1]
link6 = df.iloc[5,3]
streams6 = df.iloc[5,6]
year6 = df.iloc[5,5]
rank6 = df.iloc[5,0]
artist7 = df.iloc[6,4]
song7 = df.iloc[6,2]
change7 = df.iloc[6,1]
link7 = df.iloc[6,3]
streams7 = df.iloc[6,6]
year7 = df.iloc[6,5]
rank7 = df.iloc[6,0]
def spotifydailyspike(text, subject, recipient):
import win32com.client as win32
import os
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = recipient
mail.Subject = subject
mail.HtmlBody = text
mail.Display(True) | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
MailSubject = "Spotify Daily Spike"
MailAdress =""
MailInput = """\
<html>
<head></head>
<body>
<h1 style="font-family:calibri;font-size:30px">TODAY'S SPIKEY SONGS</h1>
<i><h4 style="font-family:calibri-light;font-size:12px;color:red">THIS IS AN AUTOMATED EMAIL</h4></i>
<p style="font-family:calibri light">
""" +str(artist1)+ """ - <a href=""" +link1+ """>""" +str(song1)+ """</a> | First released in """ +str(year1)+ """. """ +str(streams1)+ """ streams in the past 24 hours, up """ +str(change1)+ """ places to #""" +str(rank1)+ """<br>
""" +str(artist2)+ """ - <a href=""" +link2+ """>""" +str(song2)+ """</a> | First released in """ +str(year2)+ """. """ +str(streams2)+ """ streams in the past 24 hours, up """ +str(change2)+ """ places to #""" +str(rank2)+ """<br>
""" +str(artist3)+ """ - <a href=""" +link3+ """>""" +str(song3)+ """</a> | First released in """ +str(year3)+ """. """ +str(streams3)+ """ streams in the past 24 hours, up """ +str(change3)+ """ places to #""" +str(rank3)+ """<br>
""" +str(artist4)+ """ - <a href=""" +link4+ """>""" +str(song4)+ """</a> | First released in """ +str(year4)+ """. """ +str(streams4)+ """ streams in the past 24 hours, up """ +str(change4)+ """ places to #""" +str(rank4)+ """<br>
""" +str(artist5)+ """ - <a href=""" +link5+ """>""" +str(song5)+ """</a> | First released in """ +str(year5)+ """. """ +str(streams5)+ """ streams in the past 24 hours, up """ +str(change5)+ """ places to #""" +str(rank5)+ """<br>
""" +str(artist6)+ """ - <a href=""" +link6+ """>""" +str(song6)+ """</a> | First released in """ +str(year6)+ """. """ +str(streams6)+ """ streams in the past 24 hours, up """ +str(change6)+ """ places to #""" +str(rank6)+ """<br> | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
""" +str(artist7)+ """ - <a href=""" +link7+ """>""" +str(song7)+ """</a> | First released in """ +str(year7)+ """. """ +str(streams7)+ """ streams in the past 24 hours, up """ +str(change7)+ """ places to #""" +str(rank7)+ """<br> | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
</p>
</body>
</html>
"""
spotifydailyspike(MailInput, MailSubject, MailAdress)
print("FINISHED") | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
Rank,Change,Track,Internal Link,External Link,Artist,Album,Label,Release Date,Streams,Peak Position,Peak Date,7-Day Velocity,Total Days on Chart,ISRC
1,0,As It Was,/track?id=79012900,https://open.spotify.com/track/4LRPiXqCikLlN15c3yImP7,Harry Styles,As It Was,Columbia,"Mar 31, 2022",67358,1,"Apr 01, 2022",4.14,7,USSM12200612
2,0,Heat Waves,/track?id=29681793,https://open.spotify.com/track/02MWAaffLxlfxAUY7c5dvx,Glass Animals,Dreamland (+ Bonus Levels),Polydor Records,"Aug 06, 2020",25974,1,"Mar 20, 2022",-0.14,467,GBUM72000433
3,0,Cold Heart - PNAU Remix,/track?id=56778798,https://open.spotify.com/track/7rglLriMNBPAyuJOMGwi39,"Elton John, Dua Lipa, PNAU",The Lockdown Sessions,EMI,"Oct 22, 2021",24300,1,"Nov 06, 2021",-0.14,167,GBUM72104705
4,0,Starlight,/track?id=75297140,https://open.spotify.com/track/531KGXtBroSrOX9LVmiIgc,Dave,Starlight,Dave / Neighbourhood Recordings,"Mar 03, 2022",22439,4,"Mar 28, 2022",0.14,32,GBUM72201160
5,0,Down Under (feat. Colin Hay),/track?id=66927806,https://open.spotify.com/track/3Oww84xrmgjyr5J1ilOmAf,"Luude, Colin Hay",Down Under (feat. Colin Hay),Sweat It Out!,"Nov 19, 2021",22245,1,"Feb 05, 2022",-0.29,61,AUDCB1701966
6,0,Friday Night,/track?id=53117715,https://open.spotify.com/track/1Ynv5ahQNdRRgDGcMVa3Y6,King George,Friday Night,ACE VISIONZ PRODUCTIONS,"Nov 12, 2020",21538,4,"Mar 02, 2022",-0.29,106,QZNWS2005868
7,0,STAY (with Justin Bieber),/track?id=52404165,https://open.spotify.com/track/5PjdY0CKGZdEuoNab3yDmX,"The Kid LAROI, Justin Bieber",F*CK LOVE 3: OVER YOU,Columbia,"Jul 23, 2021",19721,1,"Jul 23, 2021",0.00,258,USSM12103949
8,0,INDUSTRY BABY (feat. Jack Harlow),/track?id=54095966,https://open.spotify.com/track/5Z9KJZvQzH6PFmb8SNkxuk,"Lil Nas X, Jack Harlow",MONTERO,Columbia,"Sep 17, 2021",19232,1,"Sep 17, 2021",0.43,202,USSM12104539
9,1,Shivers,/track?id=59477833,https://open.spotify.com/track/50nfwKoDiSYg8zOCREWAm5,Ed Sheeran,=,Atlantic Records UK,"Oct 29, 2021",19217,2,"Oct 31, 2021",-0.43,160,GBAHS2100671 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
10,-1,Enemy (with JID) - from the series Arcane League of Legends,/track?id=65244227,https://open.spotify.com/track/1HhNoOuqm1a5MXYEgAFl8o,"Imagine Dragons, JID, Arcane, League of Legends",Mercury - Act 1,KIDinaKORNER/Interscope Records,"Sep 03, 2021",18792,5,"Mar 19, 2022",-0.29,62,USUM72119916
11,0,In the Air,/track?id=27448698,https://open.spotify.com/track/5v7h5vQgCJKZT5vB3I9s3o,L.A.B.,L.A.B III,Loop Recordings Aot(ear)oa,"Dec 06, 2019",18544,1,"Feb 28, 2020",-0.14,631,NZLP01900490
12,0,Bad Habits,/track?id=50621806,https://open.spotify.com/track/3rmo8F54jFF8OgYsqTxm5d,Ed Sheeran,=,Atlantic Records UK,"Oct 29, 2021",17994,4,"Oct 29, 2021",-0.43,160,GBAHS2100318
13,1,Ghost,/track?id=33649792,https://open.spotify.com/track/6I3mqTwhRpn34SLVafSH7G,Justin Bieber,Justice,RBMG/Def Jam,"Mar 19, 2021",17509,10,"Mar 14, 2022",-0.14,192,USUM72102635
14,-1,MIDDLE OF THE NIGHT,/track?id=28140531,https://open.spotify.com/track/58HvfVOeJY7lUuCqF0m3ly,Elley Duhé,MIDDLE OF THE NIGHT,Not Fit For Society/RCA Records,"Jan 10, 2020",17089,13,"Apr 04, 2022",0.29,54,USRC11903813
15,0,Easy On Me,/track?id=63926722,https://open.spotify.com/track/46IZ0fSY2mpAiktS3KOqds,Adele,30,Columbia,"Nov 19, 2021",17070,1,"Nov 19, 2021",-0.29,139,USSM12105970
16,2,Mr Reggae,/track?id=67463129,https://open.spotify.com/track/6J6slpqRf9jYqGUVKVEOOt,L.A.B.,L.A.B V,Loop Recordings Aot(ear)oa,"Dec 17, 2021",16321,1,"Dec 17, 2021",-0.29,111,NZLP02200722
17,2,Where Are You Now,/track?id=55335292,https://open.spotify.com/track/3uUuGVFu1V7jTQL60S1r8z,"Lost Frequencies, Calum Scott",Where Are You Now,Epic Amsterdam,"Jul 30, 2021",16211,14,"Mar 25, 2022",0.00,122,BEHP42100067
18,-2,Woman,/track?id=50643187,https://open.spotify.com/track/6Uj1ctrBOjOas8xZXGqKk4,Doja Cat,Planet Her,Kemosabe Records/RCA Records,"Jun 25, 2021",16197,6,"Sep 11, 2021",0.14,267,USRC12101532 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
19,1,Freaky Deaky,/track?id=74525665,https://open.spotify.com/track/3vySEUpD0tc801F2WZDLYw,"Tyga, Doja Cat",Freaky Deaky,Kemosabe / RCA Records / Last Kings Music / EMPIRE,"Feb 25, 2022",16098,15,"Mar 17, 2022",-0.14,40,USUYG1414608
20,-3,Tom's Diner,/track?id=24229707,https://open.spotify.com/track/0oA9wBGDY4uyILLg4GymWP,"AnnenMayKantereit, Giant Rooks",Tom's Diner,Vertigo Berlin,"Jun 28, 2019",15957,13,"Mar 28, 2022",-0.71,25,DEUM71903009
21,3,Dreams - 2004 Remaster,/track?id=16026997,https://open.spotify.com/track/0ofHAoxe9vBkTCp2UQIavz,Fleetwood Mac,Rumours (Super Deluxe),Rhino/Warner Records,"Feb 04, 1977",15629,4,"Oct 24, 2020",0.00,"1,698",USWB11301111
22,1,Bam Bam (feat. Ed Sheeran),/track?id=75283401,https://open.spotify.com/track/0QBzMgT7NIeoCYy3sJCof1,"Camila Cabello, Ed Sheeran",Bam Bam (feat. Ed Sheeran),Epic,"Mar 04, 2022",15321,20,"Apr 04, 2022",0.57,34,USSM12200047
23,-2,No Role Modelz,/track?id=15619977,https://open.spotify.com/track/68Dni7IE4VyPkTOH9mRWHr,J. Cole,2014 Forest Hills Drive,Roc Nation Records LLC,"Dec 09, 2014",15130,20,"Mar 30, 2022",-0.14,93,USQX91402598
24,1,good 4 u,/track?id=41340637,https://open.spotify.com/track/4ZtFanR9U6ndgddUvNcjcG,Olivia Rodrigo,SOUR,Olivia Rodrigo PS,"May 21, 2021",14698,1,"May 21, 2021",1.43,321,USUG12101245
25,-3,THATS WHAT I WANT,/track?id=60290154,https://open.spotify.com/track/0e8nrvls4Qqv5Rfa2UhqmO,Lil Nas X,MONTERO,Columbia,"Sep 17, 2021",14649,3,"Sep 19, 2021",-0.29,203,USSM12105732
26,3,abcdefu,/track?id=56814906,https://open.spotify.com/track/4fouWK6XVHhzl78KzQ1UjL,GAYLE,abcdefu,Atlantic/Arthouse Records,"Aug 13, 2021",14431,3,"Dec 06, 2021",-0.86,144,USAT22103652
27,4,Controller,/track?id=17738774,https://open.spotify.com/track/2DkxWMmdvS3f5hbz4UGQLO,L.A.B.,L.A.B,Loop Recordings Aot(ear)oa,"Nov 24, 2017",14340,3,"Dec 26, 2020",0.71,875,NZLP01700337 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
28,0,Lost,/track?id=15923620,https://open.spotify.com/track/3GZD6HmiNUhxXYf8Gch723,Frank Ocean,channel ORANGE,Red Zone Entertainment / IDJ,"Jul 10, 2012",14142,19,"Mar 03, 2022",-0.57,35,USUM71207186
29,1,Kiss Me More (feat. SZA),/track?id=34026721,https://open.spotify.com/track/3DarAbFujv6eYNliUTyqtz,"Doja Cat, SZA",Planet Her,Kemosabe Records/RCA Records,"Jun 25, 2021",13909,2,"Jun 25, 2021",0.57,286,USRC12100543
30,-4,Boyfriend,/track?id=73438272,https://open.spotify.com/track/59CfNbkERJ3NoTXDvoURjj,Dove Cameron,Boyfriend,Disruptor Records/Columbia,"Feb 11, 2022",13890,12,"Mar 09, 2022",-0.43,55,USQX92200693
31,-4,Numb Little Bug,/track?id=72731976,https://open.spotify.com/track/3o9kpgkIcffx0iSwxhuNI2,Em Beihold,Numb Little Bug,"Republic Records/Moon Projects, LLC.","Jan 28, 2022",13857,24,"Mar 10, 2022",-0.86,69,USUM72200626
32,1,Here For You,/track?id=73441931,https://open.spotify.com/track/1QgebV92VO4Z7VxbQ1tSKo,"Wilkinson, Becky Hill",Cognition,BMG Rights Management (UK) Limited,"Feb 11, 2022",13679,5,"Feb 11, 2022",-0.14,56,GB5KW2104629
33,3,Nail Tech,/track?id=73641661,https://open.spotify.com/track/62Yo3FDddWY8ydu6PW2wyz,Jack Harlow,Nail Tech,Generation Now/Atlantic,"Feb 18, 2022",13581,19,"Feb 23, 2022",2.00,48,USAT22200223
34,-2,Fingers Crossed,/track?id=69188915,https://open.spotify.com/track/3yMC1KsTwh0ceXdIe4QQAQ,Lauren Spencer-Smith,Fingers Crossed,"Three Name Productions, Inc./ Island Records & Republic Records","Jan 05, 2022",13206,13,"Feb 09, 2022",-0.86,57,TCAFY2118876
35,2,Under the Sun,/track?id=68461762,https://open.spotify.com/track/1GQ7M3b1B4Dt9lMjoBOGcl,L.A.B.,L.A.B V,Loop Recordings Aot(ear)oa,"Dec 17, 2021",12858,7,"Dec 17, 2021",0.14,112,NZLP02200723
36,-2,Wait a Minute!,/track?id=13904490,https://open.spotify.com/track/0y60itmpH0aPKsFiGxmtnh,WILLOW,ARDIPITHECUS,Roc Nation W Smith P&D,"Jan 11, 2015",12718,34,"Apr 05, 2022",4.14,150,QMJMT1500801 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
37,2,Keep On Rollin,/track?id=72888783,https://open.spotify.com/track/3fRQ3919obMjRReHeoE4gH,King George,Keep On Rollin,ACE VISIONZ PRODUCTIONS,"Feb 14, 2022",12647,30,"Mar 11, 2022",0.00,45,QZFZ32236574
38,0,edamame (feat. Rich Brian),/track?id=54097040,https://open.spotify.com/track/5rW7qTn83sCKtqBoneJs63,"bbno$, Rich Brian",eat ya veggies,bbno$,"Oct 08, 2021",12509,25,"Mar 05, 2022",0.00,180,QMUY42100151
39,1,Light Switch,/track?id=69560913,https://open.spotify.com/track/3AVXwaOGCEL8cmBecfcsFJ,Charlie Puth,Light Switch (Instrumental),Atlantic Records,"Jan 19, 2022",12501,22,"Feb 07, 2022",0.29,62,USAT22107359
40,5,Why Oh Why,/track?id=32150616,https://open.spotify.com/track/3TaGtHDHWQ7TfPpX0eJrtB,L.A.B.,L.A.B IV,Loop Recordings Aot(ear)oa,"Dec 18, 2020",12144,1,"Dec 18, 2020",1.86,475,NZLP02000621
41,3,Cool it down,/track?id=68104261,https://open.spotify.com/track/3fT0AXVjnu3a3hUpyl8M6e,COTERIE,Cool it down,Sony Music Entertainment,"Dec 03, 2021",12129,40,"Apr 01, 2022",0.71,38,AUMEV2176726
42,-1,We Don't Talk About Bruno,/track?id=66986384,https://open.spotify.com/track/52xJxFP6TqMuO4Yt0eOkMz,"Carolina Gaitán - La Gaita, Mauro Castillo, Adassa, Rhenzy Feliz, Diane Guerrero, Stephanie Beatriz, Encanto - Cast",Encanto (Original Motion Picture Soundtrack),Walt Disney Records,"Nov 19, 2021",12106,3,"Feb 05, 2022",-1.86,101,USWD12112915
43,-8,When You're Gone,/track?id=78915804,https://open.spotify.com/track/0U1W2LZVUX7qTm7dDpqxh6,Shawn Mendes,When You're Gone,Shawn Mendes LP4-5 PS/ Island,"Mar 31, 2022",12019,35,"Apr 06, 2022",8.14,7,USUM72204098
44,-2,she's all i wanna be,/track?id=73278693,https://open.spotify.com/track/0IuVhCflrQPMGRrOyoY5RW,Tate McRae,she's all i wanna be,RCA Records Label,"Feb 04, 2022",11829,25,"Feb 28, 2022",-0.57,62,USRC12103120
45,3,Big Energy,/track?id=61602980,https://open.spotify.com/track/4pi1G1x8tl9VfdD9bL3maT,Latto,777,Streamcut/RCA Records,"Mar 25, 2022",11511,36,"Mar 25, 2022",-0.86,13,USRC12102454 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
46,-3,Just A Cloud Away,/track?id=78134581,https://open.spotify.com/track/0DGTcMqvVR7fmBXgiG6jz4,Pharrell Williams,Just A Cloud Away,Columbia,"Jan 01, 2013",11216,17,"Mar 25, 2022",-1.57,13,USQX92201647
47,0,Everlong,/track?id=15717288,https://open.spotify.com/track/5UWwZ5lm5PKu6eKsHAGxOk,Foo Fighters,The Colour And The Shape,RCA Records Label,"May 20, 1997",10753,30,"Mar 27, 2022",-0.71,25,USRW29600011
48,1,Do It To It,/track?id=57467910,https://open.spotify.com/track/20on25jryn53hWghthWWW3,"ACRAZE, Cherish",Do It To It,"Thrive Music, LLC","Aug 20, 2021",10747,11,"Dec 31, 2021",-0.43,157,QZFPL2100100
49,1,KELZ GARAGE (feat. Lomez Brown),/track?id=68066178,https://open.spotify.com/track/61Mo1EqfJ42Ww3BhO3nvCT,"SWIDT, Lomez Brown",312 DAY,Universal Music New Zealand & Australia (Distribution),"Dec 02, 2021",10705,49,"Apr 01, 2022",0.14,53,NZWD02100003
50,2,Levitating (feat. DaBaby),/track?id=31526926,https://open.spotify.com/track/5nujrmhLynf4yMoMtj8AQF,"Dua Lipa, DaBaby",Future Nostalgia,Warner Records,"Mar 27, 2020",10638,5,"Jan 02, 2021",-0.29,517,GBAHT2000942
51,0,Takeover,/track?id=26810154,https://open.spotify.com/track/7ArG7cEuyvTNXDwW7stm85,"Lee Mvtthews, NÜ",Bones,Lee Mvtthews,"Nov 01, 2019",10484,23,"Feb 25, 2022",-1.14,345,NZAM01902823
52,-6,In My Head,/track?id=78964339,https://open.spotify.com/track/1HvTxgCj0mTzQlEo0zLvFb,Lil Tjay,In My Head,Columbia,"Apr 01, 2022",10297,34,"Apr 03, 2022",,6,USSM12202421
53,4,Still D.R.E.,/track?id=15417010,https://open.spotify.com/track/503OTo2dSqe7qk76rgsbep,"Dr. Dre, Snoop Dogg",2001,Aftermath,"Nov 16, 1999",10142,15,"Feb 16, 2022",0.29,67,USIR19905031
54,1,Mr. Brightside,/track?id=15419058,https://open.spotify.com/track/003vvx7Niy0yvhvHt4a68B,The Killers,Hot Fuss,Island Records,"Jan 01, 2004",10008,26,"Dec 31, 2021",0.71,605,USIR20400274 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
55,4,Following the Sun,/track?id=31522299,https://open.spotify.com/track/5A5bLKdL5I3k3FTEQlAUw7,"SUPER-Hi, Neeka",Following the Sun,BLENDED,"Aug 20, 2021",9999,55,"Apr 03, 2022",1.00,30,SE5BU2081473
56,-2,traitor,/track?id=43417294,https://open.spotify.com/track/5CZ40GBx1sQ9agT82CLQCT,Olivia Rodrigo,SOUR,Olivia Rodrigo PS,"May 21, 2021",9871,3,"Jun 15, 2021",2.57,319,USUG12101243
57,4,Without Me,/track?id=15414251,https://open.spotify.com/track/7lQ8MOhq6IN2w8EYcFNSUk,Eminem,The Eminem Show,Aftermath,"May 26, 2002",9843,51,"Feb 22, 2022",0.43,230,USIR10211038
58,-2,drivers license,/track?id=32507149,https://open.spotify.com/track/5wANPM4fQCJwkGd4rN57mH,Olivia Rodrigo,SOUR,Olivia Rodrigo PS,"May 21, 2021",9828,4,"May 23, 2021",4.43,319,USUG12004749
59,4,The Real Slim Shady,/track?id=15413181,https://open.spotify.com/track/3yfqSUWxFvZELEM4PmlwIR,Eminem,The Marshall Mathers LP,Interscope,"May 23, 2000",9750,55,"Feb 24, 2022",-0.29,365,USIR10000448
60,-7,Need to Know,/track?id=48699803,https://open.spotify.com/track/3Vi5XqYrmQgOYBajMWSvCi,Doja Cat,Planet Her,Kemosabe Records/RCA Records,"Jun 25, 2021",9730,4,"Aug 18, 2021",-0.29,286,USRC12101120
61,-3,Infinity,/track?id=15093243,https://open.spotify.com/track/1SOClUWhOi8vHZYMz3GluK,Jaymes Young,Feel Something,Atlantic Records,"Jun 23, 2017",9723,40,"Mar 23, 2022",-2.43,120,USAT21700859
62,0,Go - goddard. Remix,/track?id=75320926,https://open.spotify.com/track/7kjANxR8XN4hCzLaSc2roy,"Cat Burns, goddard.",Go (goddard. Remix),Since 93,"Mar 04, 2022",9493,62,"Apr 06, 2022",,4,GBARL2200333
63,-3,Better Days (NEIKED x Mae Muller x Polo G),/track?id=61491313,https://open.spotify.com/track/6f5ExP43esnvdKPddwKXJH,"NEIKED, Mae Muller, Polo G",Better Days (NEIKED x Mae Muller x Polo G),Capitol,"Sep 24, 2021",9445,9,"Nov 02, 2021",-0.29,171,GBUM72106057
64,9,35,/track?id=58801375,https://open.spotify.com/track/6vFlODh4lr7VOho2MFxXvL,"Rob Ruha, Ka Hao",35,InDigiNation,"Sep 03, 2021",9323,11,"Nov 18, 2021",0.29,212,NZAM02102791 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
65,1,Oh My God,/track?id=66902232,https://open.spotify.com/track/3Kkjo3cT83cw09VJyrLNwX,Adele,30,Columbia,"Nov 19, 2021",9287,2,"Nov 22, 2021",-0.14,140,USSM12105973
66,1,Watermelon Sugar,/track?id=27222889,https://open.spotify.com/track/6UelLqGlWMcVH1E5c4H7lY,Harry Styles,Fine Line,Columbia,"Dec 13, 2019",9233,4,"Dec 13, 2019",3.71,844,USSM11912587
67,-3,Happier Than Ever,/track?id=55332293,https://open.spotify.com/track/4RVwu0g32PAqgUiJoXsdF8,Billie Eilish,Happier Than Ever,Darkroom/Interscope Records,"Jul 30, 2021",9139,3,"Aug 04, 2021",4.43,249,USUM72105936
68,8,Blinding Lights,/track?id=27552418,https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b,The Weeknd,After Hours,Republic Records,"Mar 20, 2020",9055,1,"Mar 21, 2020",0.14,745,USUG11904206
69,0,TO THE MOON,/track?id=65782871,https://open.spotify.com/track/5vUnjhBzRJJIAOJPde6zDx,"Jnr Choi, Sam Tompkins",TO THE MOON,Jnr Choi/Epic,"Nov 06, 2021",9009,34,"Feb 26, 2022",-2.43,71,QZNWW2131527
70,5,Hit 'Em Up - Single Version,/track?id=15893156,https://open.spotify.com/track/0Z2J91b2iTGLVTZC4fKgxf,"2Pac, Outlawz",Greatest Hits,2Pac Greatest Hits,"Jan 01, 1998",8859,64,"Mar 17, 2022",-0.29,71,USUG10801475
71,-3,Leave The Door Open,/track?id=33210584,https://open.spotify.com/track/02VBYrHfVwfEWXk5DXyf0T,"Bruno Mars, Anderson .Paak, Silk Sonic",An Evening With Silk Sonic,Aftermath Entertainment/Atlantic,"Nov 11, 2021",8825,57,"Apr 04, 2022",13.29,22,USAT22100906
72,8,The Motto,/track?id=65547840,https://open.spotify.com/track/18asYwWugKjjsihZ0YvRxO,"Tiësto, Ava Max",The Motto,Atlantic Records,"Nov 04, 2021",8816,70,"Mar 30, 2022",-0.29,98,CYA112001070
73,-8,Sweater Weather,/track?id=15790443,https://open.spotify.com/track/2QjOHCTQ1Jl3zawyYOpxh6,The Neighbourhood,I Love You.,Columbia,"Apr 19, 2013",8799,65,"Mar 20, 2022",0.71,502,USSM11300080 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
74,4,Someone To Be Around - Bonus Track,/track?id=64323491,https://open.spotify.com/track/7KkpWFfKfSivkMD6yrKhGD,SIX60,GOLD ALBUM (10th Anniversary Edition),Universal Music New Zealand Limited (Distribution),"Oct 21, 2021",8784,34,"Dec 26, 2021",-1.00,167,NZMI12100018
75,2,Sweetest Pie,/track?id=75856195,https://open.spotify.com/track/7mFj0LlWtEJaEigguaWqYh,"Megan Thee Stallion, Dua Lipa",Sweetest Pie,300 Entertainment,"Mar 11, 2022",8751,18,"Mar 14, 2022",-2.71,27,QMCE32200232
76,7,Save Your Tears (Remix) (with Ariana Grande) - Bonus Track,/track?id=34728848,https://open.spotify.com/track/1oFAF1hdPOickyHgbuRjyX,"The Weeknd, Ariana Grande",After Hours (Deluxe),XO / Republic Records,"Mar 20, 2020",8708,62,"Mar 21, 2022",3.57,16,USUG12101839
77,2,Wet Dreamz,/track?id=15619971,https://open.spotify.com/track/4tqcoej1zPvwePZCzuAjJd,J. Cole,2014 Forest Hills Drive,Roc Nation Records LLC,"Dec 09, 2014",8704,70,"Mar 22, 2022",0.71,74,USQX91402592
78,10,Don’t Forget Your Roots,/track?id=13710802,https://open.spotify.com/track/5mUiad5pDU1wFvIbtKgJKB,SIX60,Six60,Universal Music New Zealand Limited,"Jan 01, 2011",8668,18,"Apr 24, 2021",-1.00,"1,658",NZMI11100001
79,-7,Over,/track?id=61321186,https://open.spotify.com/track/23CKxEwKWsLs6LD5poGOLM,Lucky Daye,Candydrip,Keep Cool/RCA Records,"Mar 10, 2022",8621,46,"Mar 30, 2022",-3.57,20,USRC12102179
80,-9,Dandelions,/track?id=15799454,https://open.spotify.com/track/2eAvDnpXP5W0cVtiI0PUxV,Ruth B.,Safe Haven,Columbia,"May 05, 2017",8553,61,"Mar 20, 2022",-0.57,72,USSM11703468
81,-7,Mount Everest,/track?id=24136343,https://open.spotify.com/track/1ZdhOMWyFR8Iv9eylMGYg2,Labrinth,Imagination & the Misfit Kid,Syco Music,"Nov 22, 2019",8516,31,"Mar 10, 2022",-4.29,58,GBHMU1800032
82,11,Hypnotize - 2014 Remaster,/track?id=15088810,https://open.spotify.com/track/7KwZNVEaqikRSBSpyhXK2j,The Notorious B.I.G.,Life After Death (2014 Remastered Edition),Rhino Atlantic,"Mar 04, 1997",8512,67,"Mar 24, 2022",-0.71,262,USAT21402725 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
83,-13,Birthday Cake,/track?id=73138675,https://open.spotify.com/track/7dDrR6vMK1JAwZZ5MIWgme,Dylan Conrique,Birthday Cake,KYN Entertainment,"Feb 02, 2022",8497,64,"Apr 03, 2022",-1.43,18,ZZOPM2220577
84,-2,Baby,/track?id=75783908,https://open.spotify.com/track/3pudQCMnsFGwOElTZmuml8,"Aitch, Ashanti",Baby,Capitol,"Mar 10, 2022",8382,82,"Apr 06, 2022",5.43,15,GBUM72201110
85,4,deja vu,/track?id=33837370,https://open.spotify.com/track/6HU7h9RYOaPRFeh0R3UeAr,Olivia Rodrigo,SOUR,Olivia Rodrigo PS,"May 21, 2021",8355,2,"May 23, 2021",5.57,302,USUG12101240
86,-5,Meet Me At Our Spot,/track?id=28737183,https://open.spotify.com/track/07MDkzWARZaLEdKxo6yArG,"THE ANXIETY, WILLOW, Tyler Cole",THE ANXIETY,"MSFTSMusic / Roc Nation Records, LLC","Mar 13, 2020",8259,6,"Oct 20, 2021",-0.71,228,QMJMT2002693
87,-3,Stan,/track?id=15413508,https://open.spotify.com/track/3UmaczJpikHgJFyBTAJVoz,"Eminem, Dido",The Marshall Mathers LP,Interscope,"May 23, 2000",8237,80,"Mar 29, 2022",-0.14,64,USIR10001280
88,4,Someone You Loved,/track?id=21918634,https://open.spotify.com/track/7qEHsqek33rTcFNT9PFqLf,Lewis Capaldi,Divinely Uninspired To A Hellish Extent,Vertigo Berlin,"May 17, 2019",8206,3,"Jun 04, 2019",-0.57,"1,054",DEUM71807062
89,-3,Knife Talk (with 21 Savage ft. Project Pat),/track?id=58853129,https://open.spotify.com/track/2BcMwX1MPV6ZHP4tUT9uq6,"Drake, 21 Savage, Project Pat",Certified Lover Boy,OVO,"Sep 03, 2021",8185,7,"Sep 05, 2021",-0.14,213,USUG12104409
90,5,Catching Feelings (feat. SIX60),/track?id=25075281,https://open.spotify.com/track/0gCNs3jCCDhObAK0MRghtv,"Drax Project, SIX60",Drax Project,300 Entertainment,"Sep 27, 2019",8108,3,"Oct 01, 2019",0.00,919,QMCE31902432
91,0,Sunflower - Spider-Man: Into the Spider-Verse,/track?id=21815071,https://open.spotify.com/track/0RiRZpuVRbi7oqRdSMwhQY,"Post Malone, Swae Lee",Hollywood's Bleeding,Republic Records,"Sep 06, 2019",8102,18,"Dec 05, 2019",-2.71,930,USUM71814888 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
92,-2,Hrs & Hrs,/track?id=66959718,https://open.spotify.com/track/3M5azWqeZbfoVkGXygatlb,Muni Long,Public Displays Of Affection,"Supergiant Records, LLC / Def Jam Recordings","Nov 19, 2021",8015,40,"Mar 22, 2022",-4.14,16,QZAKB2136210
93,15,Go Your Own Way - 2004 Remaster,/track?id=16016837,https://open.spotify.com/track/07GvNcU1WdyZJq3XxP0kZa,Fleetwood Mac,Rumours,Rhino/Warner Records,"Feb 04, 1977",8003,33,"Dec 31, 2021",-1.14,"1,435",USWB10400050
94,-7,Softcore,/track?id=18714857,https://open.spotify.com/track/2K7xn816oNHJZ0aVqdQsha,The Neighbourhood,Hard To Imagine The Neighbourhood Ever Changing,Columbia,"Nov 02, 2018",7994,61,"Feb 13, 2022",3.86,88,USSM11800523
95,-10,Revenge,/track?id=15972113,https://open.spotify.com/track/5TXDeTFVRVY7Cvt0Dw4vWW,XXXTENTACION,17,Bad Vibes Forever / EMPIRE,"Aug 25, 2017",7899,24,"Jun 19, 2018",-2.14,149,USUYG1156895
96,2,Yes I Do,/track?id=32317413,https://open.spotify.com/track/6oTbxrszNWRsLdwFkGeHy6,L.A.B.,L.A.B IV,Loop Recordings Aot(ear)oa,"Dec 18, 2020",7889,7,"Dec 18, 2020",2.14,476,NZLP02000623
97,6,Money Trees,/track?id=15924392,https://open.spotify.com/track/2HbKqm4o0w5wEeEFXm2sD4,"Kendrick Lamar, Jay Rock","good kid, m.A.A.d city",Aftermath,"Jan 01, 2012",7808,21,"Aug 28, 2020",2.29,482,USUM71210785
98,11,Ain't Shit,/track?id=50643171,https://open.spotify.com/track/5lAnYvAIkSDNXqfo7DyFUm,Doja Cat,Planet Her,Kemosabe Records/RCA Records,"Jun 25, 2021",7786,6,"Jul 24, 2021",6.86,181,USRC12101540
99,-2,505,/track?id=12630649,https://open.spotify.com/track/58ge6dfP91o9oXMzq3XkIS,Arctic Monkeys,Favourite Worst Nightmare (Standard Version),Domino/Warner Records,"Apr 24, 2007",7776,88,"Mar 20, 2022",2.29,53,GBCEL0700074
100,2,2055,/track?id=34451527,https://open.spotify.com/track/4XvcHTUfIlWfyJTRG0aqlo,Sleepy Hallow,Still Sleep?,Winners Circle/RCA Records,"Jun 02, 2021",7770,9,"Aug 17, 2021",-1.00,265,USRC12100442 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
101,0,Pepeha,/track?id=58114994,https://open.spotify.com/track/7A1SKLC7QhybSkcIekJFxM,SIX60,Pepeha,Universal Music New Zealand Limited,"Aug 27, 2021",7761,4,"Aug 27, 2021",-2.00,223,NZMI12100002
102,-3,"Lose Yourself - From ""8 Mile"" Soundtrack",/track?id=15414496,https://open.spotify.com/track/1v7L65Lzy0j0vdpRjJewt1,Eminem,Just Lose It,Aftermath,"Jan 01, 2004",7745,59,"Feb 16, 2022",-3.29,77,USIR10211559
103,8,Peaches (feat. Daniel Caesar & Giveon),/track?id=33631904,https://open.spotify.com/track/4iJyoBOLtHqaGxP12qzhQI,"Justin Bieber, Daniel Caesar, Giveon",Justice,RBMG/Def Jam,"Mar 19, 2021",7716,1,"Mar 21, 2021",0.71,383,USUM72102636
104,-8,I Love You So,/track?id=14312336,https://open.spotify.com/track/4SqWKzw0CbA05TGszDgMlc,The Walters,I Love You So,Warner Records,"Nov 28, 2014",7622,58,"Feb 13, 2022",-1.43,140,TCACC1438995
105,-11,Another Love,/track?id=12491171,https://open.spotify.com/track/7jtQIBanIiJOMS6RyCx6jZ,Tom Odell,Long Way Down,ITNO/Columbia,"Jun 17, 2013",7620,71,"Mar 21, 2022",0.57,71,GBARL1300107
106,-2,Wavy,/track?id=32927700,https://open.spotify.com/track/6fZmJKpBSqMRx49KaY4waD,Muroki,Wavy,Universal Music New Zealand Limited (Distribution),"Feb 25, 2021",7619,20,"Aug 17, 2021",-2.14,281,NZOL02100001
107,-7,I AM WOMAN,/track?id=66960651,https://open.spotify.com/track/3nOz1U41SZZ0N3fuUWr9nb,Emmy Meli,I AM WOMAN,Disruptor Records/Arista Records,"Nov 19, 2021",7597,11,"Dec 13, 2021",-1.14,138,USAR12100239
108,-1,Redbone,/track?id=16077707,https://open.spotify.com/track/0wXuerDYiBnERgIpbb3JBR,Childish Gambino,"""Awaken, My Love!""",Glassnote Entertainment Group LLC,"Dec 02, 2016",7561,71,"Mar 16, 2022",-0.29,502,USYAH1600107
109,1,All She Wrote,/track?id=32927711,https://open.spotify.com/track/2yI8xyHgyhCXyw0Vq98twb,SIX60,All She Wrote,Universal Music New Zealand Limited,"Feb 26, 2021",7496,1,"Feb 26, 2021",-1.71,406,USSM12100552 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
110,2,Hotel California - 2013 Remaster,/track?id=15273529,https://open.spotify.com/track/40riOy7x9W7GXjyGp4pjAv,Eagles,Hotel California (2013 Remaster),Rhino/Elektra,"Dec 08, 1976",7472,45,"Dec 31, 2021",-1.00,"2,009",USEE11300353
111,-5,Sex on Fire,/track?id=15673749,https://open.spotify.com/track/0ntQJM78wzOLVeCUAW7Y45,Kings of Leon,Only By The Night,RCA/Legacy,"Sep 23, 2008",7410,69,"Aug 07, 2021",-1.29,531,USRC10800300
112,23,Africa,/track?id=15821286,https://open.spotify.com/track/2374M0fQpWi3dLnB54qaLX,TOTO,Toto IV,Columbia,"Apr 08, 1982",7383,32,"Dec 31, 2018",8.29,"1,628",USSM19801941
113,1,Smokin Out The Window,/track?id=65690618,https://open.spotify.com/track/3xVZYkcuWalGudeKl861wb,"Bruno Mars, Anderson .Paak, Silk Sonic",An Evening With Silk Sonic,Aftermath Entertainment/Atlantic,"Nov 11, 2021",7340,113,"Apr 07, 2022",10.86,21,USAT22105952
114,4,Don't Stop Believin',/track?id=15811629,https://open.spotify.com/track/4bHsxqR3GMrXTxEPLuK5ue,Journey,Escape,Columbia,"Jan 01, 1981",7302,44,"Dec 31, 2021",-1.29,"1,722",USSM18100116
115,4,Shallow,/track?id=20614204,https://open.spotify.com/track/2VxeLyX666F8uXCJ0dZF8B,"Lady Gaga, Bradley Cooper",A Star Is Born Soundtrack,A Star is Born OST,"Oct 05, 2018",7287,1,"Oct 25, 2018",-2.71,"1,277",USUM71813192
116,-3,Dark Red,/track?id=12861012,https://open.spotify.com/track/37y7iDayfwm3WXn5BiAoRk,Steve Lacy,Dark Red,Three Quarter,"Feb 20, 2017",7264,48,"Aug 25, 2021",1.43,233,GBKPL1778015
117,5,Party In The U.S.A.,/track?id=15393046,https://open.spotify.com/track/3E7dfMvvCLUddWissuqMwr,Miley Cyrus,The Time Of Our Lives (International Version),Hollywood Records,"Jan 01, 2009",7237,54,"Dec 31, 2021",0.00,"1,134",USHR10924519
118,3,Chosen (feat. Ty Dolla $ign),/track?id=32150588,https://open.spotify.com/track/1dIWPXMX4kRHj6Dt2DStUQ,"Blxst, Tyga, Ty Dolla $ign",No Love Lost (Deluxe),Red Bull Records Inc. / Evgle LLC,"Dec 04, 2020",7195,28,"Oct 12, 2021",-0.57,430,USP6L2000552 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
119,-14,Something In The Way - Remastered,/track?id=15361122,https://open.spotify.com/track/2WL6GQzPuK9Nrpy9XwNEbz,Nirvana,Nevermind (30th Anniversary Super Deluxe),Geffen,"Sep 24, 1991",7164,27,"Mar 20, 2022",-6.29,31,USGF19942512
120,20,In Da Club,/track?id=15414667,https://open.spotify.com/track/7iL6o9tox1zgHpKUfh9vuC,50 Cent,Get Rich Or Die Tryin',Shady Records,"Feb 06, 2003",7128,58,"Feb 18, 2022",2.14,58,USIR10300033
121,3,Big Poppa - 2005 Remaster,/track?id=15117473,https://open.spotify.com/track/2g8HN35AnVGIk7B8yMucww,The Notorious B.I.G.,Ready to Die (The Remaster),Bad Boy Records,"Sep 13, 1994",7120,101,"Feb 22, 2022",0.57,156,USBB40580817
122,-6,Riptide,/track?id=11005892,https://open.spotify.com/track/7yq4Qj7cqayVTp3FF9CWbm,Vance Joy,Dream Your Life Away,F-Stop Records/Atlantic,"Sep 08, 2014",7075,87,"Feb 15, 2017",-2.57,"1,555",AULI01385760
123,0,MONTERO (Call Me By Your Name),/track?id=33735279,https://open.spotify.com/track/1SC5rEoYDGUK4NfG82494W,Lil Nas X,MONTERO,Columbia,"Sep 17, 2021",7071,9,"Sep 17, 2021",1.14,201,USSM12100531
124,-9,Say You Won't Let Go,/track?id=11500844,https://open.spotify.com/track/5uCax9HTNlzGybIStD3vDh,James Arthur,Back from the Edge,Columbia,"Oct 28, 2016",7062,2,"Nov 02, 2016",-2.00,"1,965",DEE861600586
125,2,Work Out,/track?id=15617582,https://open.spotify.com/track/2wAJTrFhCnQyNSD3oUgTZO,J. Cole,Cole World: The Sideline Story,Roc Nation LLC,"Sep 27, 2011",7052,98,"Sep 28, 2021",1.71,378,USQX91100801
126,-9,pushin P (feat. Young Thug),/track?id=69230812,https://open.spotify.com/track/3XOalgusokruzA5ZBA2Qcb,"Gunna, Future, Young Thug",DS4EVER,300 Entertainment,"Jan 13, 2022",7044,14,"Feb 02, 2022",-2.71,71,QMCE32200039
127,9,Smells Like Teen Spirit - Remastered,/track?id=15361111,https://open.spotify.com/track/0gucTLf7trAf37Ua1uAyAu,Nirvana,Nevermind (30th Anniversary Super Deluxe),Geffen,"Sep 24, 1991",6989,115,"Mar 28, 2022",0.00,129,USGF19942501 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
128,13,Used To This,/track?id=66927833,https://open.spotify.com/track/37nGZSaEXsKzOZLINC3VOp,"Wilkinson, Issey Cross",Cognition,BMG Rights Management (UK) Limited,"Feb 11, 2022",6986,28,"Feb 11, 2022",-2.29,55,GB5KW2104422
129,10,Sundown,/track?id=26957652,https://open.spotify.com/track/4WEAdAPGiyI6LIMlHGfhdZ,SIX60,Six60,Universal Music New Zealand Limited,"Nov 08, 2019",6971,5,"Dec 26, 2020",-1.29,765,USSM11912566
130,4,The Chain - 2004 Remaster,/track?id=16027002,https://open.spotify.com/track/5e9TFTbltYBg2xThimr0rU,Fleetwood Mac,Rumours (Super Deluxe),Rhino/Warner Records,"Feb 04, 1977",6966,49,"Sep 21, 2019",-0.14,"1,065",USWB11301116
131,12,Don't Start Now,/track?id=26822879,https://open.spotify.com/track/3PfIrDoz19wz7qK7tYeu62,Dua Lipa,Future Nostalgia,Warner Records,"Mar 27, 2020",6949,3,"Mar 27, 2020",1.71,738,GBAHT1901121
132,-2,Love on the Run (feat. Jackson Owens),/track?id=47001694,https://open.spotify.com/track/6YHsPMvvmor0vFrMxI4UZi,"Sons Of Zion, Jackson Owens",Love on the Run (feat. Jackson Owens),Sony Music Entertainment,"Jun 04, 2021",6931,13,"Jul 23, 2021",-2.00,305,NZSG02100009
133,-8,I Hate U,/track?id=68085473,https://open.spotify.com/track/5dXWFMwD7I7zXsInONVl0H,SZA,I Hate U,Top Dawg Entertainment/RCA Records,"Dec 03, 2021",6922,6,"Dec 06, 2021",-0.71,125,USRC12103605
134,-3,'Till I Collapse,/track?id=15414270,https://open.spotify.com/track/4xkOaSrkexMciUUogZKVTS,"Eminem, Nate Dogg",The Eminem Show,Aftermath,"May 26, 2002",6912,73,"Mar 02, 2019",0.57,146,USIR10211066
135,3,Gangsta's Paradise,/track?id=15858008,https://open.spotify.com/track/1DIXPcTDzTj8ZMHt3PDt8p,"Coolio, L.V.",Gangsta's Paradise,"Tommy Boy Music, LLC","Oct 02, 1995",6865,115,"Feb 17, 2022",1.43,79,USTB10400128
136,-10,Beggin',/track?id=17856511,https://open.spotify.com/track/3Wrjm47oTz2sjIgck11l5e,Måneskin,Chosen,RCA Records Label,"Dec 08, 2017",6851,2,"Jul 24, 2021",-1.86,296,ITB001700846 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
137,9,Dance Monkey,/track?id=22955238,https://open.spotify.com/track/2N8m6CYs74qQO4mjVcXO30,Tones And I,Welcome To The Madhouse (Deluxe),Elektra (NEK),"Jul 16, 2021",6841,67,"Jul 20, 2021",0.29,263,QZES71982312
138,7,Under the Bridge,/track?id=16033465,https://open.spotify.com/track/3d9DChrdc6BOeFsbrZ3Is0,Red Hot Chili Peppers,Blood Sugar Sex Magik (Deluxe Edition),Warner Records,"Sep 24, 1991",6831,84,"Mar 08, 2019",-1.14,586,USWB19901576
139,-19,I’m Tired (with Zendaya) - Bonus Track,/track?id=73278663,https://open.spotify.com/track/6LtHYDgYHRCHoKK3snfr2w,"Labrinth, Zendaya",I’m Tired (with Zendaya) - Bonus Track,Columbia,"Feb 28, 2022",6810,13,"Mar 03, 2022",-8.00,38,USQX92200588
140,-12,Overpass Graffiti,/track?id=65243247,https://open.spotify.com/track/4btFHqumCO31GksfuBLLv3,Ed Sheeran,=,Atlantic Records UK,"Oct 29, 2021",6785,9,"Oct 29, 2021",-0.86,159,GBAHS2100673
141,18,Brown Eyed Girl,/track?id=15805428,https://open.spotify.com/track/3yrSvpt2l1xhsV9Em88Pul,Van Morrison,Blowin' Your Mind!,Columbia/Legacy,"Sep 01, 1967",6761,58,"Dec 31, 2021",-1.29,"1,152",USSM16700357
142,39,Shape of You,/track?id=12450039,https://open.spotify.com/track/7qiZfU4dY1lWllzX7mPBI3,Ed Sheeran,÷ (Deluxe),Atlantic Records UK,"Mar 03, 2017",6747,1,"Mar 07, 2017",5.86,"1,642",GBAHS1600463
143,-10,favorite crime,/track?id=43444101,https://open.spotify.com/track/5JCoSi02qi3jJeHdZXMmR8,Olivia Rodrigo,SOUR,Olivia Rodrigo PS,"May 21, 2021",6718,5,"May 30, 2021",,184,USUG12101249
144,-2,Get Into It (Yuh),/track?id=49661835,https://open.spotify.com/track/0W6I02J9xcqK8MtSeosEXb,Doja Cat,Planet Her,Kemosabe Records/RCA Records,"Jun 25, 2021",6703,15,"Aug 25, 2021",2.43,255,USRC12101535
145,-8,love nwantiti (ah ah ah),/track?id=25088483,https://open.spotify.com/track/2Xr1dTzJee307rmrkt8c0g,CKay,CKay The First,Chocolate City Music,"Aug 30, 2019",6665,10,"Oct 03, 2021",0.29,207,QMEU31910213 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
146,2,Ms. Jackson,/track?id=15483832,https://open.spotify.com/track/0I3q5fE6wg7LIfHGngUTnV,Outkast,Stankonia,Arista/LaFace Records,"Oct 31, 2000",6646,124,"Mar 12, 2022",0.71,111,USLF20000357
147,-18,Dancing On My Own,/track?id=14483852,https://open.spotify.com/track/2BOqDYLOJBiMOXShCV1neZ,Calum Scott,Only Human (Deluxe),Capitol Records (US1A),"Mar 09, 2018",6638,96,"Jun 29, 2020",-2.00,901,UK6KW1500205
148,-4,Tennessee Whiskey,/track?id=15933319,https://open.spotify.com/track/3fqwjXwUGN6vbzIwvyFMhx,Chris Stapleton,Traveller,Mercury Nashville,"May 04, 2015",6634,76,"Dec 31, 2021",-0.86,"1,426",USUM71418088
149,13,Bohemian Rhapsody - Remastered 2011,/track?id=13066583,https://open.spotify.com/track/4u7EnebtmKWzUH433cf5Qv,Queen,A Night At The Opera (2011 Remaster),EMI,"Nov 21, 1975",6620,39,"Apr 20, 2019",0.57,"1,009",GBUM71029604
150,23,California Love - Original Version,/track?id=15892932,https://open.spotify.com/track/3ia3dJETSOllPsv3LJkE35,"2Pac, Roger, Dr. Dre",Greatest Hits,2Pac Greatest Hits,"Jan 01, 1998",6613,56,"Feb 16, 2022",0.86,52,USUG10702628
151,-4,One Dance,/track?id=15194415,https://open.spotify.com/track/1zi7xx7UVEFkmKfv06H8x0,"Drake, WizKid, Kyla",Views,Cash Money Records/Young Money Ent./Universal Rec.,"May 06, 2016",6582,140,"Jul 13, 2018",1.29,133,USCM51600028
152,35,Thinking out Loud,/track?id=12449356,https://open.spotify.com/track/1Slwb6dOYkBlWal1PGtnNg,Ed Sheeran,x (Wembley Edition),Atlantic Records UK,"Jan 01, 2013",6579,38,"Mar 29, 2018",2.00,"1,442",GBAHS1400099
153,-2,Heartbreak Anniversary,/track?id=28541554,https://open.spotify.com/track/3FAJ6O0NOHQV8Mc5Ri6ENp,Giveon,TAKE TIME,Epic/Not So Fast,"Mar 27, 2020",6561,2,"Mar 14, 2021",2.14,416,USSM12000998
154,25,Jah Rastafari,/track?id=13708512,https://open.spotify.com/track/3XJy1qvLFMV42kL0lf73Po,1814,Jah Rydem,Patu Colbert,"Jan 01, 2008",6527,50,"Dec 26, 2021",1.14,375,NZEH00800003 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
155,23,Slice of Heaven,/track?id=13712816,https://open.spotify.com/track/4qVIORNqKvlFvE4HMgnvVC,"Dave Dobbyn, Herbs",Loyal,"Dobworld Limited, Thom Music","May 01, 1988",6522,27,"Dec 31, 2021",-5.57,551,NZSG00600072
156,8,Ni**as In Paris,/track?id=15920975,https://open.spotify.com/track/4Li2WHPkuyCdtmokzW2007,"JAY-Z, Kanye West",Watch The Throne (Deluxe),Roc Nation/RocAFella/IDJ,"Aug 08, 2011",6509,101,"Aug 05, 2016",2.57,335,USUM71111621
157,29,All Falls Down,/track?id=15234674,https://open.spotify.com/track/5SkRLpaGtvYPhw02vZhQQ9,"Kanye West, Syleena Johnson",The College Dropout,Roc-A-Fella,"Feb 10, 2004",6485,122,"Mar 02, 2022",-3.00,45,USDJ20301703
158,-6,Take Me To Church,/track?id=13198846,https://open.spotify.com/track/3dYD57lRAUcMHufyqn9GcI,Hozier,Hozier,Universal-Island Records Ltd.,"Jul 20, 2014",6473,110,"Mar 14, 2021",3.14,373,IEACJ1300031
159,-9,Circles,/track?id=25021708,https://open.spotify.com/track/21jGcNKet2qwijlDFuPiPb,Post Malone,Hollywood's Bleeding,Republic Records,"Sep 06, 2019",6469,2,"Sep 16, 2019",-1.43,930,USUM71915699
160,11,Forgot About Dre,/track?id=15417070,https://open.spotify.com/track/7iXF2W9vKmDoGAhlHdpyIa,"Dr. Dre, Eminem",2001,Aftermath,"Nov 16, 1999",6456,62,"Feb 15, 2022",-0.14,43,USIR19915077
161,-12,3 Nights,/track?id=21807733,https://open.spotify.com/track/0uI7yAKUf52Cn7y3sYyjiX,Dominic Fike,"Don't Forget About Me, Demos",Columbia,"Oct 16, 2018",6452,69,"Jan 09, 2020",-0.43,401,USQX91802455
162,-30,lovely (with Khalid),/track?id=19088585,https://open.spotify.com/track/0u2P5u6lvoDfwTYjAADbn4,"Billie Eilish, Khalid",lovely (with Khalid),Darkroom,"Apr 19, 2018",6445,3,"Jun 10, 2018",-1.14,"1,112",USUM71804190
163,-3,One Right Now (with The Weeknd),/track?id=65751614,https://open.spotify.com/track/00Blm7zeNqgYLPtW6zg8cj,"Post Malone, The Weeknd",One Right Now,Republic Records,"Nov 05, 2021",6445,11,"Nov 08, 2021",0.29,149,USUM72120404 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
164,6,Empire State Of Mind,/track?id=15452836,https://open.spotify.com/track/2igwFfvr1OAGX9SKDCPBwO,"JAY-Z, Alicia Keys",The Blueprint 3,Roc Nation / Jay-Z,"Sep 08, 2009",6444,164,"Apr 07, 2022",2.86,23,USJZ10900031
165,0,Godzilla (feat. Juice WRLD),/track?id=28213841,https://open.spotify.com/track/7FIWs0pqAYbP91WWM0vlTQ,"Eminem, Juice WRLD",Music To Be Murdered By,Shady/Aftermath/Interscope Records,"Jan 17, 2020",6436,2,"Jan 23, 2020",1.43,565,USUM72000788
166,-11,You Right,/track?id=50617036,https://open.spotify.com/track/0k4d5YPDr1r7FX77VdqWez,"Doja Cat, The Weeknd",Planet Her,Kemosabe Records/RCA Records,"Jun 25, 2021",6431,8,"Jun 27, 2021",0.71,276,USRC12100544
167,-1,Substance,/track?id=18463956,https://open.spotify.com/track/0MoQI1EZGSHLhd5UBdxPol,03 Greedo,The Wolf of Grape Street,Alamo,"Mar 09, 2018",6420,112,"Mar 07, 2022",0.71,48,USUYG1183222
168,29,Hey Ya!,/track?id=15049297,https://open.spotify.com/track/2PpruBYCo4H7WOBJ7Q2EwM,Outkast,Speakerboxxx/The Love Below,Arista,"Jan 01, 2003",6416,54,"Dec 31, 2017",,81,USAR10300924
169,0,It Was A Good Day,/track?id=15599388,https://open.spotify.com/track/2qOm7ukLyHUXWyR4ZWLwxA,Ice Cube,The Predator,Priority Records,"Nov 17, 1992",6415,118,"Feb 17, 2022",-2.43,61,USPO19250006
170,14,Sultans Of Swing,/track?id=12761361,https://open.spotify.com/track/37Tmv4NnfQeb0ZgUC4fOJj,Dire Straits,Dire Straits,EMI,"Oct 07, 1978",6408,83,"Jan 29, 2022",-3.14,461,GBF089601041
171,-17,Yellow,/track?id=12521939,https://open.spotify.com/track/3AJwUDP919kvQ9QcozQPxg,Coldplay,Parachutes,Parlophone UK,"Jul 10, 2000",6406,93,"May 09, 2021",-4.43,379,GBAYE0000267
172,-11,Good Days,/track?id=32400834,https://open.spotify.com/track/3YJJjQPAbDT7mGpX3WtQ9A,SZA,Good Days,Top Dawg Entertainment/RCA Records,"Dec 25, 2020",6395,2,"Feb 09, 2021",1.29,458,USRC12004189 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
173,3,Mood (feat. iann dior),/track?id=30361159,https://open.spotify.com/track/4jPy3l0RUwlUI9T5XHBW2m,"24kGoldn, iann dior",El Dorado,Records/Columbia,"Mar 26, 2021",6393,24,"Mar 28, 2021",-2.29,375,USQX92003025
174,0,They Don't Know,/track?id=13708248,https://open.spotify.com/track/2lLbW1PLYdcg7pWK8vRVIu,"Savage, Aaradhna",Moonshine,Frequency,"Jan 01, 2005",6386,79,"Feb 24, 2022",0.29,251,NZDR00500013
175,-17,Classic,/track?id=15790670,https://open.spotify.com/track/6FE2iI43OZnszFLuLtvvmg,MKTO,MKTO,Columbia/M2V,"Jan 01, 2012",6355,78,"Oct 28, 2021",-0.86,260,USSM11301446
176,17,"Rocket Man (I Think It's Going To Be A Long, Long Time)",/track?id=12483467,https://open.spotify.com/track/3gdewACMIVMEWVbyb8O9sY,Elton John,Honky Chateau,EMI,"May 19, 1972",6351,31,"Jun 02, 2019",-4.57,"1,328",GBAMB7200006
177,-10,Iris,/track?id=16032306,https://open.spotify.com/track/6Qyc6fS4DsZjB2mRW9DsQs,The Goo Goo Dolls,Dizzy up the Girl,Warner Records,"Sep 11, 1998",6324,119,"Mar 31, 2022",-8.29,82,USWB19800160
178,-21,Save Your Tears,/track?id=28793673,https://open.spotify.com/track/5QO79kh1waicV47BqGRL3g,The Weeknd,After Hours,Republic Records,"Mar 20, 2020",6304,16,"Feb 18, 2021",2.57,211,USUG12000658
179,11,Promiscuous,/track?id=15902731,https://open.spotify.com/track/2gam98EZKrF9XuOkU13ApN,"Nelly Furtado, Timbaland",Loose,Mosley / Geffen,"Jan 01, 2006",6300,77,"Oct 29, 2020",-0.29,283,USUM70603473
180,19,The Next Episode,/track?id=15417071,https://open.spotify.com/track/4LwU4Vp6od3Sb08CsP99GC,"Dr. Dre, Snoop Dogg",2001,Aftermath,"Nov 16, 1999",6263,47,"Feb 16, 2022",-0.29,48,USIR19915078
181,13,Sure Thing,/track?id=15447187,https://open.spotify.com/track/0JXXNGljqupsJaZsgSbMZV,Miguel,All I Want Is You,Jive,"Nov 26, 2010",6252,66,"Jun 02, 2021",,319,USJI10800160
182,-14,Adore You,/track?id=27599120,https://open.spotify.com/track/3jjujdWJ72nww5eGnfs2E7,Harry Styles,Fine Line,Columbia,"Dec 13, 2019",6234,5,"Dec 16, 2019",,581,USSM11912588 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
183,-17,Always on My Mind,/track?id=13707988,https://open.spotify.com/track/19cxRMqCzpYNU4wXcMj8jA,Tiki Taane,"Past, Present, Future",Dirty Dub,"Jan 01, 2007",6202,55,"Dec 26, 2021",-4.00,650,NZDD00700017
184,16,No Scrubs,/track?id=15484595,https://open.spotify.com/track/1KGi9sZVMeszgZOWivFpxs,TLC,Fanmail,Arista/LaFace Records,"Feb 23, 1999",6193,99,"Sep 15, 2016",2.00,211,USLF29900479
185,-22,Bound 2,/track?id=15927278,https://open.spotify.com/track/3sNVsP50132BTNlImLx70i,Kanye West,Yeezus,Rock The World/IDJ/Kanye/LP6,"Jun 18, 2013",6162,156,"Mar 21, 2022",1.14,24,USUM71307523
186,7,Perfect,/track?id=12450042,https://open.spotify.com/track/0tgVpDi06FyKpA1z0VMD4v,Ed Sheeran,÷ (Deluxe),Atlantic Records UK,"Mar 03, 2017",6150,6,"Mar 06, 2017",,"1,679",GBAHS1700024
187,-5,Martin & Gina,/track?id=29427847,https://open.spotify.com/track/1VLtjHwRWOVJiE5Py7JxoQ,Polo G,THE GOAT,Columbia,"May 15, 2020",6148,52,"Apr 12, 2021",-5.29,512,USQX92002595
188,-21,Somebody That I Used To Know,/track?id=11030776,https://open.spotify.com/track/1qDrWA6lyx8cLECdZE7TV7,"Gotye, Kimbra",Making Mirrors,Universal-Island Records Ltd.,"Jan 01, 2011",6137,166,"Apr 21, 2021",,25,AUZS21100040
189,-36,chaotic,/track?id=78044388,https://open.spotify.com/track/2bdqU7C4softKNcMYDFi96,Tate McRae,chaotic,RCA Records Label,"Mar 25, 2022",6129,42,"Mar 27, 2022",-13.43,12,USRC12102862
190,5,Afterglow,/track?id=12613367,https://open.spotify.com/track/6LW3Z1GqbL78TIjfDyg4zp,"Wilkinson, Becky Hill",Lazers Not Included,EMI,"Jan 01, 2013",6123,56,"May 13, 2021",,360,GBBZH1391803
191,-11,Help Me Out - Bonus Track,/track?id=31658458,https://open.spotify.com/track/7caFVygWyV6WfNcn5RrXDQ,"Kings, Sons Of Zion",RAPLIST (Fly Edition),Arch Angel Records,"May 21, 2021",6110,37,"May 21, 2021",-1.71,275,NZAC12000002
192,-7,Tropical,/track?id=17951282,https://open.spotify.com/track/3qIxnOusGoTpHvNVMLHscw,SL,Tropical,Independent,"Dec 26, 2017",6104,172,"Apr 04, 2022",,5,GBLFP1797885 | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
193,-4,Heartless,/track?id=15911299,https://open.spotify.com/track/4EWCNWgDS8707fNSZ1oaA5,Kanye West,808s & Heartbreak,Roc-A-Fella,"Nov 24, 2008",6098,161,"Mar 16, 2022",0.86,18,USUM70840511
194,-11,Listen to the Music,/track?id=16010077,https://open.spotify.com/track/7Ar4G7Ci11gpt6sfH9Cgz5,The Doobie Brothers,Toulouse Street,Warner Records,"Jan 01, 1972",6081,78,"Jan 29, 2022",-1.29,851,USWB10000626
195,-23,Location (feat. Burna Boy),/track?id=22554309,https://open.spotify.com/track/3z4CGd63tpUn9a6oQSG0CI,"Dave, Burna Boy",PSYCHODRAMA,Neighbourhood,"Mar 08, 2019",6063,160,"Apr 04, 2022",-1.14,7,GBUM71900578
196,-9,Dancing in the Moonlight,/track?id=12549819,https://open.spotify.com/track/3Fzlg5r1IjhLk2qRw667od,Toploader,Onka's Big Moka,Sony Soho Square,"Jan 01, 2000",6052,88,"Dec 31, 2020",,263,GBBBL9902165
197,-41,Falling,/track?id=27651731,https://open.spotify.com/track/1ZMiCix7XSAbfAJlEZWMCp,Harry Styles,Fine Line,Columbia,"Dec 13, 2019",6049,24,"Dec 13, 2019",,617,USSM11912590
198,-7,Before You Go,/track?id=27430934,https://open.spotify.com/track/2gMXnyrvIjhVBUZwvLZDMP,Lewis Capaldi,Divinely Uninspired To A Hellish Extent (Extended Edition),Vertigo Berlin,"Nov 22, 2019",6048,11,"Feb 20, 2020",-0.86,835,DEUM71905868
199,-4,"Surface Pressure - From ""Encanto""/Soundtrack Version",/track?id=66944652,https://open.spotify.com/track/6K5ph5mq1qprHae3TrgTj5,Jessica Darrow,"Surface Pressure (From ""Encanto"")","UMG Recordings, Inc.","Jan 27, 2022",6026,20,"Feb 06, 2022",-8.29,70,USWD12112914
200,-4,Just the Way You Are,/track?id=15084776,https://open.spotify.com/track/7BqBn9nzAq8spo5e7cZ0dJ,Bruno Mars,Doo-Wops & Hooligans,Atlantic Records,"Oct 05, 2010",6022,116,"Apr 19, 2021",,127,USAT21001269
``` | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
Answer: I would avoid Selenium if possible, but given that the website requires authentication it might be nontrivial. That said: you aren't using it other than the import; why?
I also don't understand why you're merging to an excel file. Your report - in intent, though perhaps not in implementation - only cares about the last 24 hours; so why would you merge and load?
Your repeated in-place drops will be less efficient than directly loading the CSV and specifying in usecols only the columns you want to keep.
Rather than coercing Change=New to 99999, it's simpler to include the New comparison as part of your filtration predicate.
Avoid using iloc for named columns. Just use the column names.
Your quite long copy-and-paste has effectively unrolled a loop that would just write out the top n rows of the dataframe. This repetition should go away. One easy way to look at the top few rows of a DataFrame is head().
You've hard-coded for Outlook. More portably, multiple mail clients should be able to read .eml files whose content can be produced by the Python built-in email modules; so consider doing that (even if it's a first step toward using Outlook anyway). For Outlook you might need to set an X-Unsent header.
Don't do this:
df["Release Date"].str.split(', ').str[1]
Instead, load this column as an actual Pandas timestamp.
Suggested
This suggestion covers loading, filtration and email generation, but not web download or Excel.
#!/usr/bin/env python3
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formataddr
import pandas as pd
def load_csv(filename: str = 'Spotify Daily Top 200.csv') -> pd.DataFrame:
return pd.read_csv(
filename,
parse_dates=['Peak Date', 'Release Date'],
usecols=[
'Rank', 'Change', 'Track', 'External Link', 'Artist', 'Release Date',
'Streams', 'Peak Position', 'Peak Date', 'Total Days on Chart',
],
) | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
def row_to_html(row: pd.Series) -> str:
return f'''
{row.Artist} -
<a href="{row['External Link']}">{row.Track}</a> |
First released in {row['Release Date'].year}.
{row.Streams} streams in the past 24 hours,
up {row.Change} places to #{row.Rank}<br/>
'''
def row_to_plain(row: pd.Series) -> str:
return f'''
{row.Artist} - {row.Track}
First released in {row['Release Date'].year}.
{row.Streams} streams in the past 24 hours,
up {row.Change} places to #{row.Rank}
'''
def render_html(df: pd.DataFrame) -> str:
head = '''
<html>
<head></head>
<body>
<h1 style="font-family:calibri;font-size:30px">TODAY'S SPIKEY SONGS</h1>
<i><h4 style="font-family:calibri-light;font-size:12px;color:red">THIS IS AN AUTOMATED EMAIL</h4></i>
<p style="font-family:calibri light">
'''
rows = df.apply(row_to_html, axis=1).str.cat()
foot = '''
</p>
</body>
</html>'''
return head + rows + foot
def render_plain(df: pd.DataFrame) -> str:
rows = df.apply(row_to_plain, axis=1).str.cat()
return "TODAY'S SPIKEY SONGS:\n\n" + rows
def filter_csv(df: pd.DataFrame) -> pd.DataFrame:
return df[
(df.Streams >= 7_000)
& (
(df.Change >= 5) | (df.Change == 'New')
)
& (df['Release Date'].dt.year <= 2021)
& (df.Rank <= 100)
]
def make_message(df: pd.DataFrame) -> bytes:
msg = MIMEMultipart('alternative')
msg['Subject'] = 'Spotify Daily Spike'
msg['From'] = formataddr(('Spikebot', 'spikebot@myfancydomain.nz'))
msg['To'] = formataddr(('Ross F', 'rossf@myfancydomain.nz'))
msg.attach(MIMEText(render_plain(df), 'plain'))
msg.attach(MIMEText(render_html(df), 'html'))
return msg.as_bytes()
def main() -> None:
df = filter_csv(load_csv())
print(f'{len(df)} songs returned')
n_songs = int(input('How many songs to send: '))
df = df.head(n_songs)
with open('spikey.eml', 'wb') as f:
f.write(make_message(df))
if __name__ == '__main__':
main() | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
python, parsing, csv, pandas, email
if __name__ == '__main__':
main()
Output
As shown in Evolution: | {
"domain": "codereview.stackexchange",
"id": 43205,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, parsing, csv, pandas, email",
"url": null
} |
php, html, sql, mysql, database
Title: Display visitor's number on your web page
Question: Display visitor's number on your web page.
The "visitors" table has only one column (visitor_count) and only one row. The column's initial value is 0.
I know goto should not be used but then the code would be nested if conditions:
if (...) {
if (...) {
if (...) {
.
.
.
// display successful result
echo "You are visitor number: ";
printf("%10d", $row["visitor_count"]);
}
}
}
Is there any other solution other than goto and nested if conditions such that "Rest of HTML" always show up even if php script encounters an error (like, database connection failed, table visitors not found, etc.)?
Code is below. Please do the code review.
index.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Visitor Count</title>
</head>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "exp";
// create db connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// check db connection
if ($conn == false) {
echo("Connection failed: " . mysqli_connect_error());
goto END;
}
// execute query
$sql = "UPDATE visitors SET visitor_count = visitor_count + 1";
$result = mysqli_query($conn, $sql);
// check result
if ($result == false) {
echo("Query failed: " . $sql. "<br>". "Error: " . mysqli_error($conn));
goto DB_END;
}
// execute query
$sql = "SELECT visitor_count FROM visitors";
$result = mysqli_query($conn, $sql);
// check result
if ($result == false) {
echo("Query failed: " . $sql. "<br>". "Error: " . mysqli_error($conn));
goto DB_END;
}
// get number of rows
$num_rows_expected = 1;
$num_rows_got = mysqli_num_rows($result); | {
"domain": "codereview.stackexchange",
"id": 43206,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, html, sql, mysql, database",
"url": null
} |
php, html, sql, mysql, database
// get number of rows
$num_rows_expected = 1;
$num_rows_got = mysqli_num_rows($result);
// verify number of rows got
if ($num_rows_got != $num_rows_expected) {
echo("Error: Mismatch: Number of rows expected = " . $num_rows_expected . ", Number of rows got = " . $num_rows_got);
goto RESULT_END;
}
// get a row
$row = mysqli_fetch_assoc($result);
// check if we got a row
if (($row == false) || ($row == null)) {
echo("Error: Got no row (data).");
goto RESULT_END;
}
// display successful result
echo "You are visitor number: ";
printf("%10d", $row["visitor_count"]);
RESULT_END:
// free the memory used by $result
mysqli_free_result($result);
DB_END:
// close db connection
mysqli_close($conn);
END:
?>
<!-- Rest of HTML should show up in all cases (successful cases as well as in error cases) -->
<br><br>Rest of HTML
</body>
</html>
Answer: A good method to avoid goto and nesting is exception handling. Something like this:
// database details
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "exp";
// activate reporting
$driver = new mysqli_driver();
$driver->report_mode = MYSQLI_REPORT_ALL;
try {
// create connection, if it fails an exception will be thrown
$mysqli = new mysqli($servername, $username, $password, $dbname);
// add our visit to the total
$mysqli->query("UPDATE visitors SET visitor_count = visitor_count + 1");
// get total number of visits
$result = $mysqli->query("SELECT visitor_count FROM visitors");
$row = $result->fetch_assoc();
echo "You are visitor number: ";
printf("%10d", $row["visitor_count"]);
} catch (mysqli_sql_exception $exception) {
// log and report error, then continue
echo "<br><br>A database error has occurred.<br><br>";
error_log("Visitor count database error: " . $exception);
} | {
"domain": "codereview.stackexchange",
"id": 43206,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, html, sql, mysql, database",
"url": null
} |
php, html, sql, mysql, database
In the code I used the object-oriented style instead of the procedural style, but either will do.
I left out quite a bit. I don't see the point of testing if there is one row, but you can, of course, add that. I didn't free the result, or close the database connection, because that will be done automatically when the script terminates.
As soon as any database error occurs this code will jump to the catch block. This will however not work for normal PHP errors. You might, for instance, think that you would need to check that $row["visitor_count"] exists, but I don't think so. As I said before, I assume that the single row exists in the database. If that row couldn't be retrieved it must be due to a database error, which would generate an exception.
Note 1: If your website gets very busy, and you want the visitor number to be very accurate, you might want to consider putting the 2 queries in a transaction, but I wouldn't bother. In my opinion it is completely irrelevant that the visitor count might be out by a few when the site is that busy.
Note 2: Reporting exact database errors to visitors might not be a good idea. It could be a security risk. It is better to report: "A database error has occurred.", to the visitor, and send the exact error to yourself or to a log file. | {
"domain": "codereview.stackexchange",
"id": 43206,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "php, html, sql, mysql, database",
"url": null
} |
linux, fish-shell
Title: seq with range:
Question: Is there a simpler way to get this result?
Also what is the syntax in fish for adding numbers to an array index before executing the lookup? arr[$i+1] did not seem to work...
desired output:
1-6
6-11
11-16
etc
but it would also be good to know if there was a generic unix tool to get the above output or similar:
1-6
7-11
12-16
etc
(also acceptable)
$ type seqn
seqn is a function with definition
# Defined in /home/xk/.config/fish/functions/seqn.fish @ line 2
function seqn --argument first increment last
set carr (seq $first $increment $last)
for i in (seq 1 (count $carr))
set i1 (pyp "$i+1")
echo $carr[$i] $carr[$i1]
end
end
$ for l in (seqn 1 300 3800)
echo $l | read -l start end
if test -n $end
echo $start-$end
end
end
1-301
301-601
601-901
901-1201
1201-1501
1501-1801
1801-2101
2101-2401
2401-2701
2701-3001
3001-3301
3301-3601
Answer: It's not clear whether you want a single function to produce the final output, or whether you want one function (seqn) dedicated to outputting the boundary values and a separate function to format the output of seqn.
I'm going to work on the basis that a single function to print a formatted list of intervals is the goal, which I'll achieve with stepwise adjustments to your original script:
The Basics
To start, it's a good idea to declare variables as --local inside a function to guarantee that you're not overwriting an existing variable with the same name unless that's your specific intention, which doesn't seem likely to be the case here:
function seqn --argument first increment last
set --local carr ( seq $first $increment $last )
Having defined an array, it seems a shame to have to call seq a second time just to generate the indices. Instead, you can loop through the values of the array:
for cval in $carr | {
"domain": "codereview.stackexchange",
"id": 43207,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, fish-shell",
"url": null
} |
linux, fish-shell
You referenced a program (pyp) in the next line that isn't part of FiSH nor one that's bundled with macOS as standard. You can't assume that someone will know what that program does, so a note explaining what it is (and where to obtain it from) will limit the confusion. Thankfully, you seemed to only use it to increment a numerical value. Since we're no longer referencing the array's indices, we won't have to perform any arithmetic on them, but I've commented-out the modified line that now demonstrates how to perform FiSH arithmetic.
# set i1 ( math $i + 1 )
Printing information to stdout that is generated output from a function is best done with printf, which allows one to control how it is formatted. It doesn't insert anything you don't tell it to, which includes spaces and newlines. echo is convenient to evaluate variables quickly when debugging.
Using printf, we can have each $cval item printed to stdout twice, separated by a newline character and followed by a hyphen:
printf -- '-%s\n%s' $cval $cval
For example, it will output : -1
1
which might not look so useful right now. The next iteration of the loop will print starting immediately after the last printed character of the previous iteration, so the output will now look like this:-1
1-301
301
and then this:-1
1-301
301-601
601
Then close the for loop, and close the function:
end
end | {
"domain": "codereview.stackexchange",
"id": 43207,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, fish-shell",
"url": null
} |
linux, fish-shell
Calling seqn 1 300 3800 results in the following output:-1
1-301
301-601
601-901
901-1201
1201-1501
1501-1801
1801-2101
2101-2401
2401-2701
2701-3001
3001-3301
3301-3601
3601
The first and last lines are consequences of how the formatting was achieved, and can be easily rectified by iterating over all the $carr values except the first and the last. Instead, we deal with these two separately by bringing them outside of the for loop, printing the respective values immediately prior to entering and immediately after exiting the loop:
function seqn --argument first increment last
set --local carr ( seq $first $increment $last )
printf -- '%s' $carr[1]
for cval in $carr[2..-2]
# set i1 ( math $i + 1 )
printf -- '-%s\n%s' $cval $cval
end
printf -- '-%s' $carr[-1]
end
Calling seqn 1 300 3800 now outputs the desire result:1-301
301-601
601-901
901-1201
1201-1501
1501-1801
1801-2101
2101-2401
2401-2701
2701-3001
3001-3301
3301-3601
Improvements
The above function is what one would term a naive implementation, in that it is essentially the most basic formulation for the algorithm that exposes each thought process along the way towards achieving the objective. Whilst naive implementations are generally easy-to-follow and simple to understand what's happening at each line of the script, it doesn't necessarily result in the most efficient way to do something nor the one with the fewest lines of code. Which of these attributes ends up being the most important will be up to you, but you'll only have the option to choose once you know what they are.
Consider the following array defined like so:
> set A 1 2 3 4 5
Printing two copies of this list that groups them together by index is not obviously achievable without looping through them. That is, we wish to achieve the following output:
1 1 2 2 3 3 4 4 5 5
without having to iterate through the array ourselves. Here are some common things one might try:
> echo $A $A
1 2 3 4 5 1 2 3 4 5 | {
"domain": "codereview.stackexchange",
"id": 43207,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, fish-shell",
"url": null
} |
linux, fish-shell
> echo $A$A
11 21 31 41 51 12 22 32 42 52 13 23 33 43 53 14 24 34 44 54 15 25 35 45 55
> echo {$A,$A}
1 1 2 1 3 1 4 1 5 1 1 2 2 2 3 2 4 2 5 2 1 3 2 3 3 3 4 3 5 3 1 4 2 4 3 4 4 4 5 4 1 5 2 5 3 5 4 5 5 5
If you're not familiar with Cartesian Products in the context of the shell, it's worth learning about them. That said, that reference document isn't exhaustive, and doesn't contain the solution we're after, so I'll just tell you:
> echo $A{,}
1 1 2 2 3 3 4 4 5 5
This is incredibly efficient and directly relevant to the purpose of seqn. If I borrow the line from the seqn function that prints a single iteration of $carr using the printf command, namely:
printf -- '-%s\n%s' $cval $cval
and substitute the arguments with the cartesian product operating on $A, then you can see why this is useful:
> printf -- '-%s\n%s' $A{,}
-1
1-2
2-3
3-4
4-5
5
As before, we will handle the first and last items of the array separately, but this can replace the entire for loop:
function seqn --argument first increment last
set --local carr ( seq $first $increment $last )
printf -- '%s' $carr[1]
printf -- '-%s\n%s' $carr[2..-2]{,}
printf -- '-%s' $carr[-1]
end
This might not seem obvious now if printf is not familiar to you, but these can combine and simplify into a single call:
function seqn --argument first increment last
set --local carr ( seq $first $increment $last )
printf '%s-%s\n' $carr[1] $carr[2..-2]{,} $carr[-1]
end
Final Tweaks (for the obsessive)
Calling seqn is designed to output intervals (ranges) of numbers where the values of the equivalent call to seq serve to become the boundary values of these intervals. Therefore, to me, it seems like the output from the following call is incomplete:
> seqn 1 300 3800
1-301
301-601
601-901
901-1201
1201-1501
1501-1801
1801-2101
2101-2401
2401-2701
2701-3001
3001-3301
3301-3601
as I would expect the final range to include:
3601-3800 | {
"domain": "codereview.stackexchange",
"id": 43207,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, fish-shell",
"url": null
} |
linux, fish-shell
as I would expect the final range to include:
3601-3800
Perhaps you disagree, but in case you don't, the solution is a simple tweak to the call made to seq. If $increment divides exactly the arithmetic difference ($last - $first), then $last will appear as the final number in the list generated by seq. If $increment does not divide ($last - $first), then $last won't appear.
This is inconvenient since appending the value $last to the $carr array will complete the list in a lot of cases, but in instances where the increment divides the entire range, we'd have two copies of $last at the end of $carr. One way to handle this is to do a quick check to see whether we need to append a value or not:
set --local carr ( seq $first $increment $last )
[ "$carr[-1]" -ne "$last" ]
and set --append carr $last
That's a perfectly good way to do it, and it's clear what we're doing.
But I'm going to make the call to seq with the calculated value of ($last - 1) in place of $last. The resulting $carr array definitely won't contain $last, but, importantly, every other number that would have otherwise been present will still be present (I'm assuming we're dealing only with integers). Then I can append the value $last as part of the array declaration:
set --local carr ( seq $first $increment (
math $last - 1 ) ) $last
Another option is to set the -t parameter for seq, which instructs it to terminate the list with whatever string value is passed as the parameter:
set --local carr ( seq -t $last $first $increment (
math $last - 1 ) )
The reason I'm bothering with this is that it allows me to do away with declaring a variable at the function level, and create a temporary variable attached to a single command only, in this case, the printf command:
function seqn
I=( seq -t $argv[3 1 2] (
math $argv[3] - 1 )
){,} printf '%s-%s\n' $I[2..-2]
end | {
"domain": "codereview.stackexchange",
"id": 43207,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, fish-shell",
"url": null
} |
linux, fish-shell
I've replaced the named argument variables with the default $argv simply for brevity. The printf call has also been simplified a little more by moving the cartesian product so that it operates on the temporary variable at the point of declaration, which creates exactly two copies of every item in the list allowing us to do the simpler manoeuvre of omitting one value at either end.
Calling seqn 1 300 3800 now outputs:1-301
301-601
601-901
901-1201
1201-1501
1501-1801
1801-2101
2101-2401
2401-2701
2701-3001
3001-3301
3301-3601
3601-3800 | {
"domain": "codereview.stackexchange",
"id": 43207,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "linux, fish-shell",
"url": null
} |
javascript
Title: DRY on a conditional to calculate prices
Question: I have this snippet of code where I add multiple fallbacks if the price value equals a 0 (meaning that it couldn't retrieve a price from a URL)
url = StarCityController.getSearchURLForCard(cardName, cardNumber, set, foil, variantNumber, true, false);
url = url.replaceAll('★', '').replaceAll('†', '');
soup = await StarCityController.createSoupForCard(url);
price = await StarCityController.getPriceForCard(soup);
if (price === 0) {
if (!cardNumber.includes('★')) {
url = StarCityController.getSearchURLForCard(cardName, cardNumber, set, foil, variantNumber, false, false);
} else {
url = StarCityController.getSearchURLForCard(cardName, cardNumber, set, true, variantNumber, false, false);
}
url = url.replaceAll('★', '').replaceAll('†', '');
soup = await StarCityController.createSoupForCard(url);
price = await StarCityController.getPriceForCard(soup);
if (price === 0) {
if (!cardNumber.includes('★')) {
url = StarCityController.getSearchURLForCard(cardName, cardNumber, set, foil, variantNumber, false, true);
} else {
url = StarCityController.getSearchURLForCard(cardName, cardNumber, set, true, variantNumber, false, true);
}
url = url.replaceAll('★', '').replaceAll('†', '');
soup = await StarCityController.createSoupForCard(url);
price = await StarCityController.getPriceForCard(soup);
if (price === 0) {
url = StarCityController.getImageSearchURLForCard(cardName, cardNumber, set);
soup = await StarCityController.createSoupForCard(url);
price = await StarCityController.getPriceForCardInScryfall(soup, foil);
}
}
} | {
"domain": "codereview.stackexchange",
"id": 43208,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
The last if is usually my last resort if everything else fails. As you can see, there's a lot of variables in the getSearchURLForCard call, since the URL can have multiple values for a number (for example, it can have a 003 instead of a 3 or vice-versa).
How can I rewrite this in order to enforce DRY? Maybe I could put all of this in another method, but that won't solve the main problem at hand. Any suggestions are appreciated.
Answer: In situations where you have one or more "fallback" algorithms, consider refactoring each calculation into its own function. Then you can use the || operator between function calls, since you check for a zero price, which is falsey:
let price = calculatePriceA(...)
|| calculatePriceB(...)
|| calculatePriceC(...)
|| calculatePriceD(...);
This works well in cases where the arguments to each function are known ahead of time, and do not rely on values that change after attempting to calculate a price. Alternately, you can store functions in an array and loop over them until you get a price:
let calculators = [
calculatePriceA,
calculatePriceB,
calculatePriceC,
calculatePriceD
];
let price = 0;
for (let i = 0; i < calculators.length; i++) {
if (price = calculators[i](x, y, z)) {
break;
}
}
This can accommodate a dynamic list of price calculators.
If the arguments for these functions become inconsistent, consider refactoring the calculators into an array of objects, and passing most arguments to the constructor:
let calculators = [
new CalculatorA(a, b, c),
new CalculatorB(c, b, d),
new CalculatorC(d, e, f, a, g),
new CalculatorD(c, b, a)
];
for (let i = 0; i < calculators.length; i++) {
if (price = calculators[i].calculatePrice(x, y, z)) {
break;
}
} | {
"domain": "codereview.stackexchange",
"id": 43208,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
javascript
These techniques can help you reduce nested if statements, and reduce the number of times you need to check if (price == 0), but since each calculation is a little different, there is little common code between them. | {
"domain": "codereview.stackexchange",
"id": 43208,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "javascript",
"url": null
} |
python, python-3.x, programming-challenge, number-systems
Title: Python 3 number convertor that converts floats between decimal and bases 2-36
Question: This is a Python 3 script that converts any real number (ints and floats) from decimal notation to any positional number system representation with an integer base between 2 and 36 and vice versa, meaning it can convert negative fractions.
Technically it can convert any arbitrary base, but I struggle to find a way to represent the output, its output is like hexadecimal, but instead of only letters a to f, all of the English alphabet can be used, so there can be a unique symbol for all numbers up to 35.
I don't know how to represent number systems with bases higher than 36, if I continue to use strings, if I use the Greek alphabet after Latin alphabet, I can represent bases up to 60, but many Greek letters have homoglyph in Latin alphabet... And if I just use a list, it would be perfectly fine if they only represent positive integers, but here I need a list for the integral part and a list for the fractional part, and potentially a str before the first list...
The actual code that does the job is extremely simple, but I added many useless validations that slows the execution down tremendously, just so in case someone gives incorrect inputs...
Code
import re
from typing import Union
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz' | {
"domain": "codereview.stackexchange",
"id": 43209,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, programming-challenge, number-systems",
"url": null
} |
python, python-3.x, programming-challenge, number-systems
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz'
def convertfrom_decimal(number: Union[int, float], base: int=16) -> str:
if not isinstance(number, (float, int)):
raise TypeError('Argument `number` must be a numerical value (int or float)')
if not isinstance(base, int):
raise TypeError('Argument `base` must be an integer')
if not 2 <= base <= 36:
raise ValueError('This function can only support bases from 2 to 36')
negative = False
if number < 0:
negative = True
number = -number
whole = int(number)
fraction = number - whole
if whole:
integral = ''
while whole:
whole, digit = divmod(whole, base)
integral = ALPHABET[digit] + integral
else:
integral = '0'
if not fraction:
return integral if not negative else '-'+integral
fractional = ''
bits = 0
while bits < 48:
bit, fraction = divmod(fraction*base, 1.0)
fractional += ALPHABET[int(bit)]
if fraction < 2**-48:
break
bits += 1
result = integral + '.' + fractional
return result if not negative else '-'+result | {
"domain": "codereview.stackexchange",
"id": 43209,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, programming-challenge, number-systems",
"url": null
} |
python, python-3.x, programming-challenge, number-systems
def convertto_decimal(string: str, base: int=0) -> float:
if not isinstance(string, str):
raise TypeError('Argument `string` must be an instance of `str`')
if not isinstance(base, int):
raise TypeError('Argument `base` must be an instance of `int`')
if base and not 2 <= base <= 36:
raise ValueError('Argument `base` is not between 2 and 36')
if not re.match('^(\-|\+)?[0-9a-z]+(\.[0-9a-z]+)?$', string):
raise ValueError('Argument string is not a valid numerical notation supported by this function')
negative = False
if string[0] == '-':
negative = True
string = string[1:]
fraction = ''
if '.' in string:
whole, fraction = string.split('.')
else:
whole = string
indicator = max(ALPHABET.index(d) for d in string if d in ALPHABET)
if not base:
for b in (2, 8, 16, 36):
if indicator < b:
base = b
break
if indicator >= base:
raise ValueError('Argument `base` is incorrect')
#integral = int(whole, base)
integral = sum(
ALPHABET.index(d)*base**i for i, d in enumerate(whole[::-1])
)
if not fraction:
return integral if not negative else -integral
fractional = sum(
ALPHABET.index(d)*base**-(i+1) for i, d in enumerate(fraction)
)
number = integral + fractional
return number if not negative else -number
if __name__ == '__main__':
for i in range(2, 37):
print(convertfrom_decimal(3.1415926535897932, i)) | {
"domain": "codereview.stackexchange",
"id": 43209,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, programming-challenge, number-systems",
"url": null
} |
python, python-3.x, programming-challenge, number-systems
Output
11.001001000011111101101010100010001000010110100011
10.010211012222010211002111110221222020010102220122
3.021003331222202020112203
3.032322143033432411241211414143234130344233124014
3.050330051415124105232005511454424522431000231043
3.066365143203613410601052256200101122510662105012
3.1103755242102643
3.124188124074427866112818683125147474717151652050
3.141592653589793115997963468544185161590576171875
3.16150702865a484776333a98347444320a009a7420206870
3.184809493b9186459aaa3a83
3.1ac1049052a2c71005161571824ba0969c9c2497709caba9
3.1da75cda813752b70268a34a22a74bc41348ccb8c5b228a7
3.21cd1dc46c2b7ab624ee5cd3a5322906081b7e4cc8822538
3.243f6a8885a3
3.26fag579ed6gdea8g2f5a1a2386be4847dfa9c199955365a
3.29fdeh0g77186b7e590fg494559fgf1df946f3b06h5636d9
3.2d23982975gfh9b5f957e5005e7c16d3dg23bh47838i4h7i
3.2gceg9gbhj9cc1508a2e3jdf
3.2k961edi5h85d7fhkhd2idf09bjkafe8bf0513def9k2hkj3
3.32bek9a809gafkj34f0jlilchkcg9hach0d5acji5geh42gb
3.35kh9k813jk70fjjjl150i0ikg7mffmm4efak0ih8g3i0km4
3.39d911bclk3nn443
3.3dc9fine6e76llndlfjmi7k9n2fcnlh7m95927g497l0oaka
3.3higbebohjh2bh66ka19afih5lahe37b9h5ipiend7np4mjd
3.3m5q3m2dcpq63bohkl3n4gedlg4jjk1ii8g7qi8ngbeablk4
3.3r06liojplq9mr9eq1867957
3.4328n0cjqmic2nrmogpp06ff7hd864qe4kjg48db7da6hkcf
3.47d01ee07qs3an4tkttin4l91k8a7jrh1ot5gjqa431c5imf
3.4c25oe856s2t8tg5rue7psq0h3m72hd7tloa5ja67lj96li8
3.4gvml245kc
3.4m6dn4ow9qwe210nr3u0cdqkcnrbmwlh7kmfeapn9fijt38k
3.4rn5c8ianuxpep3owhg3n4m1o6r595s5kmr3djex4m1k6cph
3.4xfrgmtm53gd8tfed3xnstgi56yfaa7dvfrxe5vb5wq7qe4e
3.53i5ab8p5fc5vayqter60f6r
I have noticed that for binary I can have up to 48 fractional bits, 24 bits for quaternary, 16 bits for octal, 12 bits for hexadecimal and 9.6 bits for base-32, all other bases have precision limits under 48 bits, but interestingly ternary seems to have infinite precision...
So how is the code? Are there any areas that can be improved? | {
"domain": "codereview.stackexchange",
"id": 43209,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, programming-challenge, number-systems",
"url": null
} |
python, python-3.x, programming-challenge, number-systems
Answer: ALPHABET should be formed from ascii_letters and digits.
base having a default of 16 is kind of an odd choice? I think it would be less surprising to have no default at all and force the programmer to be explicit.
You call your validations useless but they seem fine to me (mostly). The one I would exclude is indicator. Rather than doing all of that hard work up front, it's just as good to attempt an index(d), catch an IndexError and raise ValueError(f'Digit {d} is invalid for base {base}').
Rather than hard-coding the number 36, it's best to assign that constant as len(ALPHABET) somewhere in the globals.
convertfrom_decimal (which should probably be called convert_from_decimal) has special treatment for the fractional component and integral component, which I think it shouldn't. You should just be able to get the mantissa, and then iteratively multiply and subtract until you hit a maximum number of digits or the remaining mantissa is zero.
Your use of if not re.match is a missed opportunity: the regex is not only useful as validation, but if you name and capture your groups, it can be used to parse the string as well.
index(d) is not as efficient as it could be. Rather than using the ALPHABET string opaquely, you could test to see whether the character is a letter or number and subtract accordingly, which will obviate any iteration through your ALPHABET string. | {
"domain": "codereview.stackexchange",
"id": 43209,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "python, python-3.x, programming-challenge, number-systems",
"url": null
} |
c++, performance, strings, c++20
Title: I created something much faster than a std::string
Question: I've recreated std::string in a way that might be faster.
System Features:
Much faster than std::string.
Easy to use.
It was designed as part of a large database so it is very fast and good at handling memory.
Responsive to all types of data, you can enter characters, numbers, even decimal numbers, boolean values or even lists, without the need to convert data types to a string.
It contains a system dedicated to calculating numbers and converting them into text strings, It works great with decimal numbers. see below to learn more.
All functions tested, no errors detected. | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
The reason for the speed of performance:
The reason lies in the way I handle the heap memory, I don't need to realloc memory every time the value changes, and I don't need to completely reset the object when any modification is made.
If you are interested you can check out the set() function, i have left comments that can explain this further.
Test results:
+-------------------------+--------+------+------------------------------+
|METHOD |CLASS |TIME |NOTES |
+-------------------------+--------+------+------------------------------+
|create empty |xstring |210 | |
| |string |1586 | |
+-------------------------+--------+------+------------------------------+
|create by string |xstring |1859 | |
| |string |3194 | |
+-------------------------+--------+------+------------------------------+
|create by character |xstring |1852 | |
| |string |2680 |Unavailable, used to_string() |
+-------------------------+--------+------+------------------------------+
|create by bool |xstring |1836 | |
| |string |2487 |Unavailable, used to_string() |
+-------------------------+--------+------+------------------------------+
|create by integer |xstring |2477 | |
| |string |2453 |Unavailable, used to_string() |
+-------------------------+--------+------+------------------------------+
|create by decimal |xstring |4428 | |
| |string |23053 |Unavailable, used to_string() |
+-------------------------+--------+------+------------------------------+ | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
+-------------------------+--------+------+------------------------------+
|create by same object |xstring |3750 | |
| |string |9779 | |
+-------------------------+--------+------+------------------------------+
|create by multiple |xstring |3726 | |
| |string |-- |Unavailable |
+-------------------------+--------+------+------------------------------+
|append |xstring |2426 | |
| |string |7685 | |
+-------------------------+--------+------+------------------------------+
|prepend |xstring |2593 | |
| |string |10665 |Unavailable, used insert(0,) |
+-------------------------+--------+------+------------------------------+
|insert |xstring |2574 | |
| |string |10579 | |
+-------------------------+--------+------+------------------------------+
|compare |xstring |3985 | |
| |string |8200 | |
+-------------------------+--------+------+------------------------------+
|swap |xstring |3928 | |
| |string |11579 | |
+-------------------------+--------+------+------------------------------+
|to lower |xstring |2407 | |
| |string |-- |Unavailable |
+-------------------------+--------+------+------------------------------+
|to upper |xstring |2432 | | | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
|to upper |xstring |2432 | |
| |string |-- |Unavailable |
+-------------------------+--------+------+------------------------------+
|select by index |xstring |1984 | |
| |string |3303 | |
+-------------------------+--------+------+------------------------------+
|select by char and pos |xstring |1976 | |
| |string |4138 | |
+-------------------------+--------+------+------------------------------+
|select last |xstring |1910 | |
| |string |3563 | |
+-------------------------+--------+------+------------------------------+
|pop last |xstring |2114 | |
| |string |4338 | |
+-------------------------+--------+------+------------------------------+
|pop by index |xstring |2095 | |
| |string |6591 | |
+-------------------------+--------+------+------------------------------+
|reverse |xstring |2465 | |
| |string |-- |Unavailable |
+-------------------------+--------+------+------------------------------+
|find first of |xstring |2001 | |
| |string |4446 | |
+-------------------------+--------+------+------------------------------+
|find last of |xstring |1979 | |
| |string |4199 | | | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
| |string |4199 | |
+-------------------------+--------+------+------------------------------+
|sub string |xstring |4070 | |
| |string |17287 | |
+-------------------------+--------+------+------------------------------+
|is empty |xstring |1909 | |
| |string |3262 | |
+-------------------------+--------+------+------------------------------+ | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
Test Info
OS linux, ubuntu 20.04
processor Intel(R) Core(TM) i7-6500U CPU @ 2.50GHz
memory 8064MiB System memory
Compiler g++ 11
C++ Version c++ 20
tested by valgrind, you can test with just run script and you will got same ratios
You can find the source file and test script here GitHub: xString
I have some questions :
Are there any errors that I did not notice?
Is there anything that can be done to improve performance?
Is there anything missing?
What is your opinion and what are your suggestions?
Edit: xstring.h
/*
All rights reserved: Maysara Khalid Elshewehy [github.com/xeerx]
Created on: 4 Apr 2022
Commercial use of this file is prohibited without written permission
*/
#ifndef XCPP_XSTRING_H
#define XCPP_XSTRING_H
#include <string.h> // strlen
#include <cstdlib> // calloc, realloc, free
#include <initializer_list> // initializer_list
#include <stddef.h> // size_t
#include <stdint.h> // SIZE_MAX
#include <ostream> // ostream operator
// xstring macros
#define xnpos SIZE_MAX // max size of size_t, when error, return to it
#define _xs_extra_space_ 25 // the extra space size in heap memory | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
// xstring helpers
namespace x::hlpr
{
// [INTEGER LENGTH]
#define __sig_int_len__(t) (t int src) { unsigned t int len = src < 0 ? 1 : 0; while(true) { src /= 10; if(src != 0) len ++; else return len; } }
#define __uns_int_len__(t) (unsigned t int src) { unsigned t int len = 0; while(true) { src /= 10; if(src != 0) len ++; else return len; } }
unsigned int intlen __sig_int_len__()
unsigned int uintlen __uns_int_len__()
unsigned short int sintlen __sig_int_len__(short)
unsigned short int usintlen __uns_int_len__(short)
unsigned long lintlen __sig_int_len__(long)
unsigned long ulintlen __uns_int_len__(long)
unsigned long long llintlen __sig_int_len__(long long)
unsigned long long ullintlen __uns_int_len__(long long)
// [INTEGER TO STRING]
#define __sig_int_str__(s,t) (char *ref, s src, unsigned s len = 0) { if(src == 0){ ref[0] = '0'; ref[1] = '\0'; return; } if (len == 0) len = t(src) + 1; if (src < 0) { src = src * -1; ref[0] = '-'; } len--; ref[len + 1] = '\0'; while (src > 0) { ref[len] = src % 10 + '0'; src /= 10; len--; } }
#define __uns_int_str__(s,t) (char *ref, unsigned s src, unsigned s len = 0) { if(src == 0){ ref[0] = '0'; ref[1] = '\0'; return; } if(len == 0) len = t(src) +1; len --; ref[len+1] = '\0'; while(src >= 1) { ref[len] = src % 10 + '0'; src /= 10; len --; } }
void intstr __sig_int_str__(int,intlen)
void uintstr __uns_int_str__(int ,uintlen)
void sintstr __sig_int_str__(short int,sintlen)
void usintstr __uns_int_str__(short int ,usintlen)
void lintstr __sig_int_str__(long int,lintlen)
void ulintstr __uns_int_str__(long int ,ulintlen)
void llintstr __sig_int_str__(long long int,llintlen)
void ullintstr __uns_int_str__(long long int ,ullintlen) | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
// [INTEGER MACROS]
#define __int_str_shortcut__(src,l,lfunc,sfunc) unsigned l __len = x::hlpr::lfunc(src) +1; char * __ref = new char[__len+1]; x::hlpr::sfunc(__ref,src,__len); delete [] __ref;
#define __intstr__(src) __int_str_shortcut__(src,int,intlen,intstr)
#define __uintstr__(src) __int_str_shortcut__(src,int,uintlen,uintstr)
#define __sintstr__(src) __int_str_shortcut__(src,short int,sintlen,sintstr)
#define __usintstr__(src) __int_str_shortcut__(src,short int,usintlen,usintstr)
#define __lintstr__(src) __int_str_shortcut__(src,long int,lintlen,lintstr)
#define __ulintstr__(src) __int_str_shortcut__(src,long int,ulintlen,ulintstr)
#define __llintstr__(src) __int_str_shortcut__(src,long long int,llintlen,llintstr)
#define __ullintstr__(src) __int_str_shortcut__(src,long long int,ullintlen,ullintstr) | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
// [DECIMAL LENGTH]
#define __decimal_len__(t) (t src, unsigned short int max = 6) { unsigned int len = 0, ilen = 0, i = 0; int isrc = (int)src; if(src < 0) src *= -1; if(src > 0) { ilen = intlen(isrc); src -= isrc;} while(i < max && (isrc - src) != 0) { src = src * 10; i++; len ++; } return len + ilen; }
unsigned int floatlen __decimal_len__(float)
unsigned int doublelen __decimal_len__(double)
unsigned int ldoublelen __decimal_len__(long double)
// [DECIMAL TO STRING]
#define __decimal_str__(t,lfunc) (char *ref, t src, unsigned short int max = 0, bool setmax = false) { bool neg = false; if(src < 0) { src = src * -1; neg = true; } if(src == 0) { ref[0] = '0'; ref[1] = '.'; ref[2] = '0'; ref[3] = '\0'; } int numbers = src, digit = 0, numberslen = x::hlpr::intlen(numbers), index = numberslen + 1; long pow_value = 0; unsigned int flen = x::hlpr::lfunc(src); if(numberslen > 0) flen -= numberslen; if(!max) max = flen; else if(setmax) max -= numberslen; max --; x::hlpr::intstr(ref,numbers,index); ref[index] = '.'; index ++; if(numbers == src) { ref[index] = '0'; index ++; if(neg) { unsigned int bi = index; ref[bi] = '\0'; while (index >= 0) { ref[index+1] = ref[index]; index --; } ref[0] = '-'; return bi +1; } else ref[index] = '\0'; return index; } t fraction_part = src - numbers; t tmp1 = fraction_part, tmp =0; for( int i= 1; i < max + 2; i++) { pow_value = 10; tmp = tmp1 * pow_value; digit = tmp; ref[index] = digit +48; tmp1 = tmp - digit; index ++; } int temp_index = index -1; while(temp_index >= 0) { if(ref[temp_index] == '0') { ref[temp_index] = '\0'; index --; } else break; temp_index --; } temp_index = index -1; while(temp_index >= 0) { if(ref[temp_index] == ref[temp_index-1]) { ref[temp_index] = '\0'; index --; } else break; temp_index --; } if(neg) { unsigned int bi = index; ref[bi] = '\0'; while (index >= 0) { ref[index+1] = ref[index]; index --; } ref[0] = '-'; return bi+1; } else ref[index] = '\0'; return index;} | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
unsigned int floatstr __decimal_str__(float,floatlen)
unsigned int doublestr __decimal_str__(double,doublelen)
unsigned int ldoublestr __decimal_str__(long double,ldoublelen) | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
// [DECIMAL MACROS]
#define __decimal_str_shortcut__(src,lfunc,sfunc,max) unsigned short int __len = x::hlpr::lfunc(src,max) +1; char * __ref = new char[__len+4];__len = x::hlpr::sfunc(__ref,src,__len,true); delete [] __ref;
#define __floatstr__(src) __decimal_str_shortcut__(src,floatlen,floatstr,max)
#define __doublestr__(src) __decimal_str_shortcut__(src,doublelen,doublestr,max)
#define __ldoublestr__(src) __decimal_str_shortcut__(src,ldoublelen,ldoublestr,max)
}
// xstring class
namespace x
{
// some variables used to return to error
char xstr_null_char = '\0';
class xstring
{
public:
// data
char *src = nullptr; // pointer to character array wich contains to value of object
size_t len = 0; // length of src, zero means empty
size_t siz = 0; // size of src in heap memory
// constructor -> default empty
xstring () { }
xstring (const char *ref, size_t rlen = 0) { set(ref,rlen); }
xstring (char ref) { set(ref); }
xstring (bool ref) { set(ref); }
xstring ( int ref) { set(ref); }
xstring (unsigned int ref) { set(ref); } | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
xstring (short int ref) { set(ref); }
xstring (unsigned short int ref) { set(ref); }
xstring (long int ref) { set(ref); }
xstring (unsigned long int ref) { set(ref); }
xstring (long long int ref) { set(ref); }
xstring (unsigned long long int ref) { set(ref); }
xstring (float ref,unsigned short max = 1) { set(ref,max); }
xstring (double ref,unsigned short max = 1) { set(ref,max); }
xstring (long double ref,unsigned short max = 1) { set(ref,max); }
xstring (xstring &ref) { set(ref); }
xstring (const xstring &ref) { set(ref); }
template <typename T>
xstring (std::initializer_list<T> ref) { for(auto i:ref) append(i); }
// set
bool set (const char *ref, size_t rlen);
bool set (char ref) { char __ref[] = {ref}; return set(__ref, 1); }
bool set (bool ref) { return set(ref ? "1" : "0", 1); } | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
bool set ( int ref) { __intstr__ (ref) return set(__ref, __len); }
bool set (unsigned int ref) { __uintstr__ (ref) return set(__ref, __len); }
bool set (short int ref) { __sintstr__ (ref) return set(__ref, __len); }
bool set (unsigned short int ref) { __usintstr__ (ref) return set(__ref, __len); }
bool set (long int ref) { __lintstr__ (ref) return set(__ref, __len); }
bool set (unsigned long int ref) { __ulintstr__ (ref) return set(__ref, __len); }
bool set (long long int ref) { __llintstr__ (ref) return set(__ref, __len); }
bool set (unsigned long long int ref) { __ullintstr__ (ref) return set(__ref, __len); }
bool set (float ref,unsigned short max = 1) { __floatstr__ (ref) return set(__ref, __len); }
bool set (double ref,unsigned short max = 1) { __doublestr__ (ref) return set(__ref, __len); }
bool set (long double ref,unsigned short max = 1) { __ldoublestr__ (ref) return set(__ref, __len); }
bool set (xstring &ref) { if(&ref != this) return set(ref.src, ref.len); else return false; }
bool set (const xstring &ref) { if(&ref != this) return set(ref.src, ref.len); else return false; }
template <typename T>
bool set (std::initializer_list<T> ref) { reset(); for(auto i:ref) if(!append(i)) return false; return true; } | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
template <typename T>
bool operator = (T ref) { return set(ref); }
template <typename T>
bool operator = (std::initializer_list<T> ref) { return set(ref); }
// append
bool append (const char *ref, size_t rlen);
bool append (char ref) { char __ref[] = {ref}; return append(__ref, 1); }
bool append (bool ref) { return append(ref ? "1" : "0", 1); }
bool append ( int ref) { __intstr__ (ref) return append(__ref, __len); }
bool append (unsigned int ref) { __uintstr__ (ref) return append(__ref, __len); }
bool append (short int ref) { __sintstr__ (ref) return append(__ref, __len); }
bool append (unsigned short int ref) { __usintstr__ (ref) return append(__ref, __len); }
bool append (long int ref) { __lintstr__ (ref) return append(__ref, __len); }
bool append (unsigned long int ref) { __ulintstr__ (ref) return append(__ref, __len); }
bool append (long long int ref) { __llintstr__ (ref) return append(__ref, __len); }
bool append (unsigned long long int ref) { __ullintstr__ (ref) return append(__ref, __len); } | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
bool append (float ref,unsigned short max = 1) { __floatstr__ (ref) return append(__ref, __len); }
bool append (double ref,unsigned short max = 1) { __doublestr__ (ref) return append(__ref, __len); }
bool append (long double ref,unsigned short max = 1) { __ldoublestr__ (ref) return append(__ref, __len); }
bool append (xstring &ref) { if(&ref != this) return append(ref.src, ref.len); else return false; }
bool append (const xstring &ref) { if(&ref != this) return append(ref.src, ref.len); else return false; }
template <typename T>
bool append (std::initializer_list<T> ref) { for(auto i:ref) if(!append(i)) return false; return true; }
template <typename T>
bool operator += (T ref) { return append(ref); }
template <typename T>
bool operator += (std::initializer_list<T> ref) { return append(ref); }
// prepend
bool prepend (const char *ref, size_t rlen);
bool prepend (char ref) { char __ref[] = {ref}; return prepend(__ref, 1); }
bool prepend (bool ref) { return prepend(ref ? "1" : "0", 1); }
bool prepend ( int ref) { __intstr__ (ref) return prepend(__ref, __len); }
bool prepend (unsigned int ref) { __uintstr__ (ref) return prepend(__ref, __len); } | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
bool prepend (short int ref) { __sintstr__ (ref) return prepend(__ref, __len); }
bool prepend (unsigned short int ref) { __usintstr__ (ref) return prepend(__ref, __len); }
bool prepend (long int ref) { __lintstr__ (ref) return prepend(__ref, __len); }
bool prepend (unsigned long int ref) { __ulintstr__ (ref) return prepend(__ref, __len); }
bool prepend (long long int ref) { __llintstr__ (ref) return prepend(__ref, __len); }
bool prepend (unsigned long long int ref) { __ullintstr__ (ref) return prepend(__ref, __len); }
bool prepend (float ref,unsigned short max = 1) { __floatstr__ (ref) return prepend(__ref, __len); }
bool prepend (double ref,unsigned short max = 1) { __doublestr__ (ref) return prepend(__ref, __len); }
bool prepend (long double ref,unsigned short max = 1) { __ldoublestr__ (ref) return prepend(__ref, __len); }
bool prepend (xstring &ref) { if(&ref != this) return prepend(ref.src, ref.len); else return false; }
bool prepend (const xstring &ref) { if(&ref != this) return prepend(ref.src, ref.len); else return false; }
template <typename T>
bool prepend (std::initializer_list<T> ref) { for(auto i:ref) if(!prepend(i)) return false; return true; }
template <typename T>
bool operator |= (T ref) { return prepend(ref); }
template <typename T>
bool operator |= (std::initializer_list<T> ref) { return prepend(ref); } | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
// print
friend std::ostream &operator<<(std::ostream &os, const xstring &s) { os << (s.src ? s.src : ""); return (os); }
// insert
bool insert (size_t pos, const char *ref, size_t rlen);
bool insert (size_t pos, char ref) { char __ref[] = {ref}; return insert(pos,__ref, 1); } | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
// compare between two strings
bool compare(const char *ref) { return strcmp(src,ref) == 0; }
bool compare(xstring& ref) { return compare(ref.src); }
bool compare(const xstring& ref) { return compare(ref.src); }
bool compare( char ref) { char __ref[] = {ref}; return compare(__ref); }
bool operator == (const char *ref) { return compare(ref) == true; }
bool operator == (xstring& ref) { return compare(ref) == true; }
bool operator == (const xstring& ref) { return compare(ref) == true; }
bool operator == ( char ref) { return compare(ref) == true; }
// no need in C++ 20
// bool operator != (const char *ref) { return compare(ref) == false; }
// bool operator != (xstring& ref) { return compare(ref) == false; }
// bool operator != (const xstring& ref) { return compare(ref) == false; }
// bool operator != ( char ref) { return compare(ref) == false; }
// swap value,len,size between two string objects
void swap(xstring &ref)
{
char *tmp_src = src;
size_t tmp_len = len;
size_t tmp_siz = siz;
src = ref.src;
len = ref.len;
siz = ref.siz; | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
ref.src = tmp_src;
ref.len = tmp_len;
ref.siz = tmp_siz;
}
// convert src characters to lower case
void to_lower()
{
size_t i = 0;
while(src[i] != '\0') { src[i] = std::tolower(src[i]); i++; }
}
// convert src characters to upper case
void to_upper()
{
size_t i = 0;
while(src[i] != '\0') { src[i] = std::toupper(src[i]); i++; }
}
// select character by index, return xstr_null_char if not found
char& getChar(size_t ref)
{
if(ref > len) return xstr_null_char;
return src[ref];
}
char& operator[](size_t ref) { return getChar(ref); }
// select index by value, start from position, return xnpos if not found
size_t getIndex(char ref, size_t pos = 0)
{
if(pos > len) return xnpos;
size_t counter = pos;
while(counter < len)
{
if(src[counter] == ref) return counter;
counter ++;
}
return xnpos;
}
// get last character
char& getLast() { return src[len-1]; }
// remove from value by index
bool pop(size_t pos = 0, size_t max = 1)
{
if(pos >= len) return false;
if(max > len || max == 0) max = len;
memmove(&src[pos], &src[pos + max], len - pos - 1);
src[len - 1] = '\0';
len --;
return true;
}
// remove last character using pop(len-1)
bool pop_last() { return pop(len-1); } | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
c++, performance, strings, c++20
// remove last character using pop(len-1)
bool pop_last() { return pop(len-1); }
// reverse characters
void reverse()
{
char *tmp = new char[len];
size_t count = len;
size_t count_src = 0;
while(count > 0)
{
tmp[count-1] = src[count_src];
count --;
count_src ++;
}
tmp[len] = '\0';
memcpy(src,tmp,len+1);
delete [] tmp;
}
// check if value is empty by check if length equals zero
bool empty() { return len == 0; }
// find first matched character in string, start from begin + pos, if failed return to xnpos
size_t first_of(char ref, size_t pos = 0)
{
if(pos >= len) return xnpos;
while( src[pos]!=ref && pos < len) pos++;
return pos == len ? xnpos : pos;
}
// find last matched character in string, start from end - pos, if failed return to xnpos
size_t last_of (char ref, size_t pos = 0)
{
if(pos >= len) return xnpos;
pos = len - pos -1;
while(src[pos]!=ref && pos > 0) pos--;
if(src[pos] == ref) return pos; else return xnpos;
}
// cut string from [start] to [end] and set to ref
bool sub(xstring &ref, size_t start = 0, size_t end = 0)
{
if(start >= len) start = len -1;
if(start == end) return false;
if(end == 0 || end >= len) end = len;
size_t llen = end - start;
char *res = new char[llen+1];
size_t pos = 0;
while(start < end)
{
res[pos] = src[start];
start ++;
pos ++;
}
res[pos] = '\0';
ref.set(res, llen+1);
delete [] res;
return true;
} | {
"domain": "codereview.stackexchange",
"id": 43210,
"lm_label": null,
"lm_name": null,
"lm_q1_score": null,
"lm_q1q2_score": null,
"lm_q2_score": null,
"openwebmath_perplexity": null,
"openwebmath_score": null,
"tags": "c++, performance, strings, c++20",
"url": null
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.