php – How i can perform this function which parse a string

i have wrote this function:

function parser ($src) {
    preg_match_all("/{(.*)}/", $src, $tmp); 
    foreach ($tmp(1) as $vkey => $row) {
        preg_match_all("/((a-z0-9)+)="((wds)+)"/", $row, $col); 
        foreach ($col(0) as $ckey => $param) {
            $row = str_replace($col( 0 )( $ckey ), "", $row );
            $arr($vkey)("attrib")($col( 1 )( $ckey )) = $col( 2 )( $ckey );             
        }
        $arr($vkey)("element") = $row;
    }
    return $arr;
}

Passing this string:

$string = "
    {data:one surname="Rossi" name="Mario"}
    {data:two}
    {data:three text="this is a text"}
"; 

And calling the function parser:

$result = parser( $string );

i have this output:

Array
(
    (0) => Array
        (
            (attrib) => Array
                (
                    (surname) => Rossi
                    (name) => Mario
                )

            (element) => data:one  
        )

    (1) => Array
        (
            (element) => data:two
        )

    (2) => Array
        (
            (attrib) => Array
                (
                    (text) => this is a text
                )

            (element) => data:three 
        )

)

Is possible perform the parser function with a regular expression and have same result?
Thanks!

IMPORTANT: The string is similar to XML format but not is XML format. Here is just for a example

PHP Parse error – WordPress Development Stack Exchange

I’m getting this error:
“Parse error: syntax error, unexpected ‘endwhile’ (T_ENDWHILE) in /var/www/vhosts/website/httpdocs/wp-content/themes/website/blog-masonry-grid.php on line 209
There has been a critical error on your website.

Learn more about debugging in WordPress.”

The code is:

<?php
/*
Template Name: Blog Masonry Grid
*/
?>
<?php get_header(); ?>
<?php
global $wp_query;

$id = $wp_query->get_queried_object_id();
$category = "";
$post_number = $wp_query->max_num_pages;

if ( get_query_var('paged') ) { $paged = get_query_var('paged'); }
elseif ( get_query_var('page') ) { $paged = get_query_var('page'); }
else { $paged = 1; }


?>

<div class="blogpage">

    <div class="container">
        <div class="section">
            <?php
            // Check Sidebar Layout
            $sidebar_layout = boc_page_sidebar_layout();

            // IF Sidebar Left
            if($sidebar_layout == 'left-sidebar'){
                get_sidebar();
            }

            if($sidebar_layout != 'full-width'){
                echo "<div class='col span_3_of_4'>";
            }
            ?>




    <?php
          //query_posts('post_type=post&paged='. $paged . '&cat=' . $category .'&posts_per_page=' . $post_number );
            query_posts('post_type=post&paged='. $paged . '&posts_per_page=' . $post_number );
    ?>



<?php /*
<ul id="filters">
    <li><a href="#" data-filter="*" class="selected">Everything</a></li>
    <?php
        $terms = get_terms("category"); // get all categories, but you can use any taxonomy
        $count = count($terms); //How many are they?
        if ( $count > 0 ){  //If there are more than 0 terms
            foreach ( $terms as $term ) {  //for each term:
                echo "<li><a href='#' data-filter='.".$term->slug."'>" . $term->name . "</a></li>n";
                //create a list item with the current term slug for sorting, and name for label
            }
        }
    ?>
</ul>*/

?>


<div class="blogholder">
    <div class="masonry_full_width">

<?php if(have_posts()) : while ( have_posts() ) : the_post(); ?>

<?php
    $classesfeat = '';
    $featuredback_styles = '';
    $featured_background_style = '';
    $termsString = '';

    $_post_format = get_post_format();
    $termsArray = get_the_terms( $post->ID, "category" );
        foreach ( $termsArray as $term ) { // for each term
            $termsString = $term->slug.' '; //create a string that has all the slugs
        }
?>



<?php

 $doublewidthblock =  get_post_meta($post->ID, 'boc_page_post_style_width', true);
 $buttonlight =  get_post_meta($post->ID, 'boc_featured_post_buttonlight', true);


 if(  (get_post_meta($post->ID, 'boc_featured_post_block', true) == "on") ){
    $classesfeat = 'featuredcat-post';

    $featuredback_styles = get_post_meta($post->ID, 'boc_featured_post_block_imgcolor', true);
    //background array has the following elements
    //echo $featuredback_style("background-color");
    //echo $featuredback_style("background-repeat");
    //echo $featuredback_style("background-attachment");
    //echo $featuredback_style("background-position");
    //echo $featuredback_style("background-image");

  $featured_background_style = 'style=" ';

  if( $doublewidthblock == "double_width"){
    $doubleclass = 'widepost';
  }else{
    $doubleclass = 'stdwidthpost';
  }


  if($featuredback_styles('background-color')){
    $featured_background_style .= ' background-color: '. $featuredback_styles('background-color') .'; ';
    }else{
     if($featuredback_styles('background-image')){$featured_background_style .= ' background-image: url('. $featuredback_styles('background-image') .'); '; }
     if($featuredback_styles('background-repeat')){$featured_background_style .= ' background-repeat: '. $featuredback_styles('background-repeat') .'; '; }
     if($featuredback_styles('background-attachment')) {$featured_background_style .= ' background-attachment: '. $featuredback_styles('background-attachment') .'; '; }
     if($featuredback_styles('background-position')){$featured_background_style .= ' background-position: '. $featuredback_styles('background-position') .'; '; }
  }




  $featured_background_style .= ' "';


 }
?>


    <div id="post-<?php the_ID(); ?>" class=" <?php if($doublewidthblock == "double_width") { ?> grid-item--width2 <?php } else { ?> grid-item <?php } ?> info_item isotope_element masitempc" >
        <div class="post_item_block boxed <?php echo $doubleclass;?> <?php echo $classesfeat; ?>" <?php echo $featured_background_style; ?> >


            <?php
            if((get_post_meta($post->ID, 'boc_featured_post_block', true) == "off")){
                if ( has_post_thumbnail() ) {
                    ?>
                        <a href="<?php the_permalink(); ?>" target="_self" title="<?php the_title_attribute(); ?>">
                            <?php the_post_thumbnail('boc_thin_blog'); ?>
                        </a>
                <?php
                }
          }

            ?>

            <div class="categorytitle">
                <?php
                $categories = get_the_category();
                 if ( ! empty( $categories ) ) {
                    echo esc_html( $categories(0)->name );
                }
                ?>
            </div>
            <div class="post_info_date">
                <?php echo get_the_date(); ?>
            </div>


            <div class="post_item_desc">
                <div class="post_text_inner">

                    <h4><a href="<?php the_permalink(); ?>" target="_self" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a>
                    </h4>

            <!--<span class="post_author">
                        <a class="post_author_link" href="<?php echo get_author_posts_url( get_the_author_meta( 'ID' ) ); ?>"><i class="icon_pencil-edit" aria-hidden="true"></i><span><?php the_author_meta('display_name'); ?></span></a>
                      </span>-->

               <?php
                  //place excerpt here too
                  //the_content('Read More');

                  echo qode_excerpt();

               ?>

                    <!-- <a href="<?php echo get_permalink(); ?>"><?php echo __('Read more','portcafe');?></a>  -->


                    <?php if((get_post_meta($post->ID, 'boc_featured_post_block', true) == "on") ){



                                    if($buttonlight == "off"){

                                ?>
                                 <a href="<?php the_permalink(); ?>" class="button btn_medium btn_dark btn_squared btn_normal_style">Read More</a>

                                <?
                                    }else{
                                ?>
                                   <a href="<?php the_permalink(); ?>" class="button btn_medium btn_white btn_squared btn_normal_style">Read More</a>
                                <?
                                        }

                        }
                    ?>

                </div>
             </div>


            </div>
    </div>

                <?php endwhile; ?>              

                <?php else: //If no posts are present ?>
                <div class="entry">
                        <p><?php _e('No posts were found.', 'qode'); ?></p>
                </div>
                <?php endif; ?>

            </div>
         <?php
            if (get_next_posts_link()) { ?>
                <div class="blog_load_more_button_holder">
                    <?php //added a function to get_next_posts_link in functions.php which add a class to the button
                    ?>
                    <div class="blog_load_more_button"><span rel="<?php echo $wp_query->max_num_pages; ?>"><?php echo get_next_posts_link(__('Show more', 'qode')); ?></span></div>
                </div>
            <?php } ?>


      <?php wp_reset_query(); ?>

            <?php
            if($sidebar_layout != 'full-width'){
                echo "</div>";
            }

            // IF Sidebar Right
            if($sidebar_layout == 'right-sidebar'){
                get_sidebar();
            }
            ?>
    </div>
</div>
</div>

</div>
<?php get_footer(); ?>

Thanks in advance for your help.

partitioning – Dislocker parse error while decrypting bitlocker encrypted Windows partition in Ubuntu dual-boot

I have a Windows 10 dual boot with Ubuntu 20.04. I’m trying to access my Windows partitions which have been encrypted using Bitlocker using THIS guide.

My HDD filesystem looks like the following based on fdisk -l:

Device          Start        End    Sectors   Size Type
/dev/sda1        2048     264191     262144   128M Microsoft reserved
/dev/sda2      264192 1952258047 1951993856 930.8G Microsoft basic data
/dev/sda3  1952258048 2441824497  489566450 233.5G Microsoft basic data
/dev/sda4  2441826304 2442874879    1048576   512M EFI System
/dev/sda5  2442874880 3907028991 1464154112 698.2G Linux filesystem

My SSD which contains the Windows and Ubuntu dual boot looks like the following:

Device             Start        End   Sectors   Size Type
/dev/nvme0n1p1      2048      34815     32768    16M Microsoft reserved
/dev/nvme0n1p2  41986048  461826047 419840000 200.2G Microsoft basic data
/dev/nvme0n1p3 461826048 1000214527 538388480 256.7G Linux filesystem
/dev/nvme0n1p4     34816   41986047  41951232    20G Linux swap

Apart from this I’m seeing something else, which I can’t make sense of:

Disk /dev/loop35: 233.45 GiB, 250658022400 bytes, 489566450 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x73736572

Device        Boot      Start        End    Sectors   Size Id Type
/dev/loop35p1      1920221984 3736432267 1816210284   866G 72 unknown
/dev/loop35p2      1936028192 3889681299 1953653108 931.6G 6c unknown
/dev/loop35p3               0          0          0     0B  0 Empty
/dev/loop35p4        27722122   27722568        447 223.5K  0 Empty

I’m pretty sure I’ve got the right recovery keys. I’m able to decrypt the 233G partition /dev/sda3 using the following command:

$ sudo dislocker -V /dev/sda3 -p<48-digit-recovery-key> -- /media/bitlocker 

but when I do the same thing using the appropriate key for /dev/sda2/ it gives me the following error:

(CRITICAL) Cannot parse volume header. Abort.

Am I doing something wrong? How can I decrypt the filesystem?

Parse Error: unexpected ‘}’ while creating Shortcode with Loop

I think either I am quite stupid today or just work-blind by this project but I’ve been trying to fix a little error a new shortcode is causing.

This is the code

<?php function reviewslide_function() {
    $output .= '
    <!-- Review Injection -->
    <div id="reviews" class="p-full">
        <div class="section_head">
            <span class="eyebrow">You about us</span>
            <h2>Customer Reviews</h2>
        </div>
        <div class="stars">
            <span class="material-icons">grade</span>
            <span class="material-icons">grade</span>
            <span class="material-icons">grade</span>
            <span class="material-icons">grade</span>
            <span class="material-icons">grade</span>
        </div>
        <div id="reviewbox">';
    $args = array(
        'post_type' => 'review',
        'posts_per_page' => 5,
        'order' => 'DESC',
    );
    $loop = new WP_Query( $args );
    while ( $loop->have_posts() ) : $loop->the_post();
    $output .= '
        <div class="review">'.
        the_content().
        '<span class="review_author">'. 
        bewerter_get_meta( "bewerter_name" ).
        '</span></div>';
    enwhile;
    $output .= '
    </div>
        <script>jQuery("#reviewbox > div:gt(0)").hide();
        
            setInterval(function() {
                jQuery("#reviewbox > div:first")
                .fadeOut(1800)
                .next()
                .fadeIn(2000)
                .end()
                .appendTo("#reviewbox");
            },  6000);
        </script>
        <div class="reviewbtn btn btn_blue arrow_r nosmooth">
            <a href="~GOOGLEREVIEWLINK~" target="_blank"><span>All Reviews</span></a>
        </div>
    </div>
    <!-- Review Exit -->';
    return $output;
}
add_shortcode('reviews', 'reviewslide_function'); ?>

This is the error thrown at me:

Parse error: syntax error, unexpected '}' in /html/wordpress-dev/wp-content/plugins/cpt-review/index.php on line 187

I am getting mad crazy trying to fix this, I just seem to be unable to find the error in here.

mysqli – Error: Parse error syntax error, unexpected ‘->’ (T_OBJECT_OPERATOR) in C:wamp64www/micarpeta/miarchivo.php on line 34

Error: Parse error syntax error, unexpected ‘->’ (T_OBJECT_OPERATOR) in C:wamp64www/micarpeta/miarchivo.php on line 34

Código llamado anteriormente al crear la conexión:

$conn = new mysqli($servername, $username, $password, $dbname);

Código que usé para cerrar la conexión:

$conn->close();

Por favor, ayuda

unity – Parse JSON without providing a class to deserialize to

I’m trying to parse a very large JSON string in Unity. I do not need all the fields and I can’t create a class with all the members. It appears that all examples I have found, including the official docs, always deserialize and map to class members, which I cannot do for my application.

I tried creating a class that is similar to the JSON string, meaning that it has some members of the target JSON, but to no avail. All members are always undefined.

Here’s part of the string:

{
    "Robots":({"CanReset":false,
    "CycleTime":123.875,
    "Info":null,
    "LevelInfo":null,
    "Name":"FTF_10033",
    "State":0,"
    ...
    }, ...
}

So I tried creating these classes:

(Serializable)
public class jsonData
{
    public Robot() robots;
}

(Serializable)
public class Robot
{
    public string Name = "Unknown AGV";
}

And printing the results:

var jsonString = www.downloadHandler.text;
jsonData jsonData_ = JsonUtility.FromJson<jsonData>(jsonString);
Debug.Log("Json data: " + jsonData_);
Debug.Log("Robots: " + jsonData_.robots);

jsonData_ prints Json data: jsonData_, and jsonData_.robots prints nothing (just Robots:).

Is there any way to parse JSON without a class?

I would be content with something like jsonString(“robots”)(0)(“name”) or something.

Thank you!

compilers – left/right derivations of grammars and parse trees

I’m having a hard time understanding how left/right derivations work. I have a very simple example that I’ve attempted but I don’t really know how to check if it’s correct.

$S-> NP$ $V$ $NP$

$NP ->$ the $N$

$N ->$ cat | mouse

$V ->$ ate

LEFT

$S-> NP$ $V$ $NP$

$S->$ the $N$ $V$ $NP$

$S->$ the $N$ $V$ the $N$

$S->$ the cat $V$ the $N$

$S->$ the cat ate the $N$

$S->$ the cat ate the mouse

RIGHT

$S->NP$ $V$ $NP$

$S->NP$ $V$ the $N$

$S->$ the $N$ $V$ the $N$

$S->$ the $N$ $V$ the mouse

$S->$ the $N$ ate the mouse

$S->$ the cat ate the mouse

My Thoughts

My lecture material says that we operate on the left/rightmost non terminal, I’m not 100% sure how to differentiate terminals and non-terminals but I assumed that if it became an English word it was a terminal hence I skipped it as long as there was a production remaining with another identifier in it.

Parse Tree

I genuinely don’t know how to create the parse trees and I appreciate any input in helping me figure it out.

edit: I forgot to mention, I know that the parse tree should be the same for the left and right derivation of the above grammar, just don’t know how to build one, all examples I find online are too complex for my understanding, I just started learning about this stuff very recently.

mbox – Parse Thunderbird mboxrd file with TB stuffs

Hi all the community 🙂

I have been using TB for a long time. I am looking for a way to parse a mboxrd format mail file (like <tb_profile>/ImapMail/<ESP_IMAP>/INBOX) from outside TB. By “outside” I mean a Linux bash script that I can manage myself. The goal is to extract the mail bodies and the same metadata as those found in global-messages-db.sqlite (aka gloda) which would be presented in clear (without accents and encoding problems).

So I tried to write some scripts with commands like gawk, tr and others. I quickly realized that between the different MIME encodings (content-type and content-transfer-encoding), character sets (Unicode or not), the RFC standards that changed (before we could write a content-type on several lines as explained here), the multipart mail (multipart/mixed etc.) it was a huge shambles to parse. So I wondered if I was not reinventing the wheel and a better possibility existed….

I know I could parse the source code of TB (I have a little programming experience) to determine what is going on behind the scenes when viewing the content of an IMAP folder for example but I do not know where to start. Mainly I wonder if I can not directly use an executable file or the functions of a SO library (under Linux) which are embeded in TB.

This is why I am asking you who is reading me if you can guide me in the right direction.

Regards
lnj

Can’t parse string into json because of this char : ‘ in python

I have a program that get me a string from a database, here is an example of what string I can get :

str = '{ 
'list_one': ('dummy_one:' 'something', 'dummy_two': 'something_again'), 
'list_two': ('dummy_three': 'something once again but with a twiste : l'alsace', 'dummy_four': 'wow would you look at that again something')
}'

I need to replace ‘ to ” because it wont load into json if I don’t (” is needed for “key”: “value”).

str = str.replace("'", '"')

I want to load this string into json, so I do this :

str_json = json.loads(str)

But there is an issue : inside the str I have list_two, inside dummy_three there is the l'alsace, the ‘ of l’alsace is replaced by a ” and it cause my program to crash because it can’t work as a json.
I can’t find a way to make it work…

Parse python code, for specific pep8 issues

I am aware, that libraries exist for parsing python code, however, for the sake of learning how they parse errors, I’m creating a script that checks a file for only 6 Pep8 errors just for reference.

This is how my current 6 Pep8 functions look (they append an issue to the issues list, if issue was found)

"""
(S001) Line is longer than 79 characters
(S002) Indentation is not a multiple of four
(S003) Unnecessary semicolon after a statement (note, semicolons are admissible in comments)
(S004) At least two spaces before inline comments required
(S005) TODO found (only in comments; the case does not matter)
(S006) More than two blank lines used before this line (must be output for the first non-empty line)
"""
def S001(self, ln_num: int, line: str):
    if len(line) > 79:
        self.issues.append(f"Line {ln_num}: S001 Too Long")


def S002(self, ln_num: int, line: str):
    indentation_length = len(line) - len(line.lstrip())
    if indentation_length % 4 != 0:
        self.issues.append(f"Line {ln_num}: S002 Indentation is not a multiple of four")


def S003(self, ln_num: int, line: str):
    regex1 = re.compile("(.*)((;(s)*#)|(;$))")
    regex2 = re.compile("#.*;")
    if regex1.search(line) and not regex2.search(line):
        self.issues.append(f"Line {ln_num}: S003 Unnecessary semicolon")


def S004(self, ln_num: int, line: str):
    regex = re.compile("(((^ ){2})|(s(^ ))|((^ )s))#")
    if regex.search(line):
        self.issues.append(f"Line {ln_num}: S004 At least two spaces before inline comments required")


def S005(self, ln_num: int, line: str):
    regex =  re.compile("#(.*)todo", flags=re.IGNORECASE)
    if regex.search(line):
        self.issues.append(f"Line {ln_num}: S005 TODO found")


def S006(self, ln_num: int, line: str):
    if self.code(ln_num-4:ln_num-1) == ('', '', '') and line != "":
        self.issues.append(f"Line {ln_num}: S006 More than two blank lines used before this line")

Testcases:

""" Test case 1 """
print('What's your name?') # reading an input
name = input();
print(f'Hello, {name}');  # here is an obvious comment: this prints greeting with a name


very_big_number = 11_000_000_000_000_000_000_000_000_000_000_000_000_000_000_000
print(very_big_number)



def some_fun():
    print('NO TODO HERE;;')
    pass; # Todo something
""" END """

""" Test Case 2 """
print('hello')
print('hello');
print('hello');;;
print('hello');  # hello
# hello hello hello;
greeting = 'hello;'
print('hello')  # ;
""" END """

""" Test Case 3 """
    print('hello')
    print('hello')  # TODO
    print('hello')  # TODO # TODO
    # todo
    # TODO just do it
    print('todo')
    print('TODO TODO')
    todo()
    todo = 'todo'
""" END """

""" Test Case 4 """
print("hello")


print("bye")



print("check")
""" END """

""" Test Case 5 """
print('hello!')
# just a comment
print('hello!')  #
print('hello!')  # hello

print('hello!') # hello
print('hello!')# hello
""" END """

Testcase 1 Expected Output:

Line 1: S004 At least two spaces before inline comment required
Line 2: S003 Unnecessary semicolon
Line 3: S001 Too long
Line 3: S003 Unnecessary semicolon
Line 6: S001 Too long
Line 11: S006 More than two blank lines used before this line
Line 13: S003 Unnecessary semicolon
Line 13: S004 At least two spaces before inline comment required
Line 13: S005 TODO found

I am aware my code, is not optimal, and doesn’t satisfy every edge case, but I want an idea, on how they parse the errors properly. I would like improvements, or better ideas on how to parse for errors, since i personally don’t like my answers.