Operadores AND, XOR, OR em expressões regulares [fechada]

Estou querendo fazer um WebScrapping ou Crawler não sei o nome certo que se da, que vai até o site do planalto, pega o texto de uma lei e o separa artigo por artigo, inciso por inciso, alinea por alinea e assim vai.
Eu consegui montar o código que cópia o texto da lei usando Curl e já tenho o texto todo dentro da minha string.
O meu problema e que quero estruturar o texto, conforme os padrões que eu tenho(existe um padrão para artigo, um padrão de texto para inciso, um padrão de texto para as alienas e por assim vai).
Eu gostaria de saber se alguém consegue me dar uma ideia de como fazer isto.

Obs.: Todo o código está em PHP.

python 3.x – Convert hex to base64 and then fixed XOR

I’ve seen on the site questions where too simple tasks can be grouped into one.

Here are Challenge 1 & 2 from Crypto Challenge Set 1 in Python.
Any suggestions?

the_hex = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d"

base64_table = {
    'A': '000000',
    'B': '000001',
    'C': '000010',
    'D': '000011',
    'E': '000100',
    'F': '000101',
    'G': '000110',
    'H': '000111',
    'I': '001000',
    'J': '001001',
    'K': '001010',
    'L': '001011',
    'M': '001100',
    'N': '001101',
    'O': '001110',
    'P': '001111',
    'Q': '010000',
    'R': '010001',
    'S': '010010',
    'T': '010011',
    'U': '010100',
    'V': '010101',
    'W': '010110',
    'X': '010111',
    'Y': '011000',
    'Z': '011001',
    'a': '011010',
    'b': '011011',
    'c': '011100',
    'd': '011101',
    'e': '011110',
    'f': '011111',
    'g': '100000',
    'h': '100001',
    'i': '100010',
    'j': '100011',
    'k': '100100',
    'l': '100101',
    'm': '100110',
    'n': '100111',
    'o': '101000',
    'p': '101001',
    'q': '101010',
    'r': '101011',
    's': '101100',
    't': '101101',
    'u': '101110',
    'v': '101111',
    'w': '110000',
    'x': '110001',
    'y': '110010',
    'z': '110011',
    '0': '110100',
    '1': '110101',
    '2': '110110',
    '3': '110111',
    '4': '111000',
    '5': '111001',
    '6': '111010',
    '7': '111011',
    '8': '111100',
    '9': '111101',
    '+': '111110',
    '/': '111111'

hex2bin_table = {
    '0': '0000',
    '1': '0001',
    '2': '0010',
    '3': '0011',
    '4': '0100',
    '5': '0101',
    '6': '0110',
    '7': '0111',
    '8': '1000',
    '9': '1001',
    'a': '1010',
    'b': '1011',
    'c': '1100',
    'd': '1101',
    'e': '1110',
    'f': '1111'

def hex_to_base64(the_hex):
    hex_in_bin = ''

    for c in the_hex:
        # to_ascii = ord(c)  # if it's text to base64
        # print(c, to_ascii, bin(to_ascii)(2:).zfill(8), hex2bin_table(c))
        # hex_in_bin += bin(to_ascii)(2:).zfill(8)
        hex_in_bin += hex2bin_table(c)

    # switch keys and values only for unique values
    reversed_table = dict(zip(base64_table.values(), base64_table.keys()))

    final = ""
    for c in range(0, len(hex_in_bin), 6):
        x = hex_in_bin(c:c + 6)

        if len(x) == 6:
            final += reversed_table(x)
            # pad with 0s to 6
            final += reversed_table(x.ljust(6, '0'))

    len_to_fill_final = 0
    if len(the_hex) % 3 != 0:
        # see Output padding from wiki, base64
        if len(final) % 4 != 0:
            len_to_fill_final = len(final)
            while len_to_fill_final % 4 != 0:
                len_to_fill_final += 1

    return final.ljust(len_to_fill_final, "=")


hex1 = '1c0111001f010100061a024b53535009181c'
hex2 = '686974207468652062756c6c277320657965'
expected_result = '746865206b696420646f6e277420706c6179'

# hex to bin
def hex_2_bin(hex_string):
    hex2bin_temp = ""
    for c in hex_string:
        hex2bin_temp += hex2bin_table(c)

    return hex2bin_temp

hex2bin_temp1 = hex_2_bin(hex1)
hex2bin_temp2 = hex_2_bin(hex2)

len_hex1 = len(hex2bin_temp1)
len_hex2 = len(hex2bin_temp2)

xored_binary = ""
for index in range(len_hex1):
    a = int(hex2bin_temp1(index))
    b = int(hex2bin_temp2(index))
    c = a ^ b
    xored_binary = "".join((xored_binary, str(c)))

# again convert keys to values for hex to bin table
reversed_bin_table = dict(zip(hex2bin_table.values(), hex2bin_table.keys()))
finale = ""
for x in range(0, len(xored_binary), 4):
    h = reversed_bin_table(xored_binary(x:x + 4))
    finale = "".join((finale, h))


complexity theory – Reduction from MAX PLANAR XOR 2-SAT to PLANAR WEIGHTED MAX-CUT

Can anyone walk me through this reduction?


I just can’t seem to wrap my head around it. I’m missing some line of reasoning or misreading something.

I see the reduction if the variables are separable. Simply, create a vertex for each literal and connect each positive and negative literal with an edge weighted greater then the number clauses. Add an edge for each clause of weight one. The number of edges in the max cut correspond with max number of clauses that make the formula satisfiable. Similarly, this reduction works if the formula is monotone. The only difference is the literals don’t have to be divided by an edge.

The reduction in the text finds the cut of maximized non-monotone clauses and minimized monotone clauses. I’m not able to see how this gives the maximum satisfiable clauses. If anyone can clarify this problem or even give me a working example I would greatly appreciate it. Thanks.

programming – XOR combination between the bits of a string

Given an integer n, we can construct $2^n$ strings of length n. We can take the first element for each of these strings and create a list. In total ‘n’ such lists are possible. But now I need to create lists that are the XOR combinations of the n lists created. If n is 3 and abc is the string then I need to calculate a$oplus$b, a$oplus$c, c$oplus$b, a$oplus$b$oplus$c. How do I do this for a general n?

Here’s the code so far…

n = 4; s = Tuples[{0, 1}, n]; a = Table[s[[i, j]], {j, 1, n}, {i, 1, 2^n}]

a gives the first four indices of all the strings. Now I need to calculate all the XOR combinations possible between these four lists.

rust – single byte xor decryption code

I’ve recently started learning rust and doing cryptopals as exercise.
I coded a program that decrypts single xor cypher. The algorithm I came up with is very simple and probably not efficient, but I would like more emphasis on rust philosophy and syntax

extern crate hex;
use std::collections::HashMap;

fn main() {
    let ciphertext = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736";
    let ciphertext_bytes = hex::decode(ciphertext).unwrap();
    let xor_key = find_xor_key(&ciphertext_bytes);
    println!("{}", ciphertext_bytes.iter().map(|x|(x^xor_key) as char ).collect::<String>());

fn find_xor_key(ciphertext: &Vec<u8>) -> u8{

    let mut max_score = 0;
    let mut best_key = 0;
    for xor_key in 1..255{
        let xored_vec = ciphertext.iter().map(|x|x^xor_key).collect(); 
        let score = get_score(xored_vec);
        if score > max_score{
            max_score = score;
            best_key = xor_key;
    println!("{}", max_score);

fn get_score(text: Vec<u8>) -> u8
    let ideal_frequencies: HashMap<char, f32> = (
('E', 11.1607),
('M', 3.0129),
('A', 8.4966),
('H', 3.0034),
('R', 7.5809),
('G', 2.4705),
('I', 7.5448),
('B', 2.0720),
('O', 7.1635),
('F', 1.8121),
('T', 6.9509),
('Y', 1.7779),
('N', 6.6544),
('W', 1.2899),
('S', 5.7351),
('K', 1.1016),
('L', 5.4893),
('V', 1.0074),
('C', 4.5388),
('X', 0.2902),
('U', 3.6308),
('Z', 0.2722),
('D', 3.3844),
('J', 0.1965),
('P', 3.1671),
('Q', 0.1962),

    for byte in text.clone(){
        let char_rep: char =  byte as char;
        if !char_rep.is_ascii(){
            return 0;
    let mut score = 1;
    let chars: Vec<char> = text.iter().cloned().map(|x|x as char).collect();
    let frequencies: HashMap<char, f32> = calculate_frequencies(&chars.into_iter().collect::<String>()); 

    for (letter, frequency) in &frequencies{
        if ideal_frequencies.contains_key(&letter) && //already checked here that it exists in the hashmap
        f32::abs(frequency - ideal_frequencies.get(&letter).unwrap()) <= 10.0{
            score += 1;

fn calculate_frequencies(text: &str) ->HashMap<char, f32>{

    let mut frequencies: HashMap<char, f32> = HashMap::new();
    let mut letter_counts:HashMap<char, i32> = HashMap::new();
    let text_upper = text.to_ascii_uppercase();
    for c in text_upper.chars(){
        let count = letter_counts.entry(c).or_insert(0);
        *count += 1;        
    for (c, count) in letter_counts{
        frequencies.entry(c).or_insert(count as f32 / text_upper.len() as f32 * 100.0);

algorithm – XOR linked list implementation – Follow Up (2)

This question is a follow up (2) question to the XOR linked list implementation.XOR linked list implementation – Follow Up

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

struct StNode {
    int value;
    uintptr_t both;
typedef struct StNode StHexNode;

StHexNode *add(StHexNode *lastNode, int value)
    StHexNode *newNode = malloc(sizeof *newNode);
    newNode->value = value;
    //latest node's (both)=pointer value pointing previous node:
    newNode->both = (uintptr_t)lastNode; 
    //calculating previous node (both):
    lastNode->both = (uintptr_t)newNode ^ lastNode->both;
    return newNode;

StHexNode *get(StHexNode *headNode, unsigned int index)
    StHexNode *prevNode;
    StHexNode *currNode;
    uintptr_t tmp;
    if(index == 0)
        return headNode;
    //cur=1, prev=0
    currNode = (struct StNode *) ((headNode->both) ^ 0);
    prevNode = headNode;
    for(int i=2; i<=index; i++)
        tmp = (uintptr_t)prevNode;
        prevNode = currNode;
        currNode = (struct StNode *) (currNode->both ^ tmp);
    return currNode;

int free_list(StHexNode *headNode)
    StHexNode *prevNode;
    StHexNode *currNode;
    uintptr_t tmp;
    int ctr=0;
    //case: there is a only head node in the list
    if(headNode->both == 0) 
        return ++ctr;
    //prev=head, curr=second_node
    currNode = (struct StNode *) ((headNode->both) ^ 0);
    prevNode = headNode;
    while(currNode->both != (uintptr_t)prevNode)
        tmp = (uintptr_t)prevNode;
        prevNode = currNode;
        currNode = (struct StNode *) (currNode->both ^ tmp);
    //last node
    return ctr;

int main(void) 
    unsigned int i;
    //I named first node as headNode, and last node as tailNode
    //create head node with both=0 since there is no previous node to it
    StHexNode *headNode = malloc(sizeof *headNode);
    StHexNode *tailNode = headNode; //last node pointer in the list
    //lets add 100 nodes after head
    //special handling of both value at head node
    for(headNode->both = 0, i=100; i<200; i++)
        tailNode = add(tailNode, i);
        //printf("last node value:%dn", tailNode->value);
    //get index=50 node value
    StHexNode *iNode = get(headNode, 50);
    printf( "result: %dn",  iNode->value);
    //free memory
    printf("we released %d listn", free_list(headNode));

c – XOR linked list implementation

I am trying to resolve below question in order to prepare for an interview xD

An XOR linked list is a more memory efficient doubly linked list.
Instead of each node holding next and prev fields, it holds a field
named both, which is an XOR of the next node and the previous node.
Implement an XOR linked list; it has an add(element) which adds the
element to the end, and a get(index) which returns the node at

Please suggest how this implementation can be improved. Thank you in prior.

#include <stdio.h>
#include <stdlib.h>

typedef struct {
    int value;
    long both;
} StNode; 
typedef StNode *pStNode;

pStNode add(pStNode lastNode, int value)
    pStNode newNode = (StNode *) malloc(sizeof(StNode));
    newNode->value = value;
    //(both)=value of previous node pointer if it is last node
    newNode->both = (long)lastNode; 
    //calculating previous node (both) value
    lastNode->both = (long)newNode ^ lastNode->both;
    return newNode;

pStNode get(pStNode headNode, int index)
    pStNode prevNode;
    pStNode currNode;
    long tmp;
    //special handling
    //case: cur=1, prev=0
    //we have set previous node of head node value to be 0 manually
    currNode = (StNode *) ((headNode->both) ^ 0);
    prevNode = headNode;
    //skim through linked list
    for(int i=2; i<=index; i++)
        tmp = (long)prevNode;
        prevNode = currNode;
        currNode = (StNode *)(currNode->both ^ tmp);
    return currNode;

int main() {  
    //I named first node as headNode, and last node as tailNode
    //create head node with both=0 since there is no previous node to it
    pStNode headNode = (StNode *) malloc(sizeof(StNode));
    headNode->both = 0; 
    headNode->value = 2;
    //assign pointers
    pStNode tailNode = headNode;
    //lets add 10 nodes after head, and assign values
    for(int i=3; i<13; i++)
        tailNode = add(tailNode, i);
    //get node value where index=3
    pStNode iNode = get(headNode, 3);
    printf( "result: %dn",  iNode->value);
    return 0;

machine learning – What does the decision boundary of XOR problem look like?

My textbook walks through an example of solving the XOR problem in machine learning using a two-dimensional RBF network. It does this by setting the centers for the two basis functions at (0,0) and (1,1). Afterwards, it challenges us and asks to imagine what the decision boundary for an RBF would look like if the two centers were instead at a sample of each class (class 0 could be (0,0) and class 1 could be (1 0)). Since there is only two classes, wouldn’t this result in essentially a straight line, or would it look like something else? Is there any reason why we would want to do this?

algorithms – Efficient way to find Xor of pairs with given target X in a range 0 to K

I came across a problem: given an array (can be huge 10^8) and an integer, K, find the count of pairs in the array whose Xor equal to each value in the range 0 to K.

 Arr = 1 2 3
 K = 2 

since K=2, possible values of x are 0, 1 or 2.

x = 0

  • There are 0 pairs whose Xor=0.

x = 1

  • There is 1 pair {2,3}, whose Xor=1.

x = 2

  • There is 1 pair {1,3}, whose Xor=2.

So output is

0 1 1

I know an n² solution to this problem where I loop x from 0 to K and now used hashing over the array find all such pairs whose sum is equal to the current x add it to the result array.

I’m seeking a better approach.

cryptography – one way function xor with its input

I have the following question:
enter image description here

I saw the question here What will i obtain if i apply a xor-ing a one way function and it’s input? but from what i understand its only when f(x) is not length preserving, correct me if i’m wrong.

I think its not one way function but I cant build a function that invert it without inverting f(x), can anyone show me how it can be done?

thank you