mysql – Fastest way to find which strings in an array are NOT present in a column

I am searching through MySQL rows in yii. Let’s say I have an array of strings

$fruits=array("apple", "banana","cherry","date");

I want to search in a db that looks like this:

id  name    
1   apple   
2   banana 

And I want it to return

array("cherry",'date')

What’s the best way to do this? Is there a Yii-specific way to do this? I was going to do it the caveman way where I get all of the names into a php array and then do foreach loop on $fruits but I think there must be a smarter way.

beginner – Extracting items from comma/semicolon-delimited strings, discarding parts after a hyphen

New Scala dev here. Is there a more idiomatic or efficient way to accomplish this in Scala?

Given a list of the following strings, I need to obtain the unique ‘main parts’ once any parts including and after a “-” have been removed.

The output should be a list of sorted strings. Also note both “;” and “,” have been used as separators.

Input:

val data: List(String) = List(
  "W22; O21; B112-WX00BK; G211; B112-WI00BK; G11",
  "W22; K122l; B112-WI00BK; O21; B112-WX00BK; G211",
  "W21, V32",
  "W21, N722",
  "S133-VU3150; S133-SU3150; R22-VK3150; R123-VH3"
)   

Desired Output:

List(
    B112 G11 G211 O21 W22,
    B112 G211 K122l O21 W22,
    V32 W21,
    N722 W21,
    R123 R22 S133
)

My solution:

def process(input: String): String =
    input.split(" ").map(word => {
        if (word contains "-")
            word.take(word.indexOf("-"))
        else word
        .replace(";", "").replace(",","")}).toSet.toList.sorted.mkString(" ")

val result: List(String) = data.map(process(_))

hash map – Is there a more idiomatic way to process these strings?

New Scala dev here:

Is there a more idiomatic or efficient way to accomplish this in Scala?

Given a list of the following strings, I need to obtain the unique ‘main parts’ once any parts including and after a “-” have been removed.

The output should be a list of sorted strings. Also note both “;” and “,” have been used as separators.

Input:

val data: List(String) = List(
  "W22; O21; B112-WX00BK; G211; B112-WI00BK; G11",
  "W22; K122l; B112-WI00BK; O21; B112-WX00BK; G211",
  "W21, V32",
  "W21, N722",
  "S133-VU3150; S133-SU3150; R22-VK3150; R123-VH3"
)   

Desired Output:

List(
    B112 G11 G211 O21 W22,
    B112 G211 K122l O21 W22,
    V32 W21,
    N722 W21,
    R123 R22 S133
)

My solution:

def process(input: String): String =
    input.split(" ").map(word => {
        if (word contains "-")
            word.take(word.indexOf("-"))
        else word
        .replace(";", "").replace(",","")}).toSet.toList.sorted.mkString(" ")

val result: List(String) = data.map(process(_))

Rust: lazy_static the strings from evdev codes

short_key_name is a &str that was borrowed from key_name, a String allocated inside the loop and which will be dropped at the end of each loop iteration. Thus, it is not a &'static str.

You can use Box::leak to create an allocation that will stick around for the rest of the life of the program. (This is reasonable for lazy static initialization, but other uses can easily create a memory leak, as the name suggests!)

let short_key_name = &*Box::leak(Box::<str>::from(short_key_name));
map.insert(code, short_key_name);

This

  1. copies the characters of the &str into a Box<str>,
  2. forgets about the existence of the box (so it is never deallocated) and creates an &'static mut str to its contents, and
  3. converts the &'static mut str to an &'static str, matching the type needed for the HashMap.

Do not use Box::leak for any code that runs more than once! As the name says, it leaks!

external keyboard – manipulating character strings communicated over Bluetooth

I successfully installed a Bluetooth Keyboard Emulator for an Android device – it has keyboard and mouse control that works nicely.
I wonder if there is a way to “break” the app to get access to the character strings that are communicated from the Android device to the notebook, via the Bluetooth link, to support manipulation or feeding “synthetic” character strings to the notebook.

I need to extract strings from a cell in google sheets.. I’m trying to use the rexectextrac function, but strings are separated with “”

This is an example of the information i get when reading a QR

{"ver":1,"date":"2021-07-07","name":123456,"line":12]}

What I need to extract is

2021-07-07
123456
12

Name length is not always the same.

Operação com Strings C

Esse programa tem o objetivo de substituir as letras minúsculas por maiúsculas.
Após executar o programa, ele pede o input mas trava logo depois e não imprime nada. Não acontece nenhum erro na compilação.


void maiusculiza(char *STRING, int N){
    int i=0;
    char string(128);

    for(i=0; i<128; i++){
        if( (int)string(i) >= 97 && (int)string(i) <= 122){

                (int)string(i) = (int)string(i) - 32; 
        }else{
            continue;
        } 
    }
}

void main(){


int i=0;
char string(128);
fgets(string, 128, stdin);

while(string(i)!=''){
    maiusculiza(string, i);
}

int j=0;
for(j=0; j<=i; j++){
    printf("%c (%d)n", string(j), string(j));
}


}

c# – Concatenating two possibly null strings with a separator

I have two strings (aggregatePath and pathFromParent), either of which might be null or an empty string. I want to concatenate the two strings with a separator only if neither is null or empty. This is what I’ve ended up with:

FullPath =
    aggregatePath +
    aggregatePath is not (null or "") && pathFromParent is not (null or "") ? "." : "" +
    pathFromParent;

but it seems overly complex for what I’m trying to do.

How can I better clarify the intent of this code?

I’m not asking about performance. I’ve just come back to this code after a while, and it took me a few moments to figure out the intent. Is there perhaps some better idiom for this?

Using C# 9.

strings – Replace n or all occurrences of substring in C

I wrote this code as an answer to a question. But I’d like you to have a look at it. This post is basically a copy of the answer I posted

The code does no error checking. It assumes that the output buffer exists and is big enough and that src, orig and new are valid strings. The headers needed:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdint.h>

The main replace function

// Replace the first occurrence of orig in src with new and write result to dest
// Return pointer to first character after the end of first match in src and
// NULL if no match
const char *replace(char *dest, const char *src,
            const char *orig, const char *new) {
    char *ptr = strstr(src, orig); // First match

    // If no match, we want dest to contain a copy of src
    if(!ptr) {
        strcpy(dest, src);
        return NULL;
    }

    const ptrdiff_t offset = ptr - src; // Calculate offset
    const int origlen = strlen(orig);
    
    strncpy(dest, src, offset); // Copy everything before match
    strcpy(&dest(offset), new); // Copy replacement
    strcpy(&dest(offset + strlen(new)), &src(offset + origlen)); // Copy rest

    return src + offset + origlen;
}

Then we just add a function to handle N occurrences

// Replace maximum n occurrences. Stops when no more matches.
// Returns number of replacements
size_t replaceN(char *dest, const char *src, const char *orig, 
                const char *new, size_t n) {
    size_t ret = 0;

    // Maybe an unnecessary optimization to avoid multiple calls in 
    // loop, but it also adds clarity
    const int newlen = strlen(new);
    const int origlen = strlen(orig);
    
    do {
        const char *ptr = replace(dest, src, orig, new); // Replace

        if(!ptr) return ret; // Quit if no more matches

        // Length of the part of src before first match
        const ptrdiff_t offset = ptr - src;
    
        src = ptr; // Move src past what we have already copied.
    
        ret++;

        dest += offset - origlen + newlen; // Advance pointer to dest to the end

    } while(n > ret);

    return ret;
}

And a simple wrapper for all occurrences. Note that it’s safe to use SIZE_MAX here, because there will never be more occurrences than that.

// Replace all. Returns the number of replacements, because why not?
size_t replaceAll(char *dest, const char *src, const char *orig, const char *new) {
    return replaceN(dest, src, orig, new, SIZE_MAX); 
}

It’s easy to write a wrapper for the allocation. We borrow some code from https://stackoverflow.com/q/9052490/6699433

size_t countOccurrences(const char *str, const char *substr) {
    size_t count = 0;

    while((str = strstr(str, substr)) != NULL) {
       count++;
       str++; // We're standing at the match, so we need to advance
    }

    return count;
}

Then some code to calculate size and allocate a buffer

// Allocate a buffer big enough to hold src with n replacements 
// of orig to new
char *allocateBuffer(const char *src, const char *orig, 
                     const char *new, size_t n) {
    return malloc(strlen(src) + 
                  n * (strlen(new) - strlen(orig)) +
                  1 // Remember the zero terminator
                 );
}

And the two final functions

// Allocates a buffer and replaces max n occurrences of orig with new and
// writes it to the allocated buffer.
// Returns the buffer and NULL if allocation failed
char *replaceNAndAllocate(const char *src, const char *orig, 
                          const char *new, size_t n) {
    const size_t count = countOccurrences(src, orig);

    n = n < count ? n : count; // Min of n and count

    char *buf = allocateBuffer(src, orig, new, n);

    if(!buf) return NULL;

    replaceN(buf, src, orig, new, n);

    return buf;
}

// Allocates a buffer and replaces all occurrences of orig with new and
// writes it to the allocated buffer.
// Returns the buffer and NULL if allocation failed
char *replaceAllAndAllocate(const char *src, const char *orig, const char *new) {
    return replaceNAndAllocate(src, orig, new, SIZE_MAX);
}

And finally, a simple main with a test with multiple occurrences and with original string being a substring of replacement string:

int main(void) {
    char src() = "!!!asdf!!!asdf!!!asdf!!!asdf!!!";
    char orig() = "asdf";
    char new() = "asdfaaaaaaaaasdf";
    
    puts(replaceAllAndAllocate(src, orig, new));
}

No warnings with -Wall -Wextra -pedantic and the output is:

$ ./a.out 
!!!asdfaaaaaaaaasdf!!!asdfaaaaaaaaasdf!!!asdfaaaaaaaaasdf!!!asdfaaaaaaaaasdf!!!

Removing rows containing improperly-formatted email strings in Google Sheets

Google Sheet doesn’t include a built-in feature to remove rows having “invalidad data”, in Google Sheets the “data validation” is done by cell and this prevent to enter a invalid value or marks the cell with a red triangle in the top-right corner. Removing rows with “invalid data” might be done, manually or automatically by using an add-on, Google Apps Script, the Sheets API.

If you don’t to use a add-on, Google Apps Script or the Sheets API, here is one option:

  1. add a column with formula to return certain value for rows to be deleted
  2. apply a filter to show only the rows to be deleted
  3. delete the rows
  4. remove the filter

Here is another option:

Use a formula to return only the rows that you want to keep. For this you might use FILTER or QUERY functions. If you don’t want to keep the source data, the do a copy-paste as value only first, then delete the source data.