问:
stumped with recaptcha verification step
I hate asking for help.. but I've spent I dunno how many hours trying to figure out how to implement the verification step for this form with recaptcha.

I understand the I need define the private key somewhere, but most of the other guides are using "isset" functions and I just don't at which part of the php to do it.

At the moment, the button shows up and is checkable.. but when I click submit, it sends regardless of whether the box was checked. (Just explaining in case that's helpful.)

Thanks, sorry.

```<code><?php

$to = 'example@caraudioinc.com';
$subject = 'CarAudioInc.com Form Message';

$errName = $errEmail = $errMessage = "";
$name = $email = $pNum = $message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $pNum = test_input($_POST["pNum"]);
  $message = test_input($_POST["message"]);

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (empty($_POST["name"])) {
    $errName = "*Name field is required.";
    } else {
    $name = test_input($_POST["name"]);

        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $errName = "Invaild name.";
        }
    }

    if (empty($_POST["email"])) {
    $errEmail = "*Email field is required.";
        } else {
    $email = test_input($_POST["email"]);

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid E-mail.";
        }
    }

    if (empty($_POST["message"])) {
    $errMessage = "*Message field is required.";
        } else {
    $message = test_input($_POST["message"]);
    }

$body = <<<EMAIL

Message from: $name

$message

Phone: $pNum
Email: $email

EMAIL;

$header = "From: $email";

if (!$errName && !$errEmail && !$errMessage ) {
    if($_POST) {

        mail($to, $subject, $body, $header);

        header('Location: /sent');
    }

    }
}
?>

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=1152">
<script src="https://www.google.com/recaptcha/api.js"></script>

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src="https://www.googletagmanager.com/gtag/js?id=UA-100617570-1" ></script>
<script>
  window.dataLayer = window.dataLayer || [];
  function gtag(){dataLayer.push(arguments);}
  gtag('js', new Date());

  gtag('config', 'UA-100617570-1');
</script>

<!--Google meta tags -->
<title>Car Audio Inc | Contact</title>

<!--fb meta tags -->
<link rel="canonical" href="https://www.caraudioinc.com/contact" />
<link href="css/multiColumnTemplate.css" hreflang="en" rel="stylesheet" type="text/css">
<link rel="icon" href="images/favicon.png" type="image/png">
</head>

<body>
<div class="container">

  <header>
     <div class="primary_header">

    <nav class="secondary_header" id="menu">
      <ul>
     <li><a href="/">HOME</a></li>
        <li><a href="about">ABOUT</a></li>
          <li><a href="services">SERVICES</a></li>
        <li class="current"><a href="contact">CONTACT</a></li>
      </ul>
    </nav>

  </header>

 <div class="contactForm">
  <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"><br>

    <label for="name">Name  </label><span class="error"><?php echo $errName; ?></span><br>
    <input type="text" id="name" name="name" value="<?php echo $name;?>"><br><br>

      <label for="email">Email  </label><span class="error"><?php echo $errEmail; ?></span><br>
    <input type="email" id="email" name="email" value="<?php echo $email;?>"><br><br>

      <label for="pNum">Phone Number (optional)<br></label>
    <input type="tel" id="pNum" name="pNum" value="<?php echo $pNum;?>"><br><br>

      <label for="message">Message  </label><span class="error"><?php echo $errMessage; ?></span><br>
    <textarea id="message" name="message" style="height:100px"><?php echo $message;?></textarea>

     <div class="g-recaptcha" data-sitekey="6LcR-DQUAAAAAB2cXajVPi7lpFEZ_z8vZrS97ZXo"></div><br>

    <input type="submit" value="Submit">
    </form>

  <footer class="secondary_header footer">
    <div class="copyright">© Car Audio Inc 2020, All Rights Reserved.</div>

  </footer>

</div>
</body>
</html>
</code>```

答:
You could set the isset() function in your if() condiition as

```<code>if (isset($_POST)){...}
</code>```

By this it means that if something is posted or if $_POST os set to some value the codes moves forward.

But as your mentioned way earlier it was just checking that the form was posted or not and every time the form was being posted with no values at all and the code was moving further.

Body:
I hate asking for help.. but I've spent I dunno how many hours trying to figure out how to implement the verification step for this form with recaptcha.

I understand the I need define the private key somewhere, but most of the other guides are using "isset" functions and I just don't at which part of the php to do it.

At the moment, the button shows up and is checkable.. but when I click submit, it sends regardless of whether the box was checked. (Just explaining in case that's helpful.)

Thanks, sorry.

<?php

$to = 'example@caraudioinc.com';
$subject = 'CarAudioInc.com Form Message';

$errName = $errEmail = $errMessage = "";
$name = $email = $pNum = $message = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $name = test_input($_POST["name"]);
  $email = test_input($_POST["email"]);
  $pNum = test_input($_POST["pNum"]);
  $message = test_input($_POST["message"]);

}

function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {

    if (empty($_POST["name"])) {
    $errName = "*Name field is required.";
    } else {
    $name = test_input($_POST["name"]);

        if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
      $errName = "Invaild name.";
        }
    }

    if (empty($_POST["email"])) {
    $errEmail = "*Email field is required.";
        } else {
    $email = test_input($_POST["email"]);

        if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
      $emailErr = "Invalid E-mail.";
        }
    }

    if (empty($_POST["message"])) {
    $errMessage = "*Message field is required.";
        } else {
    $message = test_input($_POST["message"]);
    }

$body = <<<EMAIL

Message from: $name

$message

Phone: $pNum
Email: $email

EMAIL;

$header = "From: $email";

if (!$errName && !$errEmail && !$errMessage ) {
    if($_POST) {

        mail($to, $subject, $body, $header);

        header('Location: /sent');
    }

    }
}
?>

<!doctype html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=1152">

<title>Car Audio Inc | Contact</title>

<link rel="canonical" href="https://www.caraudioinc.com/contact" />
<link href="css/multiColumnTemplate.css" hreflang="en" rel="stylesheet" type="text/css">
<link rel="icon" href="images/favicon.png" type="image/png">

HOME

ABOUT

SERVICES

CONTACT

  <form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">

    Name  <?php echo $errName; ?>

    <input type="text" id="name" name="name" value="<?php echo $name;?>">

      Email  <?php echo $errEmail; ?>

    <input type="email" id="email" name="email" value="<?php echo $email;?>">

      Phone Number (optional)

    <input type="tel" id="pNum" name="pNum" value="<?php echo $pNum;?>">

      Message  <?php echo $errMessage; ?>

    <textarea id="message" name="message" style="height:100px"><?php echo $message;?></textarea>

    <input type="submit" value="Submit">
    </form>

© Car Audio Inc 2020, All Rights Reserved.

Body:
You could set the isset() function in your if() condiition as

if (isset($_POST)){...}

By this it means that if something is posted or if $_POST os set to some value the codes moves forward.

But as your mentioned way earlier it was just checking that the form was posted or not and every time the form was being posted with no values at all and the code was moving further.


来源: stackexchange

答:
How about the concat() method?

```<code>>>> import pandas as pd
>>> s1 = pd.Series(['a', 'b'])
>>> s2 = pd.Series(['c', 'd'])
>>> pd.concat([s1, s2])
</code>```

Output:

```<code>0    a
1    b
0    c
1    d
</code>```

dtype: object

ContentLicense: CC BY-SA 4.0

Title: Merge two tabel

Body:
I have two tables. I need to merge two tables with cx1, cx2 and Date keys. How is it?

fist table
cx1   Date       Amount
1     11/1/2019   400
1     12/1/2019   200
2     15/1/2019   400
3     16/1/2019   500

Second Table
cx2    Date        Amount
1      11/1/2019   300
2      16/1/2019   200
3      16/1/2019   400

Final output
cx     Date        Amount_1    Amount_2
1      11/1/2019   400         300
1      12/1/2019   0           300
2      15/1/2019   400         0
2      16/1/2019   0           200
3      16/1/2019   500         400

Body:
How about the concat() method?

>>> import pandas as pd
>>> s1 = pd.Series(['a', 'b'])
>>> s2 = pd.Series(['c', 'd'])
>>> pd.concat([s1, s2])

Output:

0    a
1    b
0    c
1    d

dtype: object


问:
Call C# function Blazor Jquery
Need some help sorting an error added a screenshot of code and the error returned by the code.
Trying to call a C# function from Jquery and pass parameters along.

_Host

```<code>        function getElementSVG(e) {
            var position = getPosition(e);
            var circle = makeSVG('circle', { cx: position.pointx, cy: position.pointy, r: 0.02, stroke: 'black', 'stroke-width': 0.5, fill: 'black' });
            document.getElementById(e.currentTarget.id).appendChild(circle);
            DotNet.invokeMethodAsync('PeopleCounterWeb', 'AddPointToList', position.pointx, position.pointy).then(result => {
                console.log(result);
            });
            return position;
        }

        function fnsuccesscallback(data) {
            alert(data.d);

        }

        function fnerrorcallback(result) {
            alert(result.statusText);
        }
        function makeSVG(tag, attrs) {
            var el = document.createElementNS('http://www.w3.org/2000/svg', tag);
            for (var k in attrs)
                el.setAttribute(k, attrs[k]);
            return el;
        }
        function getPosition(e) {
            var rect = e.target.getBoundingClientRect();
            var x = e.clientX - rect.left;
            var y = e.clientY - rect.top;

            var width = rect.width;
            var height = rect.height;
            var pointx = ((x / width) * 100).toFixed(2);
            var pointy = ((y / height) * 100).toFixed(2);
            return {
                pointx,
                pointy
            }
        };
</code>```

MainMap.cshtml

```<code>    [JSInvokable]
    public string AddPointToList(string x, string y)
    {
        var alpha = x + "-" + y;
        return "";
        //Points.Add(obj[0], obj[1]);
    }
</code>```

Code

[Error]

答:
You are trying to invoke a message on an instance without passing a reference to that instance. Without an instance you can only call static methods.

You'll need to create an instance of DotNetReference in C# and pass it to JS.

There is a section on Blazor University about calling C# from JS - https://blazor-university.com/javascript-interop/calling-dotnet-from-javascript/

Title: Call C# function Blazor Jquery

Body:
Need some help sorting an error added a screenshot of code and the error returned by the code.
Trying to call a C# function from Jquery and pass parameters along.

_Host

        function getElementSVG(e) {
            var position = getPosition(e);
            var circle = makeSVG('circle', { cx: position.pointx, cy: position.pointy, r: 0.02, stroke: 'black', 'stroke-width': 0.5, fill: 'black' });
            document.getElementById(e.currentTarget.id).appendChild(circle);
            DotNet.invokeMethodAsync('PeopleCounterWeb', 'AddPointToList', position.pointx, position.pointy).then(result => {
                console.log(result);
            });
            return position;
        }

        function fnsuccesscallback(data) {
            alert(data.d);

        }

        function fnerrorcallback(result) {
            alert(result.statusText);
        }
        function makeSVG(tag, attrs) {
            var el = document.createElementNS('http://www.w3.org/2000/svg', tag);
            for (var k in attrs)
                el.setAttribute(k, attrs[k]);
            return el;
        }
        function getPosition(e) {
            var rect = e.target.getBoundingClientRect();
            var x = e.clientX - rect.left;
            var y = e.clientY - rect.top;

            var width = rect.width;
            var height = rect.height;
            var pointx = ((x / width) * 100).toFixed(2);
            var pointy = ((y / height) * 100).toFixed(2);
            return {
                pointx,
                pointy
            }
        };

MainMap.cshtml

    [JSInvokable]
    public string AddPointToList(string x, string y)
    {
        var alpha = x + "-" + y;
        return "";
        //Points.Add(obj[0], obj[1]);
    }

Code

[Error]


问:
RCTBridge required dispatch_sync to load RCTDevLoadingView. This may lead to deadlocks
I get this in logs:

RCTBridge required dispatch_sync to load RCTDevLoadingView. This may
  lead to deadlocks

This is leading to an issue where the rendered content in React leads to alignment issues.

(See attached screenshot 1) Screenshot with Issue

This occurs randomly as all screens do not show alignment issues.

(See attached Screenshot 2) Screenshot without issue

I have used styled-components for Layout:

```<code>return(
  this.props.lastComponent ?
  <CommentList marginLeft={this.props.marginLeft}>
    <CommentUserPicWrapper imageWidth={this.props.imageWidth}>
      {this.props.imageType === 'URL' ? <CommentUserPic source={{uri:this.props.uri}} imageWidth={this.props.imageWidth} onLoad={this.handleLoad}/> : <CommentUserPic source={require('../../img/defaultProfPic.png')} imageWidth={this.props.imageWidth} onLoad={this.handleLoad}/>}
      {
        this.state.loading ? null : <ActivityIndicator style={{position:'absolute'}}/>
      }
    </CommentUserPicWrapper>
    <CommentDetails borderStatus={true} marginLeft={this.props.marginLeft}>
      <CommentUserName>{this.props.userName} says</CommentUserName>
      <CommentUserContent>{this.props.UserContent}</CommentUserContent>
      <CommentUserDate><Text>{this.props.commentDate}</Text> at <Text>{this.props.commentTime}</Text>MST</CommentUserDate>
    </CommentDetails>
    <CommentReply onPress={this.replyClicked} borderStatus={true} underlayColor='transparent'>
      <CommentReplyText>Reply</CommentReplyText>
    </CommentReply>
  </CommentList>
  :
  <CommentList marginLeft={this.props.marginLeft}>
    <CommentUserPicWrapper imageWidth={this.props.imageWidth}>
      {this.props.imageType === 'URL' ? <CommentUserPic source={{uri:this.props.uri}} imageWidth={this.props.imageWidth} onLoad={this.handleLoad}/> : <CommentUserPic source={require('../../img/defaultProfPic.png')} imageWidth={this.props.imageWidth} onLoad={this.handleLoad}/>}
      {this.state.loading ? null : <ActivityIndicator style={{position:'absolute'}}/>}
    </CommentUserPicWrapper>
    <CommentDetails borderStatus={this.props.borderStatus} marginLeft={this.props.marginLeft}>
      <CommentUserName>{this.props.userName} says</CommentUserName>
      <CommentUserContent>{this.props.UserContent}</CommentUserContent>
      <CommentUserDate><Text>{this.props.commentDate}</Text> at <Text>{this.props.commentTime}</Text>MST</CommentUserDate>
    </CommentDetails>
    <CommentReply onPress={this.replyClicked} borderStatus={this.props.borderStatus} underlayColor='transparent'>
      <CommentReplyText>Reply</CommentReplyText>
    </CommentReply>
  </CommentList>
)
</code>```

Thanks.

答:
Swift Solution</p>

```<code>let bridge = RCTBridge(bundleURL: jsCodeLocation, moduleProvider: nil, launchOptions: nil)

#if RCT_DEV
bridge?.module(for: RCTDevLoadingView.self)
#endif
let rootView = RCTRootView(bridge: bridge!, moduleName: "AppMain", initialProperties: nil)

</code>```

ContentLicense: CC BY-SA 3.0

Body:
I get this in logs:

RCTBridge required dispatch_sync to load RCTDevLoadingView. This may
  lead to deadlocks

This is leading to an issue where the rendered content in React leads to alignment issues.

(See attached screenshot 1) Screenshot with Issue

This occurs randomly as all screens do not show alignment issues.

(See attached Screenshot 2) Screenshot without issue

I have used styled-components for Layout:

return(
  this.props.lastComponent ?
  <CommentList marginLeft={this.props.marginLeft}>
    <CommentUserPicWrapper imageWidth={this.props.imageWidth}>
      {this.props.imageType === 'URL' ? <CommentUserPic source={{uri:this.props.uri}} imageWidth={this.props.imageWidth} onLoad={this.handleLoad}/> : <CommentUserPic source={require('../../img/defaultProfPic.png')} imageWidth={this.props.imageWidth} onLoad={this.handleLoad}/>}
      {
        this.state.loading ? null : <ActivityIndicator style={{position:'absolute'}}/>
      }
    </CommentUserPicWrapper>
    <CommentDetails borderStatus={true} marginLeft={this.props.marginLeft}>
      <CommentUserName>{this.props.userName} says</CommentUserName>
      <CommentUserContent>{this.props.UserContent}</CommentUserContent>
      <CommentUserDate><Text>{this.props.commentDate}</Text> at <Text>{this.props.commentTime}</Text>MST</CommentUserDate>
    </CommentDetails>
    <CommentReply onPress={this.replyClicked} borderStatus={true} underlayColor='transparent'>
      <CommentReplyText>Reply</CommentReplyText>
    </CommentReply>
  </CommentList>
  :
  <CommentList marginLeft={this.props.marginLeft}>
    <CommentUserPicWrapper imageWidth={this.props.imageWidth}>
      {this.props.imageType === 'URL' ? <CommentUserPic source={{uri:this.props.uri}} imageWidth={this.props.imageWidth} onLoad={this.handleLoad}/> : <CommentUserPic source={require('../../img/defaultProfPic.png')} imageWidth={this.props.imageWidth} onLoad={this.handleLoad}/>}
      {this.state.loading ? null : <ActivityIndicator style={{position:'absolute'}}/>}
    </CommentUserPicWrapper>
    <CommentDetails borderStatus={this.props.borderStatus} marginLeft={this.props.marginLeft}>
      <CommentUserName>{this.props.userName} says</CommentUserName>
      <CommentUserContent>{this.props.UserContent}</CommentUserContent>
      <CommentUserDate><Text>{this.props.commentDate}</Text> at <Text>{this.props.commentTime}</Text>MST</CommentUserDate>
    </CommentDetails>
    <CommentReply onPress={this.replyClicked} borderStatus={this.props.borderStatus} underlayColor='transparent'>
      <CommentReplyText>Reply</CommentReplyText>
    </CommentReply>
  </CommentList>
)

Thanks.

Body:
Swift Solution

let bridge = RCTBridge(bundleURL: jsCodeLocation, moduleProvider: nil, launchOptions: nil)

#if RCT_DEV
bridge?.module(for: RCTDevLoadingView.self)
#endif
let rootView = RCTRootView(bridge: bridge!, moduleName: "AppMain", initialProperties: nil)


问:
How to get the location of a place on google map
i'm developing an android application similar to Google places app.

I want a functionality to obtain the location of a place on google maps in my application. How do i achieve this?

This is the use case:

Using GPS my current location's lat and long will be passed using the notification service.

Then when i click on the button restaurant,the list of restaurants in that particular location will be displayed(all information is being retrieved from the server that i created using grails).

Then i select a restaurant's name from the list being displayed.and then in the user interface there is a button called "MAP" .

Upon click of the "MAP" button, the location of the restaurant i have chosen must be displayed on Google maps.

答:
What's the thing that you can't do - displaying the restaurant on the map, or having just the name of the place, you wish to find it's address/coordinates on the map?

You can follow the official Android tutorial on the subject - Point 2 in this article: http://developer.android.com/resources/tutorials/views/… Probably this article will be useful as well: http://mobiforge.com/developing/story/using-google-maps-android

Part 1 and 2 guide you through the creation of a Map activity (you should start a new map activity when the user taps on MAP button) and how to add an overlay to the map. In the article the overlay is the android robot. The other articles uses a pushpin as an overlay. Overlay, on the other hand, is .. a picture that is displayed on the map. In your case - some pinpoint put on the coordinates of the restaurant. Once you've created the map activity, you can follow my second link and look for title "Adding Markers". It's very well explained.


问:
I am trying to create a mysql trigger, but not able to, dont know what the error is
This is trigger query

```<code>    DELIMITER $$
CREATE TRIGGER adjust_ref_token
AFTER INSERT
    ON transactions FOR EACH ROW
DECLARE token_ref integer;

SELECT ico_stages.sales_token INTO @token_ref WHERE ico_stages.start_date <= NOW() <= ico_stages.end_date;

IF NEW.tnx_type = 'referral' THEN
    UPDATE ico_stages SET ico_stages.sales_token = (@token_ref - NEW.tokens) WHERE ico_stages.start_date <= NOW() <= ico_stages.end_date;
END IF;
END $$
</code>```

Error showing is

```<code>    CREATE TRIGGER adjust_ref_token
AFTER INSERT
    ON transactions FOR EACH ROW
DECLARE token_ref integer;

SELECT ico_stages.sales_token INTO @token_ref WHERE ico_stages.start_date <= NOW() <= ico_stages.end_date;

IF NEW.tnx_type = 'referral' THEN
    UPDATE ico_stages SET ico_stages.sales_token = (@token_ref - NEW.tokens) WHERE ico_stages.start_date <= NOW() <= ico_stages.end_date;
END IF;
END
</code>```

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE token_ref integer;

SELECT ico_stages.sales_token INTO @token_ref WHER' at line 4

Can anyone please tell me whats the error?

答:
```<code>DELIMITER $$
CREATE TRIGGER adjust_ref_token AFTER INSERT ON transactions
FOR EACH ROW
BEGIN
    DECLARE token_ref integer;

    SELECT ico_stages.sales_token INTO @token_ref WHERE ico_stages.start_date <= NOW() <= ico_stages.end_date;

    IF NEW.tnx_type = 'referral' THEN
        UPDATE ico_stages SET ico_stages.sales_token = (@token_ref - NEW.tokens) WHERE ico_stages.start_date <= NOW() <= ico_stages.end_date;
    END IF;
END; $$
DELIMITER ;
</code>```

Basically if you want to execute multiple statements within the trigger, you have to use BEGIN...END construct.
For more details https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html

Body:
This is trigger query

    DELIMITER $$
CREATE TRIGGER adjust_ref_token
AFTER INSERT
    ON transactions FOR EACH ROW
DECLARE token_ref integer;

SELECT ico_stages.sales_token INTO @token_ref WHERE ico_stages.start_date <= NOW() <= ico_stages.end_date;

IF NEW.tnx_type = 'referral' THEN
    UPDATE ico_stages SET ico_stages.sales_token = (@token_ref - NEW.tokens) WHERE ico_stages.start_date <= NOW() <= ico_stages.end_date;
END IF;
END $$

Error showing is

    CREATE TRIGGER adjust_ref_token
AFTER INSERT
    ON transactions FOR EACH ROW
DECLARE token_ref integer;

SELECT ico_stages.sales_token INTO @token_ref WHERE ico_stages.start_date <= NOW() <= ico_stages.end_date;

IF NEW.tnx_type = 'referral' THEN
    UPDATE ico_stages SET ico_stages.sales_token = (@token_ref - NEW.tokens) WHERE ico_stages.start_date <= NOW() <= ico_stages.end_date;
END IF;
END

MySQL said: Documentation

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE token_ref integer;

SELECT ico_stages.sales_token INTO @token_ref WHER' at line 4

Can anyone please tell me whats the error?

Body:
DELIMITER $$
CREATE TRIGGER adjust_ref_token AFTER INSERT ON transactions
FOR EACH ROW
BEGIN
    DECLARE token_ref integer;

    SELECT ico_stages.sales_token INTO @token_ref WHERE ico_stages.start_date <= NOW() <= ico_stages.end_date;

    IF NEW.tnx_type = 'referral' THEN
        UPDATE ico_stages SET ico_stages.sales_token = (@token_ref - NEW.tokens) WHERE ico_stages.start_date <= NOW() <= ico_stages.end_date;
    END IF;
END; $$
DELIMITER ;

Basically if you want to execute multiple statements within the trigger, you have to use BEGIN...END construct.
For more details https://dev.mysql.com/doc/refman/8.0/en/trigger-syntax.html


问:
How to limit the loop so it only loops through for each value once
Two arrays obtained using:

array1=($(ls -lad */ | awk '{print $5}'))

array2=($(ls -lad */ | awk '{print $9}'))

Two array typsets:

declare -a array1='([0]="4096" [1]="4096" [2]="4096" [3]="4096" [4]="4096" [5]="4096" [6]="4096" [7]="4096" [8]="4096")'

declare -a array2='([0]="bod/" [1]="working/" [2]="firm/" [3]="symbol/" [4]="info/" [5]="scripts/" [6]="development/" [7]="design/" [8]="testing/")'

For the file sizes that are less than 10000 it will get the path for these directory names and create full path to be used in an ls lRa command where it lists the directories recursively where they directory size is less than 10000.

I currently have 8 file sizes for 8 directory names that are less than 10000 in size at the current level and instead of just printing the path for each directory name once it is doing 8 times. I assume its because I have configured my for loop wrong.

```<code>for s in ${!array1[*]}
do
    if [ ${array1[$s]} -lt 10000 ]
    then
        for dir in ${!array2[@]}
        do
            paths=$(pwd {array2[$dir]})
            echo "$paths/${array2[$dir]}"
        done
    else
        :
    fi
done
</code>```

I HAVE EDITED MY QUESTION:

I want to create a script that given a path i.e. /a/path/to/use it will call ls -lRa from this path.

However, the ls -lRa should only be called on directories and their sub-directories if their size is less than 10000 bytes.

For example, if /a/path/to/use contains 4 directories with sizes 4096,4096,12480,24620 it would only call ls -lRa on the first two with the last two being ignored.

Once the ls command has been called it will then do the same for any dirs in that directory and so on until it has inspected all dirs in the file structure from the original path.

My attempt above does not appear to be working but provides some explanation as to what I am attempting.

答:
This will run ls -la on any dir/subdir under the current directory that is larger than minSize bytes.  Because we are parsing the output of find using NULL as the delimiter, it is safe from the pitfalls that plague ls.

Note: Because find is recursive in nature, we do not need to run ls recursively

```<code>#!/bin/bash

unset IFS
minSize=10000

while read -r -d $'\0' size dir; do
  if (( size < minSize )); then
    echo "############## $dir ##############"
    ls -la "$dir"
  fi
done < <(find . -mindepth 1 -depth -type d -exec du -b0 {} +)
</code>```

Body:
Two arrays obtained using:

array1=($(ls -lad */ | awk '{print $5}'))

array2=($(ls -lad */ | awk '{print $9}'))

Two array typsets:

declare -a array1='([0]="4096" [1]="4096" [2]="4096" [3]="4096" [4]="4096" [5]="4096" [6]="4096" [7]="4096" [8]="4096")'

declare -a array2='([0]="bod/" [1]="working/" [2]="firm/" [3]="symbol/" [4]="info/" [5]="scripts/" [6]="development/" [7]="design/" [8]="testing/")'

For the file sizes that are less than 10000 it will get the path for these directory names and create full path to be used in an ls lRa command where it lists the directories recursively where they directory size is less than 10000.

I currently have 8 file sizes for 8 directory names that are less than 10000 in size at the current level and instead of just printing the path for each directory name once it is doing 8 times. I assume its because I have configured my for loop wrong.

for s in ${!array1[*]}
do
    if [ ${array1[$s]} -lt 10000 ]
    then
        for dir in ${!array2[@]}
        do
            paths=$(pwd {array2[$dir]})
            echo "$paths/${array2[$dir]}"
        done
    else
        :
    fi
done

I HAVE EDITED MY QUESTION:

I want to create a script that given a path i.e. /a/path/to/use it will call ls -lRa from this path.

However, the ls -lRa should only be called on directories and their sub-directories if their size is less than 10000 bytes.

For example, if /a/path/to/use contains 4 directories with sizes 4096,4096,12480,24620 it would only call ls -lRa on the first two with the last two being ignored.

Once the ls command has been called it will then do the same for any dirs in that directory and so on until it has inspected all dirs in the file structure from the original path.

My attempt above does not appear to be working but provides some explanation as to what I am attempting.

Body:
This will run ls -la on any dir/subdir under the current directory that is larger than minSize bytes.  Because we are parsing the output of find using NULL as the delimiter, it is safe from the pitfalls that plague ls.

Note: Because find is recursive in nature, we do not need to run ls recursively

#!/bin/bash

unset IFS
minSize=10000

while read -r -d $'\0' size dir; do
  if (( size < minSize )); then
    echo "############## $dir ##############"
    ls -la "$dir"
  fi
done < <(find . -mindepth 1 -depth -type d -exec du -b0 {} +)


问:
Behaviour of require (static + dynamic) [ RAKU ]
My question is related to the behaviour of require when used with static or dynamic resolution of the desired namespace.

I'll try to present my understanding of things:

[ 1 ] Use "require" with a literal

```<code>    { require MODULE; }
</code>```

In this case the compiler checks to see if MODULE has already been declared as a symbol.
If it hasn't, the compiler declares it, and binds it to an empty placeholder package it's just created for this "require"

```<code>{
    my $response = ::('MODULE');  # this happens at runtime
    say $response.^name;          # MODULE doesn't exist so the lookup results in the compilation-phase placeholder package: MODULE

    try require MODULE;           # although the execution order of require comes after the lookup,
                                  # the placeholder package creation was done during compilation and the package is present in the current scope during run-time
}
</code>```

[ 2 ] Use "require" with a String

```<code>    { try require 'FILE_PATH'; }
</code>```

In this case "require" is trying to find (at run-time) a file that is defined by the filename declared in the string.
If found (with appropriate content: modules, packages etc.) then it creates a namespace(s) in the current scope and loads it with the content(s) of the file.

[ 3 ] Use "require" with a dynamic lookup

```<code>    { try require ::('MODULE'); }
</code>```

It seems to me that in that case "require" behaves NOT as a "normal" subroutine.

When we use "require" with "dynamic lookup" then the core functionality of the dynamic lookup is "melted" in a new routine that behaves differently than we would expect.

The fact is that the result of the "dynamic lookup" routine is either a symbol or a Failure.

If "require" behaves like a "normal" subroutine, then the only input it could use, would be the result of the dynamic lookup that followed it (Namespace or Failure).

But it is also a fact that in the case of a Failure (as the result of dynamic lookup), "require" continues searching the repositories for a proper package (as is normally the case, using nevertheless the argument we gave to dynamic lookup: 'MODULE').

So obviously "require" isn't behaving like a "normal" subroutine in that sense.

As the result of my line of thought the combination of require + dynamic lookup resembles the following construct:

```<code>{ modified_dynamic_lookup('MODULE') :if_symbol_not_found_search_repositories_and_if_appropriate_package_found_create_namespace_and_load_package_contents; }
</code>```

My concern is my understanding of case [3].

How does require + dynamic lookup work? (analytically speaking - what are the steps followed by the compiler at first and then by the runtime?)

[ Post Scriptum ]

I agree with @raiph that "require" is NOT a subroutine and that it is deeply integrated in the language.

In that sense the "dynamic lookup construct" that follows the require "instruction" is used for 2 things:

To notify the compiler that the construct is "dynamic" (so don't
bother fixing anything at compile time)

To provide the string that will be used to search for symbols,
    namespaces, files or repository content

@raiph states that he thinks that "require" does a lookup after a successful load.

My only objection about that is that when we load the same library "require" doesn't throw any exception.

Is it silently ignoring the loaded library?
Why bother doing so much work when it can check first that the same namespace is already in use?

In contrary when we pretend that we load a different library then it throws an Exception : "duplicate definition" of the symbol in use.

To demostrate that I conducted the following:

In ./lib directory I place two libraries, the "foo.pm6" which is a unit definition of "foo" with a class A defined in it:

```<code>file "foo.pm6" contents:
-----------------------------------
unit module foo;

class A is export {}
</code>```

and another library "other.pm6" that has inside a definition of "foo" this time with a different class B defined in it.

```<code>file "other.pm6" contents:
-----------------------------------
module foo {
    class B is export {}
}
</code>```

The raku program file contains the following:

```<code>use lib <lib>;

my $name = 'other';           # select one of {'other', 'foo'}

require ::('foo') <A>;        ########> Initial package loading

my $a = try ::('foo::A').new;
say '(1) ' ~ $a.^name;        # (1) foo::A

$a = ::('A').new;
say '(2) ' ~ $a.^name;        # (2) foo::A

try require ::($name);        # if $name eq 'other' => throws exception, if $name eq 'foo' => does nothing
with $! {.say};               # P6M Merging GLOBAL symbols failed: duplicate definition of symbol foo ...

$a = try ::('foo::A').new;
say '(3) ' ~ $a.^name;        # (3) foo::A

$a = ::('A').new;
say '(4) ' ~ $a.^name;        # (4) foo::A
</code>```

From the example above we see that when we try to reload the foo namespace, hidden in a file with a different name (just to trick raku) it throws an exception.

Therefore I conclude that maybe "require" checks first for a namespace that has the same name as the provided string.

By the way, checking about this, I stumbled upon a strange behaviour. It's the following:

If we use "use foo;" in line: "Initial package loading" instead of "require ::('foo') ;", we get the following results:

```<code>(1) foo::A
(2) foo::A
No such symbol 'other' ...

(3) Any
(4) foo::A
</code>```

The lookup of 'foo::A' in (3) doesn't find anything !!!

Furthermore if I change the library file: "other.pm6" with the following (class A instead of B - as in the foo.pm6)

```<code>file "other.pm6" contents:
-----------------------------------
module foo {
    class A is export {}
}
</code>```

the result seem to revert to the expected:

```<code>(1) foo::A
(2) foo::A
No such symbol 'other' ...

(3) foo::A
(4) foo::A
</code>```

Is it a bug or something else that I'm missing?

答:
require does some things during compilation if it can.

require Module;
say Module;
```

<p>It assumes that loading that module will give you something with the name of <code>Module</code>.</p>

<p>So it installs a temporary symbol with that name at compile time.</p>

<p>That is the only thing it does at compile time.<br>
(So I fibbed when I said “some things”.)</p>

<pre class="lang-raku prettyprint-override"><code>if Bool.pick {
    require module-which-does-not-exist;

    module-which-does-not-exist.method-call()
}
</code>```

About half of the time the above does nothing.

The other half of the time it complains at run-time that it can't find the module.

(I chose Bool.pick instead of False so the compile-time optimizer definitely can't optimize it away.)

When you call it with something other than an identifier, it doesn't know at compile-time what the module will be.
So it can't create a temporary namespace.

require 'Module';
say Module; # COMPILE ERROR: undeclared name
```

<pre class="lang-raku prettyprint-override"><code>require Module; # RUNTIME ERROR: can't find 'Module'
say Module;
</code>```

require 'Module'; # RUNTIME ERROR: can't find 'Module'
say ::('Module');
```

<pre class="lang-raku prettyprint-override"><code>if False {
    require Module;
    say Module;
}
# no error at all
</code>```

if False {
    require 'Module';
    say ::('Module');
}
# no error at all
```

Body:
My question is related to the behaviour of require when used with static or dynamic resolution of the desired namespace.

I'll try to present my understanding of things:

[ 1 ] Use "require" with a literal

    { require MODULE; }

In this case the compiler checks to see if MODULE has already been declared as a symbol.
If it hasn't, the compiler declares it, and binds it to an empty placeholder package it's just created for this "require"

{
    my $response = ::('MODULE');  # this happens at runtime
    say $response.^name;          # MODULE doesn't exist so the lookup results in the compilation-phase placeholder package: MODULE

    try require MODULE;           # although the execution order of require comes after the lookup,
                                  # the placeholder package creation was done during compilation and the package is present in the current scope during run-time
}

[ 2 ] Use "require" with a String

    { try require 'FILE_PATH'; }

In this case "require" is trying to find (at run-time) a file that is defined by the filename declared in the string.
If found (with appropriate content: modules, packages etc.) then it creates a namespace(s) in the current scope and loads it with the content(s) of the file.

[ 3 ] Use "require" with a dynamic lookup

    { try require ::('MODULE'); }

It seems to me that in that case "require" behaves NOT as a "normal" subroutine.

When we use "require" with "dynamic lookup" then the core functionality of the dynamic lookup is "melted" in a new routine that behaves differently than we would expect.

The fact is that the result of the "dynamic lookup" routine is either a symbol or a Failure.

If "require" behaves like a "normal" subroutine, then the only input it could use, would be the result of the dynamic lookup that followed it (Namespace or Failure).

But it is also a fact that in the case of a Failure (as the result of dynamic lookup), "require" continues searching the repositories for a proper package (as is normally the case, using nevertheless the argument we gave to dynamic lookup: 'MODULE').

So obviously "require" isn't behaving like a "normal" subroutine in that sense.

As the result of my line of thought the combination of require + dynamic lookup resembles the following construct:

{ modified_dynamic_lookup('MODULE') :if_symbol_not_found_search_repositories_and_if_appropriate_package_found_create_namespace_and_load_package_contents; }

My concern is my understanding of case [3].

How does require + dynamic lookup work? (analytically speaking - what are the steps followed by the compiler at first and then by the runtime?)

[ Post Scriptum ]

I agree with @raiph that "require" is NOT a subroutine and that it is deeply integrated in the language.

In that sense the "dynamic lookup construct" that follows the require "instruction" is used for 2 things:

To notify the compiler that the construct is "dynamic" (so don't
bother fixing anything at compile time)

To provide the string that will be used to search for symbols,
    namespaces, files or repository content

@raiph states that he thinks that "require" does a lookup after a successful load.

My only objection about that is that when we load the same library "require" doesn't throw any exception.

Is it silently ignoring the loaded library?
Why bother doing so much work when it can check first that the same namespace is already in use?

In contrary when we pretend that we load a different library then it throws an Exception : "duplicate definition" of the symbol in use.

To demostrate that I conducted the following:

In ./lib directory I place two libraries, the "foo.pm6" which is a unit definition of "foo" with a class A defined in it:

file "foo.pm6" contents:
-----------------------------------
unit module foo;

class A is export {}

and another library "other.pm6" that has inside a definition of "foo" this time with a different class B defined in it.

file "other.pm6" contents:
-----------------------------------
module foo {
    class B is export {}
}

The raku program file contains the following:

use lib <lib>;

my $name = 'other';           # select one of {'other', 'foo'}

require ::('foo') ;        ########> Initial package loading

my $a = try ::('foo::A').new;
say '(1) ' ~ $a.^name;        # (1) foo::A

$a = ::('A').new;
say '(2) ' ~ $a.^name;        # (2) foo::A

try require ::($name);        # if $name eq 'other' => throws exception, if $name eq 'foo' => does nothing
with $! {.say};               # P6M Merging GLOBAL symbols failed: duplicate definition of symbol foo ...

$a = try ::('foo::A').new;
say '(3) ' ~ $a.^name;        # (3) foo::A

$a = ::('A').new;
say '(4) ' ~ $a.^name;        # (4) foo::A

From the example above we see that when we try to reload the foo namespace, hidden in a file with a different name (just to trick raku) it throws an exception.

Therefore I conclude that maybe "require" checks first for a namespace that has the same name as the provided string.

By the way, checking about this, I stumbled upon a strange behaviour. It's the following:

If we use "use foo;" in line: "Initial package loading" instead of "require ::('foo') ;", we get the following results:

(1) foo::A
(2) foo::A
No such symbol 'other' ...

(3) Any
(4) foo::A

The lookup of 'foo::A' in (3) doesn't find anything !!!

Furthermore if I change the library file: "other.pm6" with the following (class A instead of B - as in the foo.pm6)

file "other.pm6" contents:
-----------------------------------
module foo {
    class A is export {}
}

the result seem to revert to the expected:

(1) foo::A
(2) foo::A
No such symbol 'other' ...

(3) foo::A
(4) foo::A

Is it a bug or something else that I'm missing?

Body:
require does some things during compilation if it can.

require Module;
say Module;

It assumes that loading that module will give you something with the name of Module.

So it installs a temporary symbol with that name at compile time.

That is the only thing it does at compile time.

(So I fibbed when I said “some things”.)

if Bool.pick {
    require module-which-does-not-exist;

    module-which-does-not-exist.method-call()
}

About half of the time the above does nothing.

The other half of the time it complains at run-time that it can't find the module.

(I chose Bool.pick instead of False so the compile-time optimizer definitely can't optimize it away.)

When you call it with something other than an identifier, it doesn't know at compile-time what the module will be.
So it can't create a temporary namespace.

require 'Module';
say Module; # COMPILE ERROR: undeclared name

require Module; # RUNTIME ERROR: can't find 'Module'
say Module;

require 'Module'; # RUNTIME ERROR: can't find 'Module'
say ::('Module');

if False {
    require Module;
    say Module;
}
# no error at all

if False {
    require 'Module';
    say ::('Module');
}
# no error at all


问:
How to decrypt the Obfuscated J2me file? (For reverse engineering)
Im looking into decrypt the jar files. (Obfuscated j2me/jar file).

using decompier, im not able to get the exact files & folders, b'caz of obfuscation.

is thr any possibilities  to break the obfuscated jar file?

Please, im expecting your' valuable replies..

Advance Thanks to all.

By & bye from Munna

答: No. The renaming of files (and variables, etc) during obfuscation is a one-way operation. There are tools that can assist you, but if you want them to have better names you'll have to figure them out yourself really.</p>


问:
Compile error on Serializable when compiling with OpenJdk11
I am getting compilation error when compiling a Jdk8 codebase with OpenJdk11 on Serializable class with error : The type java.io.Serializable cannot be resolved. It is indirectly referenced from required .class files

```<code>[ERROR] Failed to execute goal org.codehaus.mojo:aspectj-maven-plugin:1.4:compile (default) on project test-proj: Compiler errors:
[ERROR] error at public abstract class HiberTypeMapper implements UserType, Serializable {
[ERROR]                                                               ^^^^^^^^^^^
[ERROR] /dev_loc/test-proj/src/main/java/com/hiber/HiberTypeMapper.java:13:0::0 The type java.io.Serializable cannot be resolved. It is indirectly referenced from required .class files
[ERROR]
[ERROR] -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:aspectj-maven-plugin:1.4:compile (default) on project il-commons: Compiler errors:
error at public abstract class HiberTypeMapper implements UserType, Serializable {
                                                              ^^^^^^^^^^^
/dev_loc/test-proj/src/main/java/com/hiber/HiberTypeMapper.java:13:0::0 The type java.io.Serializable cannot be resolved. It is indirectly referenced from required .class files

    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
</code>```

The class which it is complaining on

```<code>package com.hiber;

import java.io.Serializable;

import org.hibernate.usertype.UserType;

public abstract class HiberTypeMapper implements UserType, Serializable {
...
}
</code>```

My versions are :

```<code>Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-03T15:39:06-04:00)
Maven home: /Users/jogi/Apps/apache-maven-3.5.0
Java version: 11.0.7, vendor: AdoptOpenJDK
Java home: /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.13.6", arch: "x86_64", family: "mac"
</code>```

Please suggest the solution, Serializable interface is part of java.base module, so why the compiler is giving error.

答: Jacob G. helped resolving it that it could be due to aspectj-maven-plugin version. For OpenJdk11, version 1.4 will not work. After upgrading it to 1.11, this error is no longer occurring. </p>

Body:
I am getting compilation error when compiling a Jdk8 codebase with OpenJdk11 on Serializable class with error : The type java.io.Serializable cannot be resolved. It is indirectly referenced from required .class files

[ERROR] Failed to execute goal org.codehaus.mojo:aspectj-maven-plugin:1.4:compile (default) on project test-proj: Compiler errors:
[ERROR] error at public abstract class HiberTypeMapper implements UserType, Serializable {
[ERROR]                                                               ^^^^^^^^^^^
[ERROR] /dev_loc/test-proj/src/main/java/com/hiber/HiberTypeMapper.java:13:0::0 The type java.io.Serializable cannot be resolved. It is indirectly referenced from required .class files
[ERROR]
[ERROR] -> [Help 1]
org.apache.maven.lifecycle.LifecycleExecutionException: Failed to execute goal org.codehaus.mojo:aspectj-maven-plugin:1.4:compile (default) on project il-commons: Compiler errors:
error at public abstract class HiberTypeMapper implements UserType, Serializable {
                                                              ^^^^^^^^^^^
/dev_loc/test-proj/src/main/java/com/hiber/HiberTypeMapper.java:13:0::0 The type java.io.Serializable cannot be resolved. It is indirectly referenced from required .class files

    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:213)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:154)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:146)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)

The class which it is complaining on

package com.hiber;

import java.io.Serializable;

import org.hibernate.usertype.UserType;

public abstract class HiberTypeMapper implements UserType, Serializable {
...
}

My versions are :

Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-03T15:39:06-04:00)
Maven home: /Users/jogi/Apps/apache-maven-3.5.0
Java version: 11.0.7, vendor: AdoptOpenJDK
Java home: /Library/Java/JavaVirtualMachines/adoptopenjdk-11.jdk/Contents/Home
Default locale: en_US, platform encoding: UTF-8
OS name: "mac os x", version: "10.13.6", arch: "x86_64", family: "mac"

Please suggest the solution, Serializable interface is part of java.base module, so why the compiler is giving error.


问:
Sub menu in side menu
I did a menu in the left side of the screen that it's rotated but when I try to add a sub menu it appears in the top side of the menu and not in the bottom could someone help me?

ul li{
 display:inline;
 padding: 0.4vw 0.7vw;
}
nav {
  grid-area: menu;
  font-family: Karla;
  display: block;
  writing-mode: vertical-lr;
  transform: rotate(-180deg);
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
}

.dropdown:hover .dropdown-content {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li>Home</li>
    <li>Sobre</li>
    <div class="dropdown">
      <li>Portfólio</li>
      <div class="dropdown-content">
        <li> Link1</li>
      </div>
    </div>
    <li>Website</li>
  </ul>
</nav></code>```

答:
you can add as many submenu items with this</p>

```<code>        ul li{
            display:inline;
            padding: 0.4vw 0.7vw;
        }
        nav {
          grid-area: menu;
          font-family: Karla;
          display: block;
          writing-mode: vertical-rl;
          transform: rotate(-180deg);
        }

        .dropdown {
          position: relative;
          display: inline-block;
        }

        .dropdown-content {
          display: none;
          position: absolute;
          padding-left: 100px
        }

        .dropdown:hover .dropdown-content {
          display: block;
        }
</code>```

```<code>    <nav>
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="sobre.html">Sobre</a></li>
        <div class="dropdown">
          <li><a href="portfolio.html">Portfólio</a></li>
          <div class="dropdown-content">
            <li><a href="#"> Link1</a></li>
            <li><a href="#"> Link1</a></li>
            <li><a href="#"> Link1</a></li>
            <li><a href="#"> Link1</a></li>
            <li><a href="#"> Link1</a></li>
          </div>
        </div>
        <li><a href="website.html">Website</a></li>
      </ul>
    </nav>
</code>```

Title: Sub menu in side menu

Body:
I did a menu in the left side of the screen that it's rotated but when I try to add a sub menu it appears in the top side of the menu and not in the bottom could someone help me?

ul li{
 display:inline;
 padding: 0.4vw 0.7vw;
}
nav {
  grid-area: menu;
  font-family: Karla;
  display: block;
  writing-mode: vertical-lr;
  transform: rotate(-180deg);
}

.dropdown {
  position: relative;
  display: inline-block;
}

.dropdown-content {
  display: none;
  position: absolute;
}

.dropdown:hover .dropdown-content {
  display: block;
}

Home

Sobre

Portfólio

 Link1

Website

Body:
you can add as many submenu items with this

        ul li{
            display:inline;
            padding: 0.4vw 0.7vw;
        }
        nav {
          grid-area: menu;
          font-family: Karla;
          display: block;
          writing-mode: vertical-rl;
          transform: rotate(-180deg);
        }

        .dropdown {
          position: relative;
          display: inline-block;
        }

        .dropdown-content {
          display: none;
          position: absolute;
          padding-left: 100px
        }

        .dropdown:hover .dropdown-content {
          display: block;
        }

    <nav>
      <ul>
        <li><a href="index.html">Home</a></li>
        <li><a href="sobre.html">Sobre</a></li>
        <div class="dropdown">
          <li><a href="portfolio.html">Portfólio</a></li>
          <div class="dropdown-content">
            <li><a href="#"> Link1</a></li>
            <li><a href="#"> Link1</a></li>
            <li><a href="#"> Link1</a></li>
            <li><a href="#"> Link1</a></li>
            <li><a href="#"> Link1</a></li>
          </div>
        </div>
        <li><a href="website.html">Website</a></li>
      </ul>
    </nav>


问:
Stop propagation of a div inside a div
I have a card inside another clickable card. In my case, a carousel inside a card.

In a usual situation, I know I have to use @click.stop to prevent opening the parent card from opening when I click something clickable inside it.... but in my case, I'm having a carousel which do not have a click event, hence, I'm unable to use stop event on it.
 So what happens is when I click the next arrow of the carousel, the parent card pops up too.

 Any idea how do I use stop event handling on something that do not have click event?

```<code>________________
|            <-|---- Master Card
| ------------ |
| |       <--|-|---- Carousel
| |__________| |
|              |
|              |
|______________|
</code>```

答:
tl;dr:

In Vue, if you want to stop the native click events, you have to use the native event modifier:

```<code><carousel @click.native.stop />
</code>```

or

```<code><carousel @click.native.stop="yourMethod" />
</code>```

Internally, the .stop modifier calls .stopPropagation() on the native click event, besides running yourMethod with the click event as param (when yourMethod is specified).

$emit()-ted click events (i.e: $emit('click', payload) don't need stopping, as they are not propagating by default.

complete answer: (regardless of Vue)

Any HTML element has an onclick event.

Therefore,

```<code>document.querySelector('.your-selector').onclick = function(event) {
  event.stopPropagation()
}
</code>```

will stop the click event's propagation (assuming document.querySelector('.your-selector') does select your carousel - note querySelector only returns the first element matching the selector).

If you want to do this on multiple elements matching the same selector, you'll need to use querySelectorAll and iterate through each element. Example:

```<code> [...document.querySelectorAll('.your-selector')].forEach(el => {
   el.onclick = function(e) {
     e.stopPropagation();
   }
 });
</code>```

There are less verbose ways of doing it using frameworks, such as jQuery:

```<code>$('.your-selector').on('click', e => { e.stopPropagation(); })
</code>```

... which does it on the entire collection returned by $('.your-selector'), out of the box.

Title: Stop propagation of a div inside a div

Body:
I have a card inside another clickable card. In my case, a carousel inside a card.

In a usual situation, I know I have to use @click.stop to prevent opening the parent card from opening when I click something clickable inside it.... but in my case, I'm having a carousel which do not have a click event, hence, I'm unable to use stop event on it.
 So what happens is when I click the next arrow of the carousel, the parent card pops up too.

 Any idea how do I use stop event handling on something that do not have click event?

________________
|            <-|---- Master Card
| ------------ |
| |       <--|-|---- Carousel
| |__________| |
|              |
|              |
|______________|

Body:
tl;dr:

In Vue, if you want to stop the native click events, you have to use the native event modifier:

<carousel @click.native.stop />

or

<carousel @click.native.stop="yourMethod" />

Internally, the .stop modifier calls .stopPropagation() on the native click event, besides running yourMethod with the click event as param (when yourMethod is specified).

$emit()-ted click events (i.e: $emit('click', payload) don't need stopping, as they are not propagating by default.

complete answer: (regardless of Vue)

Any HTML element has an onclick event.

Therefore,

document.querySelector('.your-selector').onclick = function(event) {
  event.stopPropagation()
}

will stop the click event's propagation (assuming document.querySelector('.your-selector') does select your carousel - note querySelector only returns the first element matching the selector).

If you want to do this on multiple elements matching the same selector, you'll need to use querySelectorAll and iterate through each element. Example:

 [...document.querySelectorAll('.your-selector')].forEach(el => {
   el.onclick = function(e) {
     e.stopPropagation();
   }
 });

There are less verbose ways of doing it using frameworks, such as jQuery:

$('.your-selector').on('click', e => { e.stopPropagation(); })

... which does it on the entire collection returned by $('.your-selector'), out of the box.


问:
How to cover test for button click in angular? (Stackblitz attached)
I am making a very simple application which has one input box and a button.

Input is for entering email

Subscribe button with event handler

Entering email and click over the button will make an api call, (This method works)

```<code>  subscribeEmail() {
    this.error = '';

        if (this.userForm.controls.email.status === 'VALID') {

      const params = new HttpParams()
                .set('EMAIL', this.userForm.controls.email.value)
        .set('subscribe','Subscribe')
        .set('b_aaa7182511d7bd278fb9d510d_01681f1b55','')
      console.log(params);
            const mailChimpUrl = this.mailChimpEndpoint + params.toString();

            this.http.jsonp<MailChimpResponse>(mailChimpUrl, 'c').subscribe(response => {
        console.log('response ', response)
                if (response.result && response.result !== 'error') {
                    this.submitted = true;
                }
                else {
                    this.error = response.msg;
                }
            }, error => {
                console.error(error);
                this.error = 'Sorry, an error occurred.';
            });
        }
  }
</code>```

A complete working example here

There is no issues with it and you can also check everything works fine.

Requirement: I am in the need to cover test case for this button click and the http call with params.

I am unable to write the test case and it is showing that the tests are not covered for the http calls with params.

The tests that I have written so for for achieving the button click scenario like,

```<code>describe('HelloComponent', () => {

  let component: HelloComponent;
  let fixture: ComponentFixture<HelloComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
       imports: [
        HttpClientTestingModule,
        ReactiveFormsModule
      ],
      declarations: [HelloComponent]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HelloComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('check subscribeEmail function has value', (done: DoneFn) => {

    const subscribeButton = fixture.debugElement.query(By.css('.subscribe'));
    subscribeButton.triggerEventHandler('click', {});

    done();
  });
});
</code>```

And the Working stackblitz with test cases here

(Please look into hello.component.spec.ts )

For button click, I have covered and it works

```<code>    const subscribeButton = fixture.debugElement.query(By.css('.subscribe'));
    subscribeButton.triggerEventHandler('click', {});
</code>```

Could you please help me to achieve the result of covering the test case for the button click that has http call with params?

Update:
After some search I have found that I can use httpmock to call the url with params but I am ending up with error as,

Error: Expected one matching request for criteria "Match URL:
  https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&id=01681f1b55&amp",
  found none.

You can also see the Modified stackblitz with httpMock here...

After all try only I am making this post so please consider this question and provide right solution.

A big thanks in advance.

答:
That was a very long question, I understand that you have put a lot of time to create it. So, I have also put some time to refactor the code to make it as per the best practices. This would require to split your code as a service and make the code better for Unit Testing. (Unit testing for component & service)

Create a service such as MyService and move the http code into it. It would help you unit test component and service separately. I created as below:

```<code>export class MyService {
  mailChimpEndpoint = 'https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&id=01681f1b55&amp';
  constructor(private _http: HttpClient) {}

  submitForm(email: string){
    const params = new HttpParams()
                .set('EMAIL', email)
        .set('subscribe','Subscribe')
        .set('b_aaa7182511d7bd278fb9d510d_01681f1b55','')
    const mailChimpUrl = this.mailChimpEndpoint + params.toString();

    return this._http.jsonp<MailChimpResponse>(mailChimpUrl, 'c')
  }
}
</code>```

Create a Unit test for component as you can see here in the stackblitz . Take a good look at refactored code & how I have covered all cases depending on the scenario. As I have already explained in your previous question, you can test MatSnackBar calls

Similarly, you can write Unit test for service by referring to one my of my articles to test a service

Body:
I am making a very simple application which has one input box and a button.

Input is for entering email

Subscribe button with event handler

Entering email and click over the button will make an api call, (This method works)

  subscribeEmail() {
    this.error = '';

        if (this.userForm.controls.email.status === 'VALID') {

      const params = new HttpParams()
                .set('EMAIL', this.userForm.controls.email.value)
        .set('subscribe','Subscribe')
        .set('b_aaa7182511d7bd278fb9d510d_01681f1b55','')
      console.log(params);
            const mailChimpUrl = this.mailChimpEndpoint + params.toString();

            this.http.jsonp<MailChimpResponse>(mailChimpUrl, 'c').subscribe(response => {
        console.log('response ', response)
                if (response.result && response.result !== 'error') {
                    this.submitted = true;
                }
                else {
                    this.error = response.msg;
                }
            }, error => {
                console.error(error);
                this.error = 'Sorry, an error occurred.';
            });
        }
  }

A complete working example here

There is no issues with it and you can also check everything works fine.

Requirement: I am in the need to cover test case for this button click and the http call with params.

I am unable to write the test case and it is showing that the tests are not covered for the http calls with params.

The tests that I have written so for for achieving the button click scenario like,

describe('HelloComponent', () => {

  let component: HelloComponent;
  let fixture: ComponentFixture<HelloComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
       imports: [
        HttpClientTestingModule,
        ReactiveFormsModule
      ],
      declarations: [HelloComponent]
    }).compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(HelloComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('check subscribeEmail function has value', (done: DoneFn) => {

    const subscribeButton = fixture.debugElement.query(By.css('.subscribe'));
    subscribeButton.triggerEventHandler('click', {});

    done();
  });
});

And the Working stackblitz with test cases here

(Please look into hello.component.spec.ts )

For button click, I have covered and it works

    const subscribeButton = fixture.debugElement.query(By.css('.subscribe'));
    subscribeButton.triggerEventHandler('click', {});

Could you please help me to achieve the result of covering the test case for the button click that has http call with params?

Update:
After some search I have found that I can use httpmock to call the url with params but I am ending up with error as,

Error: Expected one matching request for criteria "Match URL:
  https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&id=01681f1b55&amp",
  found none.

You can also see the Modified stackblitz with httpMock here...

After all try only I am making this post so please consider this question and provide right solution.

A big thanks in advance.

Body:
That was a very long question, I understand that you have put a lot of time to create it. So, I have also put some time to refactor the code to make it as per the best practices. This would require to split your code as a service and make the code better for Unit Testing. (Unit testing for component & service)

Create a service such as MyService and move the http code into it. It would help you unit test component and service separately. I created as below:

export class MyService {
  mailChimpEndpoint = 'https://gmail.us10.list-manage.com/subscribe/post-json?u=aaa7182511d7bd278fb9d510d&amp;id=01681f1b55&amp';
  constructor(private _http: HttpClient) {}

  submitForm(email: string){
    const params = new HttpParams()
                .set('EMAIL', email)
        .set('subscribe','Subscribe')
        .set('b_aaa7182511d7bd278fb9d510d_01681f1b55','')
    const mailChimpUrl = this.mailChimpEndpoint + params.toString();

    return this._http.jsonp<MailChimpResponse>(mailChimpUrl, 'c')
  }
}

Create a Unit test for component as you can see here in the stackblitz . Take a good look at refactored code & how I have covered all cases depending on the scenario. As I have already explained in your previous question, you can test MatSnackBar calls

Similarly, you can write Unit test for service by referring to one my of my articles to test a service


问:
Fastest way to convert a number to radix 64 in JavaScript?
In JavaScript you can convert a number to a string representation with a specific radix as follows:

```<code>(12345).toString(36) // "9ix"
</code>```

...and you can convert it back to a regular number like this:

```<code>parseInt("9ix", 36) // 12345
</code>```

36 is the highest radix you can specify. It apparently uses the characters 0-9 and a-z for the digits (36 total).

My question: what's the fastest way to convert a number to a base 64 representation (for example, using A-Z, and - and _ for the extra 28 digits)?

Update: Four people have posted responses saying this question is duplicated, or that I'm looking for Base64. I'm not.

"Base64" is a way of encoding binary data in a simple ASCII character set, to make it safe for transfer over networks etc. (so that text-only systems won't garble the binary).

That's not what I'm asking about. I'm asking about converting numbers to a radix 64 string representation. (JavaScript's toString(radix) does this automatically for any radix up to 36; I need a custom function to get radix 64.)

Update 2: Here are some input & output examples...

```<code>0   → "0"
1   → "1"
9   → "9"
10  → "a"
35  → "z"
61  → "Z"
62  → "-"
63  → "_"
64  → "10"
65  → "11"
128 → "20"
etc.
</code>```

答: In a mozilla or webkit browser you can use btoa() and atob() to encode and decode base64.</p>

Body:
In JavaScript you can convert a number to a string representation with a specific radix as follows:

(12345).toString(36) // "9ix"

...and you can convert it back to a regular number like this:

parseInt("9ix", 36) // 12345

36 is the highest radix you can specify. It apparently uses the characters 0-9 and a-z for the digits (36 total).

My question: what's the fastest way to convert a number to a base 64 representation (for example, using A-Z, and - and _ for the extra 28 digits)?

Update: Four people have posted responses saying this question is duplicated, or that I'm looking for Base64. I'm not.

"Base64" is a way of encoding binary data in a simple ASCII character set, to make it safe for transfer over networks etc. (so that text-only systems won't garble the binary).

That's not what I'm asking about. I'm asking about converting numbers to a radix 64 string representation. (JavaScript's toString(radix) does this automatically for any radix up to 36; I need a custom function to get radix 64.)

Update 2: Here are some input & output examples...

0   → "0"
1   → "1"
9   → "9"
10  → "a"
35  → "z"
61  → "Z"
62  → "-"
63  → "_"
64  → "10"
65  → "11"
128 → "20"
etc.


问:
How to align a label in Qt Designer without cutting the label content?
I'm trying to create a widget that will act as a navigation bar. It is formed by some buttons that are separated by arrows.

I'm trying to replicate this picture in Qt Designer using labels with the arrow character → . The problem is that this character is bigger than it seems so when I resize the container, the lower part of the arrow disappears.

I have tried to use the vertical layout using a vertical spacer to align the arrow character as the same height as the buttons but the character was cut anyways.

答:
I can't reproduce your example by using just the standard settings.
I added two buttons and a label to the horizontalLayout and set the label font size to 55. I also set the text alignment to horizontal center and vertical center.

You will always have more space at the top cause this is the content of the ascii char.

Maybe it's better to use a simple icon?

EDIT:

You can also add a label or a button with a pixmap/icon which is resizeing with the window:


问:
Is there a null std::ostream implementation in C++ or libraries?
I'm looking for a std::ostream implementation that acts like /dev/null.   It would just ignore anything that is streamed to it.  Does such a thing exist in the standard libraries or Boost?  Or do I have to roll my own?

答:
You can do it without third-party libraries. Just set the associated stream buffer to nullptr using rdbuf and your job is done

```<code>std::cout << "Hello,";
std::cout.rdbuf(nullptr);
std::cout << " world!\n";
</code>```

Online example here.

Body:
You can do it without third-party libraries. Just set the associated stream buffer to nullptr using rdbuf and your job is done

std::cout << "Hello,";
std::cout.rdbuf(nullptr);
std::cout << " world!\n";

Online example here.


问:
Can you cache url under some custom key using Fresco?
I would like to cache url using Fresco but I need to cache it under some key, tag or something and retrieve it using that key or tag. Is it possible doing that using fresco?</p>

答:
You can implement a custom CacheKeyFactory which takes an ImageRequest, which you can then use to create cache keys for.

```<code>CacheKeyFactory myFactory = new CacheKeyFactory() {
  @Override
  public CacheKey getBitmapCacheKey(ImageRequest request, Object callerContext) {
    // your logic goes here
    return new BitmapMemoryCacheKey(
        getCacheKeySourceUri(request.getSourceUri()).toString(),
        request.getResizeOptions(),
        request.getRotationOptions(),
        request.getImageDecodeOptions(),
        null,
        null,
        callerContext);
  }

}
ImagePipelineConfig.Builder builder = ...
builder.setCacheKeyFactory(myFactory);

Fresco.initialize(c, builder.build());
</code>```

Default implementation: https://github.com/facebook/fresco/blob/cc75c37eb777b000426a2373312e3b143c8ed9f7/imagepipeline/src/main/java/com/facebook/imagepipeline/cache/DefaultCacheKeyFactory.java

Body:
You can implement a custom CacheKeyFactory which takes an ImageRequest, which you can then use to create cache keys for.

CacheKeyFactory myFactory = new CacheKeyFactory() {
  @Override
  public CacheKey getBitmapCacheKey(ImageRequest request, Object callerContext) {
    // your logic goes here
    return new BitmapMemoryCacheKey(
        getCacheKeySourceUri(request.getSourceUri()).toString(),
        request.getResizeOptions(),
        request.getRotationOptions(),
        request.getImageDecodeOptions(),
        null,
        null,
        callerContext);
  }

}
ImagePipelineConfig.Builder builder = ...
builder.setCacheKeyFactory(myFactory);

Fresco.initialize(c, builder.build());

Default implementation: https://github.com/facebook/fresco/blob/cc75c37eb777b000426a2373312e3b143c8ed9f7/imagepipeline/src/main/java/com/facebook/imagepipeline/cache/DefaultCacheKeyFactory.java


问:
Why my pygame game with a tiled map is lagging?
I just started pygame and I started coding a little game, but when I put the code for the tiled map my game lagged! I don't understand why so I ask you.
my code:

```<code>import pygame
from player import Player
from level import Level

clock = pygame.time.Clock()

from pygame.locals import *

pygame.init()

WIDHT = 1024
HEIGHT = 768
MAP_FILE = "niveau.txt"

pygame.display.set_caption("TEST")
screen = pygame.display.set_mode((WIDHT, HEIGHT))

player = Player()
moving_right = False
moving_left = False
moving_up = False
moving_down = False
i = 0

level = Level()
level.generer(MAP_FILE)

while True:
    screen.fill((146,244,255))
    level.afficher(screen, 0, 0, WIDHT, HEIGHT)

    player.movement = [0, 0]
    if moving_right == True:
        player.movement[0] += 5
    if moving_left == True:
        player.movement[0] -= 5
    if moving_up == True:
        player.movement[1] -= 5
    if moving_down == True:
        player.movement[1] += 5
    player.rect.x += player.movement[0]
    player.rect.y += player.movement[1]
    screen.blit(player.original_image, player.rect)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break
            pygame.quit()

        if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                moving_right = True
            if event.key == K_LEFT:
                moving_left = True
            if event.key == K_UP:
                moving_up = True
            if event.key == K_DOWN:
                moving_down = True

        if event.type == KEYUP:
            if event.key == K_RIGHT:
                moving_right = False
            if event.key == K_LEFT:
                moving_left = False
            if event.key == K_UP:
                moving_up = False
            if event.key == K_DOWN:
                moving_down = False

    pygame.display.update()
    clock.tick(60)
    #i += 1
</code>```

and level.py:

```<code>import pygame

class Level():
    def __init__(self):
        self.structure = 0
        self.map = []
        self.grass = pygame.image.load("assets/bloc/normal_blocks/grass.png").convert_alpha()
        self.tree = pygame.image.load("assets/bloc/collidables_blocks/tree_grass.png").convert_alpha()
        self.no_texture = pygame.image.load("assets/bloc/specials_blocks/no_texture.png").convert_alpha()

    def generer(self, map_file_name):
        with open(map_file_name, "r") as fichier:
            structure_niveau = []
            for ligne in fichier:
                ligne_niveau = []
                for sprite in ligne:
                    if sprite != '\n':
                        ligne_niveau.append(sprite)
                structure_niveau.append(ligne_niveau)
            self.structure = structure_niveau

    def afficher(self, fenetre, x, y, screen_widht, screen_height):
        tileSize = 64
        num_ligne = 0
        for ligne in self.structure:
            num_case = 0
            for sprite in ligne:
                x = num_case * tileSize
                y = num_ligne * tileSize
                tile_rect = pygame.Rect(x, y, 64, 64)
                screenRect = pygame.Rect(0, 0, screen_widht + 64, screen_height + 64)

                #Normal Bolcks
                if sprite == 'G' and screenRect.colliderect(tile_rect):
                    fenetre.blit(self.grass, (x, y))

                #Collidables blocks
                elif sprite == 'T' and screenRect.colliderect(tile_rect):
                    fenetre.blit(self.tree, (x, y))

                #specials bolcks
                else:
                    if screenRect.colliderect(tile_rect):
                        fenetre.blit(self.no_texture, (x, y))

                num_case += 1
            num_ligne += 1
        #pygame.draw.rect(fenetre, (255, 0, 0), self.aroundPlayer)
</code>```

there is also player.py but it's not important!
Thank you !

答:
The game is lagging, because the playground is generated in every frame. Create a pygame.Surface with the size of the playground and draw all the tiles on it:

tileSize = 64
size_y, size_x = len(self.structure), len(self.structure[0])
self.field = pygame.Surface((size_x * tileSize, size_y * tileSize))
for iy, line in enumerate(self.structure):
    for ix, sprite in enumerate(line):
        tile_surf = self.no_texture
        if sprite == 'G':
            tile_surf = self.grass
        if sprite == 'T':
            tile_surf = self.tree
        self.field.blit(tile_surf, (ix*tileSize, iy*tileSize))
```

<p>Blit the playground an area of the playground with the size of the window, on the window, in every frame:</p>

<pre class="lang-py prettyprint-override"><code>fenetre.blit(self.field, (0, 0), (x, y, screen_widht, screen_height))
</code>```

Class Level:

class Level():
    def __init__(self):
        self.structure = 0
        self.map = []
        self.grass = pygame.image.load("assets/bloc/normal_blocks/grass.png").convert_alpha()
        self.tree = pygame.image.load("assets/bloc/collidables_blocks/tree_grass.png").convert_alpha()
        self.no_texture = pygame.image.load("assets/bloc/specials_blocks/no_texture.png").convert_alpha()

    def generer(self, map_file_name):
        with open(map_file_name, "r") as fichier:
            structure_niveau = []
            for ligne in fichier:
                ligne_niveau = []
                for sprite in ligne:
                    if sprite != '\n':
                        ligne_niveau.append(sprite)
                structure_niveau.append(ligne_niveau)
            self.structure = structure_niveau
            self.createMap()

    def createMap(self):
        tileSize = 64
        size_y, size_x = len(self.structure), len(self.structure[0])
        self.field = pygame.Surface((size_x * tileSize, size_y * tileSize))
        for iy, line in enumerate(self.structure):
            for ix, sprite in enumerate(line):
                tile_surf = self.no_texture
                if sprite == 'G':
                    tile_surf = self.grass
                if sprite == 'T':
                    tile_surf = self.tree
                self.field.blit(tile_surf, (ix*tileSize, iy*tileSize))

    def afficher(self, fenetre, x, y, screen_widht, screen_height):
        fenetre.blit(self.field, (0, 0), (x, y, screen_widht, screen_height))
```

Body:
I just started pygame and I started coding a little game, but when I put the code for the tiled map my game lagged! I don't understand why so I ask you.
my code:

import pygame
from player import Player
from level import Level

clock = pygame.time.Clock()

from pygame.locals import *

pygame.init()

WIDHT = 1024
HEIGHT = 768
MAP_FILE = "niveau.txt"

pygame.display.set_caption("TEST")
screen = pygame.display.set_mode((WIDHT, HEIGHT))

player = Player()
moving_right = False
moving_left = False
moving_up = False
moving_down = False
i = 0

level = Level()
level.generer(MAP_FILE)

while True:
    screen.fill((146,244,255))
    level.afficher(screen, 0, 0, WIDHT, HEIGHT)

    player.movement = [0, 0]
    if moving_right == True:
        player.movement[0] += 5
    if moving_left == True:
        player.movement[0] -= 5
    if moving_up == True:
        player.movement[1] -= 5
    if moving_down == True:
        player.movement[1] += 5
    player.rect.x += player.movement[0]
    player.rect.y += player.movement[1]
    screen.blit(player.original_image, player.rect)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            break
            pygame.quit()

        if event.type == KEYDOWN:
            if event.key == K_RIGHT:
                moving_right = True
            if event.key == K_LEFT:
                moving_left = True
            if event.key == K_UP:
                moving_up = True
            if event.key == K_DOWN:
                moving_down = True

        if event.type == KEYUP:
            if event.key == K_RIGHT:
                moving_right = False
            if event.key == K_LEFT:
                moving_left = False
            if event.key == K_UP:
                moving_up = False
            if event.key == K_DOWN:
                moving_down = False

    pygame.display.update()
    clock.tick(60)
    #i += 1

and level.py:

import pygame

class Level():
    def __init__(self):
        self.structure = 0
        self.map = []
        self.grass = pygame.image.load("assets/bloc/normal_blocks/grass.png").convert_alpha()
        self.tree = pygame.image.load("assets/bloc/collidables_blocks/tree_grass.png").convert_alpha()
        self.no_texture = pygame.image.load("assets/bloc/specials_blocks/no_texture.png").convert_alpha()

    def generer(self, map_file_name):
        with open(map_file_name, "r") as fichier:
            structure_niveau = []
            for ligne in fichier:
                ligne_niveau = []
                for sprite in ligne:
                    if sprite != '\n':
                        ligne_niveau.append(sprite)
                structure_niveau.append(ligne_niveau)
            self.structure = structure_niveau

    def afficher(self, fenetre, x, y, screen_widht, screen_height):
        tileSize = 64
        num_ligne = 0
        for ligne in self.structure:
            num_case = 0
            for sprite in ligne:
                x = num_case * tileSize
                y = num_ligne * tileSize
                tile_rect = pygame.Rect(x, y, 64, 64)
                screenRect = pygame.Rect(0, 0, screen_widht + 64, screen_height + 64)

                #Normal Bolcks
                if sprite == 'G' and screenRect.colliderect(tile_rect):
                    fenetre.blit(self.grass, (x, y))

                #Collidables blocks
                elif sprite == 'T' and screenRect.colliderect(tile_rect):
                    fenetre.blit(self.tree, (x, y))

                #specials bolcks
                else:
                    if screenRect.colliderect(tile_rect):
                        fenetre.blit(self.no_texture, (x, y))

                num_case += 1
            num_ligne += 1
        #pygame.draw.rect(fenetre, (255, 0, 0), self.aroundPlayer)

there is also player.py but it's not important!
Thank you !

Body:
The game is lagging, because the playground is generated in every frame. Create a pygame.Surface with the size of the playground and draw all the tiles on it:

tileSize = 64
size_y, size_x = len(self.structure), len(self.structure[0])
self.field = pygame.Surface((size_x * tileSize, size_y * tileSize))
for iy, line in enumerate(self.structure):
    for ix, sprite in enumerate(line):
        tile_surf = self.no_texture
        if sprite == 'G':
            tile_surf = self.grass
        if sprite == 'T':
            tile_surf = self.tree
        self.field.blit(tile_surf, (ix*tileSize, iy*tileSize))

Blit the playground an area of the playground with the size of the window, on the window, in every frame:

fenetre.blit(self.field, (0, 0), (x, y, screen_widht, screen_height))

Class Level:

class Level():
    def __init__(self):
        self.structure = 0
        self.map = []
        self.grass = pygame.image.load("assets/bloc/normal_blocks/grass.png").convert_alpha()
        self.tree = pygame.image.load("assets/bloc/collidables_blocks/tree_grass.png").convert_alpha()
        self.no_texture = pygame.image.load("assets/bloc/specials_blocks/no_texture.png").convert_alpha()

    def generer(self, map_file_name):
        with open(map_file_name, "r") as fichier:
            structure_niveau = []
            for ligne in fichier:
                ligne_niveau = []
                for sprite in ligne:
                    if sprite != '\n':
                        ligne_niveau.append(sprite)
                structure_niveau.append(ligne_niveau)
            self.structure = structure_niveau
            self.createMap()

    def createMap(self):
        tileSize = 64
        size_y, size_x = len(self.structure), len(self.structure[0])
        self.field = pygame.Surface((size_x * tileSize, size_y * tileSize))
        for iy, line in enumerate(self.structure):
            for ix, sprite in enumerate(line):
                tile_surf = self.no_texture
                if sprite == 'G':
                    tile_surf = self.grass
                if sprite == 'T':
                    tile_surf = self.tree
                self.field.blit(tile_surf, (ix*tileSize, iy*tileSize))

    def afficher(self, fenetre, x, y, screen_widht, screen_height):
        fenetre.blit(self.field, (0, 0), (x, y, screen_widht, screen_height))


问:
Image.open() cannot identify image file - Python?
I am running Python 2.7 in Visual Studio 2013. The code previously worked ok when in Spyder, but when I run:

```<code>import numpy as np
import scipy as sp
import math as mt
import matplotlib.pyplot as plt
import Image
import random

# (0, 1) is N
SCALE = 2.2666 # the scale is chosen to be 1 m = 2.266666666 pixels
MIN_LENGTH = 150 # pixels

PROJECT_PATH = 'C:\\cimtrack_v1'
im = Image.open(PROJECT_PATH + '\\ST.jpg')
</code>```

I end up with the following errors:

```<code>Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\cimtrack_v1\PythonApplication1\dr\trajgen.py", line 19, in <module>
    im = Image.open(PROJECT_PATH + '\\ST.jpg')
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 2020, in open
    raise IOError("cannot identify image file")
IOError: cannot identify image file
</code>```

Why is it so and how may I fix it?

As suggested, I have used the Pillow installer to my Python 2.7. But weirdly, I end up with this:

```<code>>>> from PIL import Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named PIL

>>> from pil import Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named pil

>>> import PIL.Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named PIL.Image

>>> import PIL
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named PIL
</code>```

All fail!

答:
For whoever reaches here with the error colab PIL UnidentifiedImageError: cannot identify image file in Google Colab, with a new PIL versions, and none of the previous solutions works for him:

Simply restart the environment, your installed PIL version is probably outdated.

Body:
I am running Python 2.7 in Visual Studio 2013. The code previously worked ok when in Spyder, but when I run:

import numpy as np
import scipy as sp
import math as mt
import matplotlib.pyplot as plt
import Image
import random

# (0, 1) is N
SCALE = 2.2666 # the scale is chosen to be 1 m = 2.266666666 pixels
MIN_LENGTH = 150 # pixels

PROJECT_PATH = 'C:\\cimtrack_v1'
im = Image.open(PROJECT_PATH + '\\ST.jpg')

I end up with the following errors:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\cimtrack_v1\PythonApplication1\dr\trajgen.py", line 19, in <module>
    im = Image.open(PROJECT_PATH + '\\ST.jpg')
  File "C:\Python27\lib\site-packages\PIL\Image.py", line 2020, in open
    raise IOError("cannot identify image file")
IOError: cannot identify image file

Why is it so and how may I fix it?

As suggested, I have used the Pillow installer to my Python 2.7. But weirdly, I end up with this:

>>> from PIL import Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named PIL

>>> from pil import Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named pil

>>> import PIL.Image
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named PIL.Image

>>> import PIL
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: No module named PIL

All fail!