问:
how can i get the value of a variable outside the arrow function in mern stack
i want to get the value of this variable outside the function const custDetail = await registeredUser.findOne(req.params);

```<code>const dashboardReq = async (req, res, next) => {
      try {
        const regCust = await registeredUser.findOne({ mobile: req.params.mobile });

    if (regCust == null) {
      console.log("No user found");
    } else {
      const custDetail = await registeredUser.findOne(req.params);
    }
    res.status(201).json({
      status: "success",
      data: { regCust },
    });
  } catch (error) {
    res.status(400).json({
      status: "fail",
      data: next(error),
    });
  }
};
</code>```

答:
Edit a simple way to pass data to another function using res.locals

router:

```<code>router.get('getDashboardRef/:mobile', userCtl.dashboardReq, userCtl.nextFunction)
</code>```

dashboardReq

```<code>const dashboardReq = async (req, res, next) => {
      try {
        res.locals.regCust = await registeredUser.findOne({ mobile: req.params.mobile });

    if (!res.locals.regCust) {
      console.log("No user found");
      throw new Error("No user found")
    } else {
      res.locals.custDetail = await registeredUser.findOne(req.params);
     next()
    }
  } catch (error) {
    res.status(400).json({
      status: "fail",
      data: error,
    });
  }
};
</code>```

nextFunction

```<code>const nextFunction = (req, res) => {
  //do stuff with res.locals.custDetail
 res.status(201).json({
      status: "success",
      data: { res.locals.regCust },
    });
}
</code>```

Body:
i want to get the value of this variable outside the function const custDetail = await registeredUser.findOne(req.params);

const dashboardReq = async (req, res, next) => {
      try {
        const regCust = await registeredUser.findOne({ mobile: req.params.mobile });

    if (regCust == null) {
      console.log("No user found");
    } else {
      const custDetail = await registeredUser.findOne(req.params);
    }
    res.status(201).json({
      status: "success",
      data: { regCust },
    });
  } catch (error) {
    res.status(400).json({
      status: "fail",
      data: next(error),
    });
  }
};

Body:
Edit a simple way to pass data to another function using res.locals

router:

router.get('getDashboardRef/:mobile', userCtl.dashboardReq, userCtl.nextFunction)

dashboardReq

const dashboardReq = async (req, res, next) => {
      try {
        res.locals.regCust = await registeredUser.findOne({ mobile: req.params.mobile });

    if (!res.locals.regCust) {
      console.log("No user found");
      throw new Error("No user found")
    } else {
      res.locals.custDetail = await registeredUser.findOne(req.params);
     next()
    }
  } catch (error) {
    res.status(400).json({
      status: "fail",
      data: error,
    });
  }
};

nextFunction

const nextFunction = (req, res) => {
  //do stuff with res.locals.custDetail
 res.status(201).json({
      status: "success",
      data: { res.locals.regCust },
    });
}


来源: stackexchange

问:
A bare bones Scala web framework?
Is there a bare-bones Scala web framework? I basically need the essential features such as:

Routing.

GET/POST/PUT parameter handling.

A simple templating engine (content substitution based).

Serialization (JSON, YAML)

I don't like Lift as it does too much for me, as I would like complete control over the generated HTML, meaning that I want to be able to write 100% of the HTML/CSS/JS code.

Is there such a framework? Or is it possible to use Lift in a way that no HTML is generated behind the scenes? Or would I be better of writing a normal servlet?

答:
Peter gave a great answer... I'll expand on it a little.

Lift gives you a ton of control and access to raw HTTP requests as well as providing a ton of abstractions on top of the HTTP level.  It's your choice on how much or how little you want Lift to do.

You can built a REST-based application using Lift's RestHelper.  See http://simply.liftweb.net/index-Chapter-5.html  The advantage that Lift's RestHelper gives you over most MVC/Routing based approaches is type-safety and access control at the very edge of your application.  But using Scala's pattern matching extractors, you can insure that parameters delivered to the business logic of your application have already been materialized and checked for access control.  Further, Lift's REST support will be as concise or more concise than other web frameworks.

In terms of Lift's HTML handling, you have a ton of control over the creation of the HTML, as long as you want to generate HTML as a valid DOM rather than as a series of Strings.

Most web frameworks force you to emit Strings when you're composing HTML.  It's up to the developer to properly HTML-escape Strings.  It's up to the developer to make sure that closing tags line up correctly.  With Lift, you get this kind of thing for free.

You can serve HTML from Lift apps in MVC style.  See https://github.com/dpp/hoisted (this is the code that powers http://liftweb.net)

In the "standard" configuration of Lift apps, Lift does some post-processing of the HTML if, and only if, you use certain construct.  So, if you put a  tag in the body, the HTML page, Lift will take the contents of that  tag and move it to the head section of the page.  If you include calls to Lift's Comet support, Lift will insert JavaScript on the page to do long polling.  But these features are optional and they only happen if you use certain features in Lift.

I hope this helps you understand the benefits of using Lift.

ContentLicense: CC BY-SA 3.0

Title: A bare bones Scala web framework?

Body:
Peter gave a great answer... I'll expand on it a little.

Lift gives you a ton of control and access to raw HTTP requests as well as providing a ton of abstractions on top of the HTTP level.  It's your choice on how much or how little you want Lift to do.

You can built a REST-based application using Lift's RestHelper.  See http://simply.liftweb.net/index-Chapter-5.html  The advantage that Lift's RestHelper gives you over most MVC/Routing based approaches is type-safety and access control at the very edge of your application.  But using Scala's pattern matching extractors, you can insure that parameters delivered to the business logic of your application have already been materialized and checked for access control.  Further, Lift's REST support will be as concise or more concise than other web frameworks.

In terms of Lift's HTML handling, you have a ton of control over the creation of the HTML, as long as you want to generate HTML as a valid DOM rather than as a series of Strings.

Most web frameworks force you to emit Strings when you're composing HTML.  It's up to the developer to properly HTML-escape Strings.  It's up to the developer to make sure that closing tags line up correctly.  With Lift, you get this kind of thing for free.

You can serve HTML from Lift apps in MVC style.  See https://github.com/dpp/hoisted (this is the code that powers http://liftweb.net)

In the "standard" configuration of Lift apps, Lift does some post-processing of the HTML if, and only if, you use certain construct.  So, if you put a <head> tag in the body, the HTML page, Lift will take the contents of that <head> tag and move it to the head section of the page.  If you include calls to Lift's Comet support, Lift will insert JavaScript on the page to do long polling.  But these features are optional and they only happen if you use certain features in Lift.

I hope this helps you understand the benefits of using Lift.


问:
authenticate a server application with an OAuth2 flow

Probleme

I want to create a server application that modifies playlists on spotify, deezer and youtube (to create multi-platform playlists). My problem is that these different services require OAuth2 authentication to manipulate playlists, and that this authentication requires human intervention

What I've tried

I tried to use the api key, but it did not allow me to edit the playlist (access_key needed).

My Research

from what I understood from the different documentation, the api key is made for server applications (like my case) and that the OAuth2 authentication is more made to authenticate a client.

Question

how to authenticate a server side application with an OAuth2 flow. or how to allow a server application to modify/manipulate playlists on youtube, spotify, deezer.

Details

i use node server.

答:
The first thing you need to under stand is the difference between public and private data.  Private data is data that is not owned by anyone that any one has access to.  Public videos on YouTube for example can be read by anyone.  Private user data is data that is owned by a user that being their play lists for example.

API keys will only give you access to public data not private user data.

The only flow available to you to read YouTube private user data is Ouath2.  What you should do is follow the official node.js sample.

When you run this sample it is single user it will store the user credentials in TOKEN_DIR.  Then it will use the refresh token that was generated in order to request a new access token when ever it needs one.  So you will need to authorize your code once then it will be able to run on  your server without you having to grant it permissions.

```<code>var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the YouTube API.
  authorize(JSON.parse(content), getChannel);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
    if (err) throw err;
    console.log('Token stored to ' + TOKEN_PATH);
  });
}

/**
 * Lists the names and IDs of up to 10 files.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function getChannel(auth) {
  var service = google.youtube('v3');
  service.channels.list({
    auth: auth,
    part: 'snippet,contentDetails,statistics',
    forUsername: 'GoogleDevelopers'
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    var channels = response.data.items;
    if (channels.length == 0) {
      console.log('No channel found.');
    } else {
      console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
                  'it has %s views.',
                  channels[0].id,
                  channels[0].snippet.title,
                  channels[0].statistics.viewCount);
    }
  });
}
</code>```

You may want to monitor it there are some instances where a refresh token will be expired in the event that happens you will need to authorize the application again.

ContentLicense: CC BY-SA 4.0

Body:
The first thing you need to under stand is the difference between public and private data.  Private data is data that is not owned by anyone that any one has access to.  Public videos on YouTube for example can be read by anyone.  Private user data is data that is owned by a user that being their play lists for example.

API keys will only give you access to public data not private user data.

The only flow available to you to read YouTube private user data is Ouath2.  What you should do is follow the official node.js sample.

When you run this sample it is single user it will store the user credentials in TOKEN_DIR.  Then it will use the refresh token that was generated in order to request a new access token when ever it needs one.  So you will need to authorize your code once then it will be able to run on  your server without you having to grant it permissions.

var fs = require('fs');
var readline = require('readline');
var {google} = require('googleapis');
var OAuth2 = google.auth.OAuth2;

// If modifying these scopes, delete your previously saved credentials
// at ~/.credentials/youtube-nodejs-quickstart.json
var SCOPES = ['https://www.googleapis.com/auth/youtube.readonly'];
var TOKEN_DIR = (process.env.HOME || process.env.HOMEPATH ||
    process.env.USERPROFILE) + '/.credentials/';
var TOKEN_PATH = TOKEN_DIR + 'youtube-nodejs-quickstart.json';

// Load client secrets from a local file.
fs.readFile('client_secret.json', function processClientSecrets(err, content) {
  if (err) {
    console.log('Error loading client secret file: ' + err);
    return;
  }
  // Authorize a client with the loaded credentials, then call the YouTube API.
  authorize(JSON.parse(content), getChannel);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 *
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  var clientSecret = credentials.installed.client_secret;
  var clientId = credentials.installed.client_id;
  var redirectUrl = credentials.installed.redirect_uris[0];
  var oauth2Client = new OAuth2(clientId, clientSecret, redirectUrl);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, function(err, token) {
    if (err) {
      getNewToken(oauth2Client, callback);
    } else {
      oauth2Client.credentials = JSON.parse(token);
      callback(oauth2Client);
    }
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 *
 * @param {google.auth.OAuth2} oauth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback to call with the authorized
 *     client.
 */
function getNewToken(oauth2Client, callback) {
  var authUrl = oauth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES
  });
  console.log('Authorize this app by visiting this url: ', authUrl);
  var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  });
  rl.question('Enter the code from that page here: ', function(code) {
    rl.close();
    oauth2Client.getToken(code, function(err, token) {
      if (err) {
        console.log('Error while trying to retrieve access token', err);
        return;
      }
      oauth2Client.credentials = token;
      storeToken(token);
      callback(oauth2Client);
    });
  });
}

/**
 * Store token to disk be used in later program executions.
 *
 * @param {Object} token The token to store to disk.
 */
function storeToken(token) {
  try {
    fs.mkdirSync(TOKEN_DIR);
  } catch (err) {
    if (err.code != 'EEXIST') {
      throw err;
    }
  }
  fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
    if (err) throw err;
    console.log('Token stored to ' + TOKEN_PATH);
  });
}

/**
 * Lists the names and IDs of up to 10 files.
 *
 * @param {google.auth.OAuth2} auth An authorized OAuth2 client.
 */
function getChannel(auth) {
  var service = google.youtube('v3');
  service.channels.list({
    auth: auth,
    part: 'snippet,contentDetails,statistics',
    forUsername: 'GoogleDevelopers'
  }, function(err, response) {
    if (err) {
      console.log('The API returned an error: ' + err);
      return;
    }
    var channels = response.data.items;
    if (channels.length == 0) {
      console.log('No channel found.');
    } else {
      console.log('This channel\'s ID is %s. Its title is \'%s\', and ' +
                  'it has %s views.',
                  channels[0].id,
                  channels[0].snippet.title,
                  channels[0].statistics.viewCount);
    }
  });
}

You may want to monitor it there are some instances where a refresh token will be expired in the event that happens you will need to authorize the application again.


问:
How do I put the image on the right side of the text in a UIButton?
I don't want to use a subview if I can avoid it. I want a UIButton with a background image, text, and an image in it. Right now, when I do that, the image is on the left side of the text. The background image, text, and image all have different highlight states.

答:
Subclassing and over-riding layoutSubviews is probably your best way to go.

Referenced from: iPhone UIButton - image position


问:
how do i run this cpp file in ros
i am new to ROS currently working on ROS Kinetic,i have an issue when i run this linefollowing.cpp file using the command "rosrun roscv linefollowing.cpp" (where roscv is the package name & "linefollowing.cpp" is the .cpp file),

the error;

```<code>/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 19: using: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 20: using: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 21: namespace: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 22: static: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 24: float: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 25: float: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 26: float: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 28: class: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 36: syntax error near unexpected token `('
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 36: `  image_transport::Publisher image_pub_; //image publisher(we subscribe to ardrone image_raw)'
</code>```

the code in this file is;

```<code>    #include <ros/ros.h>
#include <stdio.h>
#include <iostream>
#include "std_msgs/String.h"
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>     //make sure to include the relevant headerfiles
#include <opencv2/highgui/highgui.hpp>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <cv_bridge/CvBridge.h>
#include <cvaux.h>
#include<math.h>
#include <cxcore.h>
#include "turtlesim/Velocity.h"

/*here is a simple program which demonstrates the use of ros and opencv to do image manipulations on video streams given out as image topics from the monocular vision
of robots,here the device used is a ardrone(quad-rotor).*/
using namespace std;
using namespace cv;
namespace enc = sensor_msgs::image_encodings;
static const char WINDOW[] = "Image window";

float prevVelocity_angular ,prevVelocity_linear ,newVelocity_angular ,newVelocity_linear ;
float derive_angular, derive_linear, dt = 0.5;
float horizontalcount;

class ImageConverter
{
  ros::NodeHandle nh_;
  ros::NodeHandle n;
  ros::Publisher pub ;
  ros::Publisher tog;
  image_transport::ImageTransport it_;
  image_transport::Subscriber image_sub_; //image subscriber
  image_transport::Publisher image_pub_; //image publisher(we subscribe to ardrone image_raw)
  std_msgs::String msg;
public:
  ImageConverter()
    : it_(nh_)
  {
      pub= n.advertise<turtlesim::Velocity>("/drocanny/vanishing_points", 500);//
      image_sub_ = it_.subscribe("/ardrone/image_raw", 1, &ImageConverter::imageCb, this);
      image_pub_= it_.advertise("/arcv/Image",1);
  }

  ~ImageConverter()
  {
    cv::destroyWindow(WINDOW);
  }

  void imageCb(const sensor_msgs::ImageConstPtr& msg)
  {

     sensor_msgs::CvBridge bridge;//we need this object bridge for facilitating conversion from ros-img to opencv
   IplImage* img = bridge.imgMsgToCv(msg,"rgb8");  //image being converted from ros to opencv using cvbridge
   turtlesim::Velocity velMsg;
 CvMemStorage* storage = cvCreateMemStorage(0);
     CvSeq* lines = 0;
       int i,c,d;
       float c1[50];
       float m,angle;
          float buf;
          float m1;
       float dis;
       int k=0,k1=0;
      int count=0;

      float xv;
      float yv;
      int vc=0;
     float xvan=0,yvan=0;
      static float xvan1=0,yvan1=0;
    float num=0;
   static float count1=0;
  float dv;
float vxx,vyy;

         cvSetImageROI(img, cvRect(0, 0,170, 140));
        IplImage* out1 = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 3 );   //make sure to feed the image(img) data to the parameters necessary for canny edge output
        IplImage* gray_out = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 1 );
        IplImage* canny_out = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 1 );
        IplImage* gray_out1=cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 3 );
          IplImage* canny_out1 = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 1 );
          IplImage* canny_out2 = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 1 );

        cvSmooth( img, out1, CV_GAUSSIAN, 11, 11 );

      cvCvtColor(out1 , gray_out, CV_RGB2GRAY);
        cvCanny( gray_out, canny_out, 50, 125, 3 );
      cvCvtColor(canny_out ,gray_out1, CV_GRAY2BGR);

       lines = cvHoughLines2( canny_out, storage, CV_HOUGH_PROBABILISTIC, 1, CV_PI/180, 80,50, 10 );
        for( i = 0; i < lines->total; i++ )
        {

             CvPoint* line = (CvPoint*)cvGetSeqElem(lines,i);
{
{
cvLine( out1, line[0], line[1], CV_RGB(0,255,0), 1, 8 );
cvLine( gray_out1, line[0], line[1], CV_RGB(0,255,0), 2, 8 );
xv=line[0].x-line[1].x;
yv=line[0].y-line[1].y;
velMsg.linear = atan2(xv,yv)*180 /3.14159265;
angle=velMsg.linear;
if(velMsg.linear<-90)
{
  velMsg.linear=velMsg.linear+180;
}
buf=(line[0].x+line[1].x)/2;

if(abs(85-buf)<=15)
{
velMsg.angular =0;
}
else
{
velMsg.angular =(85-(line[0].x+line[1].x)/2);
}

if(abs(velMsg.angular)>50)
{
velMsg.angular =0;
}

printf("\nX::Y::X1::Y1::%d:%d:%d:%d",line[0].x,line[0].y,line[1].x,line[1].y);

pub.publish(velMsg);

}

}

cvSeqRemove(lines,i);

{
         cvShowImage( "OUT1", out1 );//lines projected onto the real picture
        cvShowImage( "GRAY_OUT1", gray_out1 );
        cv::waitKey(3);
   sensor_msgs::ImagePtr out = sensor_msgs::CvBridge::cvToImgMsg(img, "rgb8");//image converted from opencv to ros for publishing
   image_pub_.publish(out);
 cvClearMemStorage(storage);
cvReleaseMemStorage(&storage);
}

};

int main(int argc, char** argv)
{
  ros::init(argc, argv, "image_converter");
  ImageConverter ic;
  ros::spin();
  return 0;
}
</code>```

CMakeLists.txt of the package "roscv" ;

```<code>cmake_minimum_required(VERSION 3.0.2)
project(roscv)
find_package(catkin REQUIRED COMPONENTS
  ardrone_autonomy
  cv_bridge
  image_transport
  roscpp
  sensor_msgs
  std_msgs
  std_srvs
  turtlesim
)
find_package(OpenCV)
include_directories(
  ${catkin_INCLUDE_DIRS}
)
include_directories(${OpenCV_INCLUDE_DIRS})

catkin_package(
    CATKIN_DEPENDS
     ardrone_autonomy
     cv_bridge
     image_transport
     roscpp
     sensor_msgs
     std_msgs
     std_srvs
     turtlesim
)

catkin_package(
INCLUDE_DIRS include
LIBRARIES roscv
CATKIN_DEPENDS ardrone_autonomy cv_bridge image_transport opencv2 roscpp sensor_msgs std_msgs std_srvs turtlesim
DEPENDS system_lib
)

add_executable(linefollowing src/linefollowing.cpp)

target_link_libraries(linefollowing ${catkin_LIBRARIES})
install(TARGETS linefollowing
  ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
  LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
  RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)
</code>```

any suggestions on how to tackle this issue guys? thank you in advance

答: Based on your CMakeLists.txt you're actually compiling the file to linefollowing in the package roscv. Thus, if you're trying to use rosrun the command should be: rosrun roscv linefollowing. Notice the .cpp isn't included here. This is because what you were trying to run was a cpp source file. These are not directly executable and have to be compiled first.

Title: how do i run this cpp file in ros

Body:
i am new to ROS currently working on ROS Kinetic,i have an issue when i run this linefollowing.cpp file using the command "rosrun roscv linefollowing.cpp" (where roscv is the package name & "linefollowing.cpp" is the .cpp file),

the error;

/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 19: using: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 20: using: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 21: namespace: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 22: static: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 24: float: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 25: float: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 26: float: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 28: class: command not found
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 36: syntax error near unexpected token `('
/home/badhrisrini/line_follow_ws/src/roscv/src/linefollow.cpp: line 36: `  image_transport::Publisher image_pub_; //image publisher(we subscribe to ardrone image_raw)'

the code in this file is;

    #include <ros/ros.h>
#include <stdio.h>
#include <iostream>
#include "std_msgs/String.h"
#include <image_transport/image_transport.h>
#include <cv_bridge/cv_bridge.h>
#include <sensor_msgs/image_encodings.h>
#include <opencv2/imgproc/imgproc.hpp>     //make sure to include the relevant headerfiles
#include <opencv2/highgui/highgui.hpp>
#include <opencv/cv.h>
#include <opencv/highgui.h>
#include <cv_bridge/CvBridge.h>
#include <cvaux.h>
#include<math.h>
#include <cxcore.h>
#include "turtlesim/Velocity.h"

/*here is a simple program which demonstrates the use of ros and opencv to do image manipulations on video streams given out as image topics from the monocular vision
of robots,here the device used is a ardrone(quad-rotor).*/
using namespace std;
using namespace cv;
namespace enc = sensor_msgs::image_encodings;
static const char WINDOW[] = "Image window";

float prevVelocity_angular ,prevVelocity_linear ,newVelocity_angular ,newVelocity_linear ;
float derive_angular, derive_linear, dt = 0.5;
float horizontalcount;

class ImageConverter
{
  ros::NodeHandle nh_;
  ros::NodeHandle n;
  ros::Publisher pub ;
  ros::Publisher tog;
  image_transport::ImageTransport it_;
  image_transport::Subscriber image_sub_; //image subscriber
  image_transport::Publisher image_pub_; //image publisher(we subscribe to ardrone image_raw)
  std_msgs::String msg;
public:
  ImageConverter()
    : it_(nh_)
  {
      pub= n.advertise<turtlesim::Velocity>("/drocanny/vanishing_points", 500);//
      image_sub_ = it_.subscribe("/ardrone/image_raw", 1, &ImageConverter::imageCb, this);
      image_pub_= it_.advertise("/arcv/Image",1);
  }

  ~ImageConverter()
  {
    cv::destroyWindow(WINDOW);
  }

  void imageCb(const sensor_msgs::ImageConstPtr& msg)
  {

     sensor_msgs::CvBridge bridge;//we need this object bridge for facilitating conversion from ros-img to opencv
   IplImage* img = bridge.imgMsgToCv(msg,"rgb8");  //image being converted from ros to opencv using cvbridge
   turtlesim::Velocity velMsg;
 CvMemStorage* storage = cvCreateMemStorage(0);
     CvSeq* lines = 0;
       int i,c,d;
       float c1[50];
       float m,angle;
          float buf;
          float m1;
       float dis;
       int k=0,k1=0;
      int count=0;

      float xv;
      float yv;
      int vc=0;
     float xvan=0,yvan=0;
      static float xvan1=0,yvan1=0;
    float num=0;
   static float count1=0;
  float dv;
float vxx,vyy;

         cvSetImageROI(img, cvRect(0, 0,170, 140));
        IplImage* out1 = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 3 );   //make sure to feed the image(img) data to the parameters necessary for canny edge output
        IplImage* gray_out = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 1 );
        IplImage* canny_out = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 1 );
        IplImage* gray_out1=cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 3 );
          IplImage* canny_out1 = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 1 );
          IplImage* canny_out2 = cvCreateImage( cvGetSize(img), IPL_DEPTH_8U, 1 );

        cvSmooth( img, out1, CV_GAUSSIAN, 11, 11 );

      cvCvtColor(out1 , gray_out, CV_RGB2GRAY);
        cvCanny( gray_out, canny_out, 50, 125, 3 );
      cvCvtColor(canny_out ,gray_out1, CV_GRAY2BGR);

       lines = cvHoughLines2( canny_out, storage, CV_HOUGH_PROBABILISTIC, 1, CV_PI/180, 80,50, 10 );
        for( i = 0; i < lines->total; i++ )
        {

             CvPoint* line = (CvPoint*)cvGetSeqElem(lines,i);
{
{
cvLine( out1, line[0], line[1], CV_RGB(0,255,0), 1, 8 );
cvLine( gray_out1, line[0], line[1], CV_RGB(0,255,0), 2, 8 );
xv=line[0].x-line[1].x;
yv=line[0].y-line[1].y;
velMsg.linear = atan2(xv,yv)*180 /3.14159265;
angle=velMsg.linear;
if(velMsg.linear<-90)
{
  velMsg.linear=velMsg.linear+180;
}
buf=(line[0].x+line[1].x)/2;

if(abs(85-buf)<=15)
{
velMsg.angular =0;
}
else
{
velMsg.angular =(85-(line[0].x+line[1].x)/2);
}

if(abs(velMsg.angular)>50)
{
velMsg.angular =0;
}

printf("\nX::Y::X1::Y1::%d:%d:%d:%d",line[0].x,line[0].y,line[1].x,line[1].y);

pub.publish(velMsg);

}

}

cvSeqRemove(lines,i);

{
         cvShowImage( "OUT1", out1 );//lines projected onto the real picture
        cvShowImage( "GRAY_OUT1", gray_out1 );
        cv::waitKey(3);
   sensor_msgs::ImagePtr out = sensor_msgs::CvBridge::cvToImgMsg(img, "rgb8");//image converted from opencv to ros for publishing
   image_pub_.publish(out);
 cvClearMemStorage(storage);
cvReleaseMemStorage(&storage);
}

};

int main(int argc, char** argv)
{
  ros::init(argc, argv, "image_converter");
  ImageConverter ic;
  ros::spin();
  return 0;
}

CMakeLists.txt of the package "roscv" ;

cmake_minimum_required(VERSION 3.0.2)
project(roscv)
find_package(catkin REQUIRED COMPONENTS
  ardrone_autonomy
  cv_bridge
  image_transport
  roscpp
  sensor_msgs
  std_msgs
  std_srvs
  turtlesim
)
find_package(OpenCV)
include_directories(
  ${catkin_INCLUDE_DIRS}
)
include_directories(${OpenCV_INCLUDE_DIRS})

catkin_package(
    CATKIN_DEPENDS
     ardrone_autonomy
     cv_bridge
     image_transport
     roscpp
     sensor_msgs
     std_msgs
     std_srvs
     turtlesim
)

catkin_package(
INCLUDE_DIRS include
LIBRARIES roscv
CATKIN_DEPENDS ardrone_autonomy cv_bridge image_transport opencv2 roscpp sensor_msgs std_msgs std_srvs turtlesim
DEPENDS system_lib
)

add_executable(linefollowing src/linefollowing.cpp)

target_link_libraries(linefollowing ${catkin_LIBRARIES})
install(TARGETS linefollowing
  ARCHIVE DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
  LIBRARY DESTINATION ${CATKIN_PACKAGE_LIB_DESTINATION}
  RUNTIME DESTINATION ${CATKIN_PACKAGE_BIN_DESTINATION}
)

any suggestions on how to tackle this issue guys? thank you in advance


问:
Recursive function returns undefined
I have a function which calculates taxes.

```<code>function taxes(tax, taxWage)
{
    var minWage = firstTier; //defined as a global variable
    if (taxWage > minWage)
    {
        //calculates tax recursively calling two other functions difference() and taxStep()
        tax = tax + difference(taxWage) * taxStep(taxWage);
        var newSalary = taxWage - difference(taxWage);
        taxes(tax, newSalary);
    }
    else
    {
        returnTax = tax + taxWage * taxStep(taxWage);
        return returnTax;
    }
}
</code>```

I can't see why it doesn't stop the recursion.

答:
For example taxes(tax, newSalary); returns 100;

```<code>taxes(tax, newSalary); // undefined
</code>```

You expect to see 100 because you called taxes(tax, newSalary) recursively but in fact you got the value (100) and you need to return this value.

```<code>return taxes(tax, newSalary); // 100
// simply it's the same as
// return 100
// because taxes(tax, newSalary) returned 100
</code>```

after return 100 you will get this value.

Title: Recursive function returns undefined

Body:
I have a function which calculates taxes.

function taxes(tax, taxWage)
{
    var minWage = firstTier; //defined as a global variable
    if (taxWage > minWage)
    {
        //calculates tax recursively calling two other functions difference() and taxStep()
        tax = tax + difference(taxWage) * taxStep(taxWage);
        var newSalary = taxWage - difference(taxWage);
        taxes(tax, newSalary);
    }
    else
    {
        returnTax = tax + taxWage * taxStep(taxWage);
        return returnTax;
    }
}

I can't see why it doesn't stop the recursion.

Body:
For example taxes(tax, newSalary); returns 100;

taxes(tax, newSalary); // undefined

You expect to see 100 because you called taxes(tax, newSalary) recursively but in fact you got the value (100) and you need to return this value.

return taxes(tax, newSalary); // 100
// simply it's the same as
// return 100
// because taxes(tax, newSalary) returned 100

after return 100 you will get this value.


问:
Testing if all values in a numpy array are equal
I have a numpy one dimensional array c that is supposed to be filled with the contents of
a + b. I'm first executing a + b on a device using PyOpenCL.

I want to quickly determine the correctness of the result array c in python using numpy slicing.

This is what I currently have

```<code>def python_kernel(a, b, c):
    temp = a + b
    if temp[:] != c[:]:
        print "Error"
    else:
        print "Success!"
</code>```

But I get the error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

But it seems a.any or a.all will just determine whether the values aren't 0.

What should I do if I want to test if all of the scalers in the numpy array temp are equal to every value in the numpy array c?

答: Why not just use numpy.array_equal(a1, a2)[docs]  from NumPy's functions?

Body:
I have a numpy one dimensional array c that is supposed to be filled with the contents of
a + b. I'm first executing a + b on a device using PyOpenCL.

I want to quickly determine the correctness of the result array c in python using numpy slicing.

This is what I currently have

def python_kernel(a, b, c):
    temp = a + b
    if temp[:] != c[:]:
        print "Error"
    else:
        print "Success!"

But I get the error:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

But it seems a.any or a.all will just determine whether the values aren't 0.

What should I do if I want to test if all of the scalers in the numpy array temp are equal to every value in the numpy array c?


问:
Why Device Manager don't open?
I'm working on the Flutter project. After I updated the version of the Android Studio when I click on the device manager to open my devices it doesn't show. I don't know what should I do?

At the first image it's gif image to explain what I mean.

I put the second image to show current version (Bumblebee).

答:
Android studio no android module

Please check whether your flutter project is creating Android module by clicking left side of the android studio.
Also try another SDK location or try renaming it.
Do not delete the previous sdk since it seems it creates some issue while opening the device manager.

Title: Why Device Manager don't open?


问:
react-map-gl Marker is moving when zooming the map
I've built a React app with a map component which renders a map. I tried to add a marker, but the marker keeps moving when I zoom. What is causing this to happen?</p>
```<code>import MapGL, { Marker } from "react-map-gl"
import { useState } from "react";

const Map = () => {
    const [viewState, setViewState] = useState({
        longitude: 4.895168,
        latitude: 52.370216,
        zoom: 10,
    })
    const [marker] = useState({
        longitude: 4.895168,
        latitude: 52.370216,
    })

    return (
        <div className="map">
            <MapGL
                {...viewState}
                style={{ width: "100%", height: "100%" }}
                mapStyle="mapbox://styles/mapbox/streets-v9"
                onMove={(evt) => setViewState(evt.viewState)}
                mapboxAccessToken="my_token"
            >
                <Marker
                    {...marker}
                />
            </MapGL>
        </div>
    )
}

export default Map;
</code>```

答:
The problem was this missing line in my index.html:

```<code><link href="https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css" rel="stylesheet">
</code>```

The documentation tells you nothing about it, had to find it in the source code of this example: https://github.com/visgl/react-map-gl/tree/7.0-release/examples/controls

Body:
I've built a React app with a map component which renders a map. I tried to add a marker, but the marker keeps moving when I zoom. What is causing this to happen?

import MapGL, { Marker } from "react-map-gl"
import { useState } from "react";

const Map = () => {
    const [viewState, setViewState] = useState({
        longitude: 4.895168,
        latitude: 52.370216,
        zoom: 10,
    })
    const [marker] = useState({
        longitude: 4.895168,
        latitude: 52.370216,
    })

    return (

            <MapGL
                {...viewState}
                style={{ width: "100%", height: "100%" }}
                mapStyle="mapbox://styles/mapbox/streets-v9"
                onMove={(evt) => setViewState(evt.viewState)}
                mapboxAccessToken="my_token"
            >
                <Marker
                    {...marker}
                />
            </MapGL>

    )
}

export default Map;

Body:
The problem was this missing line in my index.html:

<link href="https://api.mapbox.com/mapbox-gl-js/v2.6.1/mapbox-gl.css" rel="stylesheet">

The documentation tells you nothing about it, had to find it in the source code of this example: https://github.com/visgl/react-map-gl/tree/7.0-release/examples/controls


问:
Index-based assignment in the loop for Pair, C++
I am new to C++. I want to assign the values to my tuple inside the loop.
The following does not work.

```<code>#include<utility>

std::pair<int, int> myPair;

int main() {
    for(int i=0; i<2; i++) {
        std::get<i>(myPair) = i;
    }
}
</code>```

How could I do it correctly?

答:
Do you have a reason to insist on doing this in a loop? If not, you can just assign to mypair.first and mypair.second.

```<code>#include<utility>

std::pair<int, int> myPair;

int main() {
    myPair.first = 1;
    myPair.second = 2;
}
</code>```

A very useful website to check what's available for standard library types is cppreference.com

Maybe you actually want a std::vector?

#include <vector>

int get_next_value(int); // Not defined in this example.
// You get your values from somewhere...

// note that global variables like this might not be the best idea.
std::vector<int> values;

int main() {
    for (int i=0; i < 2; ++i) {
        values.push_back(get_next_value(i));
    }
}

```

Body:
I am new to C++. I want to assign the values to my tuple inside the loop.
The following does not work.

#include<utility>

std::pair<int, int> myPair;

int main() {
    for(int i=0; i<2; i++) {
        std::get(myPair) = i;
    }
}

How could I do it correctly?

Body:
Do you have a reason to insist on doing this in a loop? If not, you can just assign to mypair.first and mypair.second.

#include<utility>

std::pair<int, int> myPair;

int main() {
    myPair.first = 1;
    myPair.second = 2;
}

A very useful website to check what's available for standard library types is cppreference.com

Maybe you actually want a std::vector?

#include <vector>

int get_next_value(int); // Not defined in this example.
// You get your values from somewhere...

// note that global variables like this might not be the best idea.
std::vector<int> values;

int main() {
    for (int i=0; i < 2; ++i) {
        values.push_back(get_next_value(i));
    }
}


问:
Number of format specifications in 'msgid' and 'msgstr' does not match msgfmt: found 1 fatal error
Django-Admin generates the following error: Execution of msgfmt failed: /home/djuka/project_app/locale/eng/LC_MESSAGES/django.po:49: number of format specifications in 'msgid' and 'msgstr' does not match
msgfmt: found 1 fatal error
CommandError: compilemessages generated one or more errors.

I have the same number of strings in msgid and msgstr and i still get an error. Here is the code.

```<code>#: reBankMini/templates/reBankMiniApp/index.html:135
#, python-format
msgid ""
"Leta 2020 je po svetu nastalo rekordnih 54 milijonov ton elektronskih "
"odpadkov, kar je 21 odstotkov več kot v zadnjih petih letih. E-odpadki so "
"najhitreje rastoči gospodinjski odpadki na svetu, ki jih povzročajo predvsem "
"višje stopnje porabe električne in elektronske opreme, kratki življenjski "
"cikli in malo možnosti za popravila. Le 17,4%% zavrženih e-odpadkov leta "
"2020 je bilo recikliranih. Pri procesu recikliranju pride do številnih "
"okolju nevarnih reakcij. Mi recikliramo drugače. Prizadevamo si za varne, "
"trajnostne in popravljive izdelke, s katerimi bo vsak uporabnik aktivno "
"vključen v reševanje okoljskih problemov."

msgstr ""
"In 2020, a record 54 million tons of electronic "
"waste was generated worldwide, which is 21 percent more than in the last five years. E-waste is "
"the fastest growing household waste in the world, caused mainly by "
"higher levels of consumption of electrical and electronic equipment, short life "
"cycles and little opportunity for repair. Only 17.4% of e-waste discarded in "
"2020 was recycled. Many environmentally hazardous reactions occur "
"during the recycling process. We recycle differently. We strive for safe, "
"sustainable and repairable products that will actively involve every user "
"in solving environmental problems."

</code>```

Here is the index.html file

```<code><div class="rebank-desc">
        <h3>
            {% trans 'Leta 2020 je po svetu nastalo rekordnih 54 milijonov ton elektronskih odpadkov, kar je 21 odstotkov več kot v zadnjih petih letih. E-odpadki so najhitreje rastoči gospodinjski odpadki na svetu, ki jih povzročajo predvsem višje stopnje porabe električne in elektronske opreme, kratki življenjski cikli in malo možnosti za popravila. Le 17,4% zavrženih e-odpadkov leta 2020 je bilo recikliranih. Pri procesu recikliranju pride do številnih okolju nevarnih reakcij. Mi recikliramo drugače. Prizadevamo si za varne, trajnostne in popravljive izdelke, s katerimi bo vsak uporabnik aktivno vključen v reševanje okoljskih problemov.' %}
        </h3>
        <h3>
            {% trans 'Predstavljamo vam RebankMini, prvi power bank (prenosna baterija) na svetu, ki ga poganjajo reciklirane baterijske celice. rEbankMini je v celoti izdelan v Sloveniji in s tem prvi power bank izdelan v Evropi. Sestavljen je iz prestižnega slovenskega lesa, hrasta in oreha. Z nakupom enega rEbankMini-ja nam pomagate zmanjšati izpust toplogrednih plinov za 14,6 kg (CO2eq), ki bi nastali pri proizvodnji izdelka, podobnega našemu.' %}
        </h3>
    </div>
</code>```

答:
I'm not exactly sure what you are trying to do, but I would make a msg class in you app's models.py file. Also, are you trying to make the msgid a translated version of english? If so, making a msg class in your models.py file would provide you with a pk or id which you can use as a replacement for the translated version. The code would look something like this:

from django.db import models
from django.utils import timezone

class Msg(models.Model):
   msgContents = models.TextField()
   sender = models.ForeignKey(User, on_delete=models.CASCADE)
   date_sent = models.DateTimeField(default=timezone.now)

   def __str__(self):
      return '<What you want the Django admin page to use as the title>' # Example: return f'{self.sender} - {self.pk}'
```

I'm not exactly sure if this will help, but it's commonly used code for a message / posting system.

Body:
Django-Admin generates the following error: Execution of msgfmt failed: /home/djuka/project_app/locale/eng/LC_MESSAGES/django.po:49: number of format specifications in 'msgid' and 'msgstr' does not match
msgfmt: found 1 fatal error
CommandError: compilemessages generated one or more errors.

I have the same number of strings in msgid and msgstr and i still get an error. Here is the code.

#: reBankMini/templates/reBankMiniApp/index.html:135
#, python-format
msgid ""
"Leta 2020 je po svetu nastalo rekordnih 54 milijonov ton elektronskih "
"odpadkov, kar je 21 odstotkov več kot v zadnjih petih letih. E-odpadki so "
"najhitreje rastoči gospodinjski odpadki na svetu, ki jih povzročajo predvsem "
"višje stopnje porabe električne in elektronske opreme, kratki življenjski "
"cikli in malo možnosti za popravila. Le 17,4%% zavrženih e-odpadkov leta "
"2020 je bilo recikliranih. Pri procesu recikliranju pride do številnih "
"okolju nevarnih reakcij. Mi recikliramo drugače. Prizadevamo si za varne, "
"trajnostne in popravljive izdelke, s katerimi bo vsak uporabnik aktivno "
"vključen v reševanje okoljskih problemov."

msgstr ""
"In 2020, a record 54 million tons of electronic "
"waste was generated worldwide, which is 21 percent more than in the last five years. E-waste is "
"the fastest growing household waste in the world, caused mainly by "
"higher levels of consumption of electrical and electronic equipment, short life "
"cycles and little opportunity for repair. Only 17.4% of e-waste discarded in "
"2020 was recycled. Many environmentally hazardous reactions occur "
"during the recycling process. We recycle differently. We strive for safe, "
"sustainable and repairable products that will actively involve every user "
"in solving environmental problems."

Here is the index.html file

            {% trans 'Leta 2020 je po svetu nastalo rekordnih 54 milijonov ton elektronskih odpadkov, kar je 21 odstotkov več kot v zadnjih petih letih. E-odpadki so najhitreje rastoči gospodinjski odpadki na svetu, ki jih povzročajo predvsem višje stopnje porabe električne in elektronske opreme, kratki življenjski cikli in malo možnosti za popravila. Le 17,4% zavrženih e-odpadkov leta 2020 je bilo recikliranih. Pri procesu recikliranju pride do številnih okolju nevarnih reakcij. Mi recikliramo drugače. Prizadevamo si za varne, trajnostne in popravljive izdelke, s katerimi bo vsak uporabnik aktivno vključen v reševanje okoljskih problemov.' %}

            {% trans 'Predstavljamo vam RebankMini, prvi power bank (prenosna baterija) na svetu, ki ga poganjajo reciklirane baterijske celice. rEbankMini je v celoti izdelan v Sloveniji in s tem prvi power bank izdelan v Evropi. Sestavljen je iz prestižnega slovenskega lesa, hrasta in oreha. Z nakupom enega rEbankMini-ja nam pomagate zmanjšati izpust toplogrednih plinov za 14,6 kg (CO2eq), ki bi nastali pri proizvodnji izdelka, podobnega našemu.' %}

Body:
I'm not exactly sure what you are trying to do, but I would make a msg class in you app's models.py file. Also, are you trying to make the msgid a translated version of english? If so, making a msg class in your models.py file would provide you with a pk or id which you can use as a replacement for the translated version. The code would look something like this:

from django.db import models
from django.utils import timezone

class Msg(models.Model):
   msgContents = models.TextField()
   sender = models.ForeignKey(User, on_delete=models.CASCADE)
   date_sent = models.DateTimeField(default=timezone.now)

   def __str__(self):
      return '<What you want the Django admin page to use as the title>' # Example: return f'{self.sender} - {self.pk}'

I'm not exactly sure if this will help, but it's commonly used code for a message / posting system.


问:
Copying to Clipboard in a content Script
Can someone explain how I can write to clipboard please? I've seen a lot of ways but I cant seem to understand how. Currently using manifest v3 and no background.js script.

popup.js (action: download) -> contentscript.js (see below)

```<code>function listener(info) {

    chrome.runtime.onMessage.addListener(
        function (request, sender, sendResponse) {

            if (!request.action) return sendResponse({
                err: 'Error: No Request Action'
            });

            switch (request.action) {
                case "copy":

                    var textCopy = info.links.join(', ').replace(/"/g, '') // Text to Copy (String)

                    navigator.clipboard.writeText(textCopy).then(() => {
                        sendResponse('success')
                    }, () => {
                        sendResponse('failed')
                    });

                    break;

                // Other Requests

            }

        }
    );
}
</code>```

答:
At least in manifest v2, this method works.

First you need to add the permission clipboardWrite to your manifest:

```<code>...
"permissions": ["clipboardWrite", ... ],
...
</code>```

Then do something like what was answered here: https://stackoverflow.com/a/18455088

The idea is to create a temporary text area to put the text in which then allows you to select all the text inside with .select() and then copy it with document.execCommand('copy').

Body:
Can someone explain how I can write to clipboard please? I've seen a lot of ways but I cant seem to understand how. Currently using manifest v3 and no background.js script.

popup.js (action: download) -> contentscript.js (see below)

function listener(info) {

    chrome.runtime.onMessage.addListener(
        function (request, sender, sendResponse) {

            if (!request.action) return sendResponse({
                err: 'Error: No Request Action'
            });

            switch (request.action) {
                case "copy":

                    var textCopy = info.links.join(', ').replace(/"/g, '') // Text to Copy (String)

                    navigator.clipboard.writeText(textCopy).then(() => {
                        sendResponse('success')
                    }, () => {
                        sendResponse('failed')
                    });

                    break;

                // Other Requests

            }

        }
    );
}

Body:
At least in manifest v2, this method works.

First you need to add the permission clipboardWrite to your manifest:

...
"permissions": ["clipboardWrite", ... ],
...

Then do something like what was answered here: https://stackoverflow.com/a/18455088

The idea is to create a temporary text area to put the text in which then allows you to select all the text inside with .select() and then copy it with document.execCommand('copy').


问:
How can I speed this page up?
I have a ASP.Net WebForms page that has 2 drop-down lists (1 with 10 options, the other with about 600) and about 5 panels. Based on what value is selected from the drop-downs, other panels are made visible or invisible during async postback by querying a database.

My dilemma is this: The page is not fast enough on a slow connection, particularly during page load. When looking at the rendered page, the size of viewstate is large, even on initial load. Also, there is a large amount of data needing to populate the drop-downs, which could be contributing to the viewstate size.

Are there any suggestions to speed this page up?

答:
If the requests accept zip or deflate make your response return it.

```<code>var response = HttpContext.Current.Response;

string acceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"] ?? "";
if (acceptEncoding.Contains("gzip"))
{
    response.Filter =
        new System.IO.Compression.GZipStream(response.Filter,
            System.IO.Compression.CompressionMode.Compress);
    response.AppendHeader("Content-Encoding", "gzip");
}
else if (acceptEncoding.Contains("deflate"))
{
    response.Filter =
        new System.IO.Compression.DeflateStream(response.Filter,
            System.IO.Compression.CompressionMode.Compress);
    response.AppendHeader("Content-Encoding", "deflate");
}
</code>```

And move your ViewState to the session. Override this property on the base page class.

```<code>protected override PageStatePersister PageStatePersister
{
    get { return new SessionPageStatePersister(this); }
}
</code>```

Title: How can I speed this page up?

Body:
If the requests accept zip or deflate make your response return it.

var response = HttpContext.Current.Response;

string acceptEncoding = HttpContext.Current.Request.Headers["Accept-Encoding"] ?? "";
if (acceptEncoding.Contains("gzip"))
{
    response.Filter =
        new System.IO.Compression.GZipStream(response.Filter,
            System.IO.Compression.CompressionMode.Compress);
    response.AppendHeader("Content-Encoding", "gzip");
}
else if (acceptEncoding.Contains("deflate"))
{
    response.Filter =
        new System.IO.Compression.DeflateStream(response.Filter,
            System.IO.Compression.CompressionMode.Compress);
    response.AppendHeader("Content-Encoding", "deflate");
}

And move your ViewState to the session. Override this property on the base page class.

protected override PageStatePersister PageStatePersister
{
    get { return new SessionPageStatePersister(this); }
}


问:
Why am I not getting the NULL values when using FILTER to remove CSV Headers in PIG?
I have this data below in a .csv file:

```<code>Needed_values,TEMP,Desc
,022.3,NewYork
3,022.30,India
,027.0,Australia
,027.00,Russia
1,027.1,Austria
,027.10,Norway
,036.2,Hungary
,036.20,Lithunia
2,785.52,Nigeria

</code>```

I saw in one of the StackOverflow question the way to remove header using FILTER. So,
When I load this file in my pig script and use Filter to remove the header of my csv then all the NULL values under Needed_values also got removed!

```<code>LOAD_DATA = LOAD 'DATA.csv' Using PigStorage(',') as
(
NEEDED_VALUES:chararray,
TEMP:chararray,
DESC:chararray
);

FILTER_HEADER = FILTER LOAD_DATA BY NEEDED_VALUES != 'Needed_values';

</code>```
```<code>ACTUAL OUTPUT:
(3,022.30,India)
(1,027.1,Austria)
(1,027.1,Austria)
</code>```

I'm expecting the output to include everything except the headers- Needed_values,TEMP,Desc:

```<code>,022.3,NewYork
3,022.30,India
,027.0,Australia
,027.00,Russia
1,027.1,Austria
,027.10,Norway
,036.2,Hungary
,036.20,Lithunia
2,785.52,Nigeria

</code>```

答:
The null values will not pass the filter condition. Change the filter to:</p>
```<code>FILTER_HEADER = FILTER LOAD_DATA BY NEEDED_VALUES != 'Needed_values' OR NEEDED_VALUES IS NULL;
</code>```

Body:
I have this data below in a .csv file:

Needed_values,TEMP,Desc
,022.3,NewYork
3,022.30,India
,027.0,Australia
,027.00,Russia
1,027.1,Austria
,027.10,Norway
,036.2,Hungary
,036.20,Lithunia
2,785.52,Nigeria

I saw in one of the StackOverflow question the way to remove header using FILTER. So,
When I load this file in my pig script and use Filter to remove the header of my csv then all the NULL values under Needed_values also got removed!

LOAD_DATA = LOAD 'DATA.csv' Using PigStorage(',') as
(
NEEDED_VALUES:chararray,
TEMP:chararray,
DESC:chararray
);

FILTER_HEADER = FILTER LOAD_DATA BY NEEDED_VALUES != 'Needed_values';

ACTUAL OUTPUT:
(3,022.30,India)
(1,027.1,Austria)
(1,027.1,Austria)

I'm expecting the output to include everything except the headers- Needed_values,TEMP,Desc:

,022.3,NewYork
3,022.30,India
,027.0,Australia
,027.00,Russia
1,027.1,Austria
,027.10,Norway
,036.2,Hungary
,036.20,Lithunia
2,785.52,Nigeria

Body:
The null values will not pass the filter condition. Change the filter to:

FILTER_HEADER = FILTER LOAD_DATA BY NEEDED_VALUES != 'Needed_values' OR NEEDED_VALUES IS NULL;


问:
How to save a Dataframe in batches in Pyspark?
I am trying to split a dataframe into chunks using the following code:

```<code>chunk = 50
id1 = 0
id2 = chunk
df = df.withColumn('id_tmp', F.monotonically_increasing_id())
c = df.count()
while id1 < c:
    stop_df = df.filter((df['id_tmp'] < id2) & (df['id_tmp'] >= id1))

    stop_df.write \
        .mode('overwrite')\
        .option("header", True) \
        .option("sep", "|") \
        .option('quoteAll', True) \
        .format("csv") \
        .save("filepath")

    id1 += chunk
    id2 += chunk
</code>```

But it's only writing the first 50 rows (1st chunk) into csv.

What changes do I need to make to save other chunks as well?

答:
I've tried to achieve this using a new dataframe with an id that I've created locally.

Steps used

Use the chunk size to determine the number of partitions

Use the number of partitions to create a list/array with the partition number which will correspond to the ids.

Create a list/array of ids which can map one to one with your existing dataframes ids

Create new dataframe with the created partition list and matching id list

Join to your existing dataframe

Write using partitionBy on the partition number column

Code

Code for the above steps are as follows:

chunk = 50

id = list(range(0,200))
# [0, 1, 2, 3, 4 ... 199]
num_parts = int(len(id)/chunk)
# 4 chunks

# distribute it based on the chunks you need
part = list()
# [] empty list
for i in range(num_parts):
   for value in range(chunk):
     part.append(i)
# [0, 0, 0 ... 1, 1, 1, ...3, 3, 3]

part_data = [i for i in zip(id, part)]
# [(0, 0), (0, 1), .... (0, 49), (1, 50), (1, 51), .... (3, 199)]

part_df = spark.createDataFrame(part_data, ["id", "part"])
part_df.show(5, False)
# +---+----+
# |id |part|
# +---+----+
# |0  |0   |
# |1  |0   |
# |2  |0   |
# |3  |0   |
# |4  |0   |
# +---+----+
# only showing top 5 rows

df = spark.range(0,200)
df.show(5, False)
# +---+
# |id |
# +---+
# |0  |
# |1  |
# |2  |
# |3  |
# |4  |
# +---+
# only showing top 5 rows

new_df = df.join(part_df, "id")
new_df.show(5, False)
# +---+----+
# |id |part|
# +---+----+
# |0  |0   |
# |1  |0   |
# |2  |0   |
# |3  |0   |
# |4  |0   |
# +---+----+
# only showing top 5 rows

new_df.write.option("header", True).partitionBy("part").csv("so/test1")
# 4 x parts, each part 50 rows

```

Screenshot

The resulting folder structure is as shown in the screenshot below.

Body:
I am trying to split a dataframe into chunks using the following code:

chunk = 50
id1 = 0
id2 = chunk
df = df.withColumn('id_tmp', F.monotonically_increasing_id())
c = df.count()
while id1 < c:
    stop_df = df.filter((df['id_tmp'] < id2) & (df['id_tmp'] >= id1))

    stop_df.write \
        .mode('overwrite')\
        .option("header", True) \
        .option("sep", "|") \
        .option('quoteAll', True) \
        .format("csv") \
        .save("filepath")

    id1 += chunk
    id2 += chunk

But it's only writing the first 50 rows (1st chunk) into csv.

What changes do I need to make to save other chunks as well?

Body:
I've tried to achieve this using a new dataframe with an id that I've created locally.

Steps used

Use the chunk size to determine the number of partitions

Use the number of partitions to create a list/array with the partition number which will correspond to the ids.

Create a list/array of ids which can map one to one with your existing dataframes ids

Create new dataframe with the created partition list and matching id list

Join to your existing dataframe

Write using partitionBy on the partition number column

Code

Code for the above steps are as follows:

chunk = 50

id = list(range(0,200))
# [0, 1, 2, 3, 4 ... 199]
num_parts = int(len(id)/chunk)
# 4 chunks

# distribute it based on the chunks you need
part = list()
# [] empty list
for i in range(num_parts):
   for value in range(chunk):
     part.append(i)
# [0, 0, 0 ... 1, 1, 1, ...3, 3, 3]

part_data = [i for i in zip(id, part)]
# [(0, 0), (0, 1), .... (0, 49), (1, 50), (1, 51), .... (3, 199)]

part_df = spark.createDataFrame(part_data, ["id", "part"])
part_df.show(5, False)
# +---+----+
# |id |part|
# +---+----+
# |0  |0   |
# |1  |0   |
# |2  |0   |
# |3  |0   |
# |4  |0   |
# +---+----+
# only showing top 5 rows

df = spark.range(0,200)
df.show(5, False)
# +---+
# |id |
# +---+
# |0  |
# |1  |
# |2  |
# |3  |
# |4  |
# +---+
# only showing top 5 rows

new_df = df.join(part_df, "id")
new_df.show(5, False)
# +---+----+
# |id |part|
# +---+----+
# |0  |0   |
# |1  |0   |
# |2  |0   |
# |3  |0   |
# |4  |0   |
# +---+----+
# only showing top 5 rows

new_df.write.option("header", True).partitionBy("part").csv("so/test1")
# 4 x parts, each part 50 rows

Screenshot

The resulting folder structure is as shown in the screenshot below.


问:
Recursive map function for nested array
I'm trying to create a map function that supports computing nested arrays, using recursion:

This function, when a unidimesional (eg. [1,2,3,4] ) array is used works fine:

```<code>const map = (oldArray, callback, newArray = []) => {

    //base case: check if there are any items left in the original array to process
    if (oldArray.length <= 0){
      //if all items have been processed return the new array
      return newArray
    } else {
      //destructure the first item from old array and put remaining in a separate array
      const [item, ...theRest] = oldArray
      // create an array of the current new array and the result of the current item and the callback function
      const interimArray = [...newArray, callback(item)]
      // return a recursive call to to map to process the next item.
      return map(theRest, callback, interimArray)
    }

  }
</code>```

But, I want to support a nested array, so for example, I have an array like this:

```<code>const array = [1,[1,2],3]
</code>```

and I want to apply a function, eg: (x)=>x+1;

I have this implementation so far, but I can't wrap my mind around it.

```<code>function rnMap(oldArr, fn, newArr = []) {
  const [item, ...rest] = oldArr;

  if (oldArr.length <= 0) {
    return newArr;
  } else if (Array.isArray(item)) {
    return rnMap(item, fn, [...newArr, rnMap(item, fn, [])]);
  } else {
    const interimArray = [...newArr, fn(item)];

    return rnMap(rest, fn, interimArray);
  }
}

const rnRes = rnMap(nArr, (e) => {
  return e + 1;
});

console.log(rnRes);
</code>```

It returns [ 2, [ 2, 2 ], 2, 2 ] but it suppose to return [2,[2,3],4]

If anyone could help me will be appretiated.
Thanks in advance.

答:
Finally I found the error, here is my solution:</p>
```<code>function rnMap(oldArr, fn, newArr = []) {
  const [item, ...rest] = oldArr;

  if (oldArr.length <= 0) {
    return newArr;
  } else if (Array.isArray(item)) {
    return rnMap(rest, fn, [...newArr, rnMap(item, fn, [])]);
  } else {
    return rnMap(rest, fn, [...newArr, fn(item)]);
  }
}

const rnRes = rnMap([1, 2, [3, 4, [5, 6]], 7], (e) => {
  return e + 1;
});

console.log(rnRes);
</code>```

Title: Recursive map function for nested array

Body:
I'm trying to create a map function that supports computing nested arrays, using recursion:

This function, when a unidimesional (eg. [1,2,3,4] ) array is used works fine:

const map = (oldArray, callback, newArray = []) => {

    //base case: check if there are any items left in the original array to process
    if (oldArray.length <= 0){
      //if all items have been processed return the new array
      return newArray
    } else {
      //destructure the first item from old array and put remaining in a separate array
      const [item, ...theRest] = oldArray
      // create an array of the current new array and the result of the current item and the callback function
      const interimArray = [...newArray, callback(item)]
      // return a recursive call to to map to process the next item.
      return map(theRest, callback, interimArray)
    }

  }

But, I want to support a nested array, so for example, I have an array like this:

const array = [1,[1,2],3]

and I want to apply a function, eg: (x)=>x+1;

I have this implementation so far, but I can't wrap my mind around it.

function rnMap(oldArr, fn, newArr = []) {
  const [item, ...rest] = oldArr;

  if (oldArr.length <= 0) {
    return newArr;
  } else if (Array.isArray(item)) {
    return rnMap(item, fn, [...newArr, rnMap(item, fn, [])]);
  } else {
    const interimArray = [...newArr, fn(item)];

    return rnMap(rest, fn, interimArray);
  }
}

const rnRes = rnMap(nArr, (e) => {
  return e + 1;
});

console.log(rnRes);

It returns [ 2, [ 2, 2 ], 2, 2 ] but it suppose to return [2,[2,3],4]

If anyone could help me will be appretiated.
Thanks in advance.

Body:
Finally I found the error, here is my solution:

function rnMap(oldArr, fn, newArr = []) {
  const [item, ...rest] = oldArr;

  if (oldArr.length <= 0) {
    return newArr;
  } else if (Array.isArray(item)) {
    return rnMap(rest, fn, [...newArr, rnMap(item, fn, [])]);
  } else {
    return rnMap(rest, fn, [...newArr, fn(item)]);
  }
}

const rnRes = rnMap([1, 2, [3, 4, [5, 6]], 7], (e) => {
  return e + 1;
});

console.log(rnRes);


问:
How do I limit the GRPC send queue?
When you perform onNext() on a stream response in GRPC it queues it up for transmission, this allocates on direct buffer memory rather than heap as such java.lang.OutOfMemoryError: Direct buffer memory will not generate a useful heap dump.  This can be simulated by creating a

```<code>message Chunk {
  bytes data = 1
}
</code>```

And sending multiple small chunks into a stream where the receiving end may not be as quick will cause this to trigger.  The proper fix would be to make sure the server does not do anything stupid like send many small chunks, but this still can be a vector of DoS attack that could shut down a service.

My question is in GRPC, is there a setting on the server side to limit the amount and block further onNext until the queue is diminished, with a timeout to cancel the operation when the transfer takes too long?  That way it won't shutdown the service but just the GRPC call.

I am thinking the answer would somewhere be in this Github issue though it seems a lot of code for something so fundamental.

答: The local send buffer size on the server is hard-coded to 32 KB. You can use the ServerCallStreamObserver.isReady() or the onReadyHandler to block to achieve flow control (and also timeout for how long you wait).

Title: How do I limit the GRPC send queue?

Body:
When you perform onNext() on a stream response in GRPC it queues it up for transmission, this allocates on direct buffer memory rather than heap as such java.lang.OutOfMemoryError: Direct buffer memory will not generate a useful heap dump.  This can be simulated by creating a

message Chunk {
  bytes data = 1
}

And sending multiple small chunks into a stream where the receiving end may not be as quick will cause this to trigger.  The proper fix would be to make sure the server does not do anything stupid like send many small chunks, but this still can be a vector of DoS attack that could shut down a service.

My question is in GRPC, is there a setting on the server side to limit the amount and block further onNext until the queue is diminished, with a timeout to cancel the operation when the transfer takes too long?  That way it won't shutdown the service but just the GRPC call.

I am thinking the answer would somewhere be in this Github issue though it seems a lot of code for something so fundamental.


问:
Hydrapaper will not open - need help interpreting errors
I'm running Ubuntu 20.04.3 LTS and until recently, I used Hydrapaper for my dual monitor setup. It's not imperative that I be able to have separate wallpapers but I am being driven kind of mad by the errors I'm seeing when I try to open Hydrapaper from the terminal. This is what I get:

michael@michael-Inspiron-7790-AIO:~$ flatpak run org.gabmus.hydrapaper
Traceback (most recent call last):
  File "/app/lib/python3.9/site-packages/hydrapaper/__main__.py", line 206, in do_command_line
    self.do_activate()
  File "/app/lib/python3.9/site-packages/hydrapaper/__main__.py", line 146, in do_activate
    self.window = HydraPaperAppWindow()
  File "/app/lib/python3.9/site-packages/hydrapaper/app_window.py", line 44, in __init__
    self.monitors_flowbox = HydraPaperMonitorsFlowbox()
  File "/app/lib/python3.9/site-packages/hydrapaper/monitors_flowbox.py", line 132, in __init__
    self.populate()
  File "/app/lib/python3.9/site-packages/hydrapaper/monitors_flowbox.py", line 151, in populate
    HydraPaperMonitorsFlowboxItem(m), -1
  File "/app/lib/python3.9/site-packages/hydrapaper/monitors_flowbox.py", line 71, in __init__
    self.set_picture()
  File "/app/lib/python3.9/site-packages/hydrapaper/monitors_flowbox.py", line 94, in set_picture
    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(
gi.repository.GLib.GError: gdk-pixbuf-error-quark: Couldn’t recognize the image file format for file “/home/michael/.var/app/org.gabmus.hydrapaper/cache/org.gabmus.hydrapaper/thumbnails//a5debe6ea02641a70325dc008910a85c61765e55906c29dd338e9f63506378a4.png” (3)
```

And as I said, Hydrapaper won't open. It appears in my topbar for a few seconds then disappears. Can anyone suggest a fix? Thanks in advance.

答: I had this same exact issue, what fixed it for me was going to the file mentioned at the end of the error and deleting it, hydra paper worked perfectly after that</p>

Body:
I'm running Ubuntu 20.04.3 LTS and until recently, I used Hydrapaper for my dual monitor setup. It's not imperative that I be able to have separate wallpapers but I am being driven kind of mad by the errors I'm seeing when I try to open Hydrapaper from the terminal. This is what I get:

michael@michael-Inspiron-7790-AIO:~$ flatpak run org.gabmus.hydrapaper
Traceback (most recent call last):
  File "/app/lib/python3.9/site-packages/hydrapaper/__main__.py", line 206, in do_command_line
    self.do_activate()
  File "/app/lib/python3.9/site-packages/hydrapaper/__main__.py", line 146, in do_activate
    self.window = HydraPaperAppWindow()
  File "/app/lib/python3.9/site-packages/hydrapaper/app_window.py", line 44, in __init__
    self.monitors_flowbox = HydraPaperMonitorsFlowbox()
  File "/app/lib/python3.9/site-packages/hydrapaper/monitors_flowbox.py", line 132, in __init__
    self.populate()
  File "/app/lib/python3.9/site-packages/hydrapaper/monitors_flowbox.py", line 151, in populate
    HydraPaperMonitorsFlowboxItem(m), -1
  File "/app/lib/python3.9/site-packages/hydrapaper/monitors_flowbox.py", line 71, in __init__
    self.set_picture()
  File "/app/lib/python3.9/site-packages/hydrapaper/monitors_flowbox.py", line 94, in set_picture
    pixbuf = GdkPixbuf.Pixbuf.new_from_file_at_scale(
gi.repository.GLib.GError: gdk-pixbuf-error-quark: Couldn’t recognize the image file format for file “/home/michael/.var/app/org.gabmus.hydrapaper/cache/org.gabmus.hydrapaper/thumbnails//a5debe6ea02641a70325dc008910a85c61765e55906c29dd338e9f63506378a4.png” (3)

And as I said, Hydrapaper won't open. It appears in my topbar for a few seconds then disappears. Can anyone suggest a fix? Thanks in advance.


问:
How to correctly place an image outside the container, and make them adaptive, HTML/CSS?
Maket link: https://www.figma.com/file/hYoPHDHOzzgzEPo4crMmy1/UH15U7CD4WZkbhcW?node-id=2%3A334

Project link: https://plupiks.github.io/Real-Estate-LandingPage/

I have a layout, it has an image of a building. This image is outside of the container. I was able to take the image out of the container, but I can’t adapt it anymore. If I give the image width: 100%; height: auto; , its dimensions no longer correspond to those specified in the layout.

The question is, how to move images outside the container so that they can then be adapted without changing the original image dimensions?

Worked with preprocessor SCSS.

```<code><div class="hero">
        <div class="container">
          <div class="hero--wrapper">
            <div class="hero--blok-left">
              <div class="hero--descr">Welcome to Besnik Agency</div>
              <h1 class="hero--title">Discover a place you’ll love to live.</h1>
              <p class="hero--subtitle">
                Get the best real estate deals first, before they hit the mass market! hot foreclosure deals with one simple search
              </p>
              <button class="button hero--button">More About Us</button>
            </div>
            <div class="hero--block-right">
              <div class="hero--img">
                <svg width="584" height="620" viewBox="0 0 584 620" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M241.032 610.998L231.713 201.367L58.0327 201.367L60.5743 610.998H241.032Z" fill="#F1F6FF" />
                  <path d="M302.879 608.881V337.77L512.566 343.89V608.881H302.879Z" fill="#FEFCED" />
                  <path d="M58.033 201.367L60.5747 610.998H159.276L154.616 201.367H58.033Z" fill="#7398F7" />
                  <path d="M182.997 159.855H110.983V201.369H182.997V159.855Z" fill="#1F1D42" />
                  <path d="M110.983 159.855V201.369H159.698C136.315 196.285 129.057 171.575 128.351 159.855H110.983Z" fill="#1F1717" />
                  <path
                    d="M152.498 89.1111L144.026 88.2639C141.908 87.4167 141.484 77.6737 149.533 79.7917C155.971 81.4861 154.192 86.7107 152.498 89.1111Z"
                    fill="#0E173D"
                  />
                  <path d="M152.498 89.112L144.026 88.2648V100.549L152.498 101.397V89.112Z" fill="#0E173D" />
                  <path d="M144.025 100.548L152.497 101.396L183.845 123.847H110.56L144.025 100.548Z" fill="#1F1D42" />
                  <path d="M323.636 403.007H316.859V451.298H313.893V456.381H326.602V449.604H323.636V403.007Z" fill="#1B2A63" />
                  <path d="M512.566 612.269H302.879V473.325L512.566 476.385V612.269Z" fill="#A3BDFF" />
                  <path d="M448.177 242.458L221.546 235.257L302.879 337.77L520.614 344.124L448.177 242.458Z" fill="#063183" />
                  <path d="M302.879 337.77L520.614 344.124L316.011 238.258L221.546 235.257L302.879 337.77Z" fill="#7087FB" />
                  <path
                    d="M221.546 235.257L302.879 337.77V605.915L152.921 613.117V476.291V337.77L193.164 284.819H184.268L221.546 235.257Z"
                    fill="#CFDEF3"
                  />
                  <path d="M250.776 297.527H206.297V350.902H250.776V297.527Z" fill="#0C183F" />
                  <rect x="211.38" y="303.033" width="15.2499" height="18.6388" fill="#1F326B" />
                  <rect x="232.56" y="303.033" width="15.2499" height="18.6388" fill="#1F326B" />
                  <rect x="232.56" y="328.451" width="15.2499" height="18.6388" fill="#1F326B" />
                  <path d="M110.562 123.846H183.846H188.929V125.964H104.631V123.846H110.562Z" stroke="black" />
                  <path d="M150.804 378.012H303.727H512.99" stroke="black" stroke-width="4" />
                  <path d="M151.652 486.457H301.186H511.297" stroke="black" stroke-width="5" />
                  <path d="M151.652 486.457H301.186" stroke="#5267FA" stroke-width="6" />
                  <rect x="211.38" y="328.451" width="15.2499" height="18.6388" fill="#1F326B" />
                  <path d="M113.525 289.901H91.0741V350.901H115.22L113.525 289.901Z" fill="#0E173D" />
                  <path d="M113.525 395.381H91.0741V456.381H115.22L113.525 395.381Z" fill="#0C193F" />
                  <path d="M114.797 267.027H91.9224V220.43C97.3446 205.18 106.325 214.076 110.138 220.43L114.797 267.027Z" fill="#1F1D42" />
                  <path
                    d="M352.019 247.118H327.873L306.693 240.763V201.368V199.25L327.873 198.677L353.714 197.979L353.597 201.368L352.019 247.118Z"
                    fill="#1F326B"
                  />
                  <path d="M352.019 247.118H327.874V201.368V198.677L353.714 197.979L353.597 201.368L352.019 247.118Z" fill="#FEFDE8" />
                  <path d="M306.693 199.25L327.873 198.677L353.714 197.979L353.597 201.368H327.873H306.693V199.25Z" fill="#112F7F" />
                  <rect x="180.881" y="125.966" width="1.69444" height="33.8888" fill="#0C1942" />
                  <rect x="241.032" y="166.632" width="1.69444" height="189.777" transform="rotate(90 241.032 166.632)" fill="#0C1942" />
                  <rect x="241.032" y="199.673" width="1.69444" height="189.777" transform="rotate(90 241.032 199.673)" fill="#0C1942" />
                  <path d="M58.0009 231.867H155.855H232.501" stroke="#18265D" stroke-width="4" />
                  <rect x="241.032" y="186.118" width="1.69444" height="189.777" transform="rotate(90 241.032 186.118)" fill="#081334" />
                  <rect x="110.56" y="125.966" width="1.69444" height="33.8888" fill="#132355" />
                  <rect x="128.352" y="131.895" width="1.69444" height="27.9582" fill="#132355" />
                  <rect x="131.741" y="131.895" width="1.69444" height="27.9582" fill="#132355" />
                  <rect x="136.824" y="131.895" width="1.69444" height="27.9582" fill="#132355" />
                  <path
                    d="M221.546 235.257L227.259 244.153M302.879 337.77L296.72 330.145M227.259 244.153L453.308 249.66M227.259 244.153L237.524 256.861M237.524 256.861L462.061 261.944M237.524 256.861L248.816 270.84M248.816 270.84L470.813 274.229M248.816 270.84L257.976 282.18M257.976 282.18L479.566 286.514M257.976 282.18L269.004 295.833M269.004 295.833L488.42 298.939M269.004 295.833L278.243 307.27M278.243 307.27L497.739 312.019M278.243 307.27L290.561 322.52M290.561 322.52H505.221M290.561 322.52L296.72 330.145M296.72 330.145L512.918 333.322"
                    stroke="#A3BDFF"
                    stroke-width="4"
                  />
                  <rect x="83.4506" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="51.2557" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="239.338" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <path d="M377.436 511.026H363.88V579.651H377.436V511.026Z" fill="#0C183F" />
                  <path d="M363.88 579.651H377.436V545.339H363.88V579.651Z" fill="#17275F" />
                  <path d="M489.691 548.304H467.24V580.499H489.691V548.304Z" fill="#17275F" />
                  <path d="M148.687 79.7914L146.992 1" stroke="black" stroke-width="3" />
                  <rect x="210.534" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="151.227" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="77.5193" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="204.602" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="204.602" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="145.298" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="158.853" y="131.895" width="1.69444" height="27.9582" fill="#121B3A" />
                  <rect x="162.241" y="131.895" width="1.69444" height="27.9582" fill="#121B3A" />
                  <rect x="152.921" y="131.895" width="1.69444" height="27.9582" fill="#121B3A" />
                  <path d="M467.24 580.499H489.691V564.402H467.24V580.499Z" fill="#0F1C49" />
                  <path d="M503.67 556.353H495.198V574.145L503.67 573.721V556.353Z" fill="#FAF2E2" />
                  <path
                    d="M200.365 511.449V548.727H204.601V604.643H211.803V546.185H207.143V517.803H248.657V546.185H241.879V604.643H246.115V548.727H254.164V511.449H200.365Z"
                    fill="#0D0808"
                  />
                  <path d="M241.881 546.186V604.644H211.805V546.186H207.145V517.804H248.659V546.186H241.881Z" fill="#17275F" />
                  <path d="M584 611.421H0V620H584V611.421Z" fill="#091D39" />
                  <path
                    d="M571.873 611.422V576.686M510.026 576.686V611.422M446.485 576.686V611.422M385.909 576.686V611.422M323.214 576.686V611.422M259.249 576.686V611.422M201.638 576.686V611.422M136.826 576.686V611.422M74.132 576.686V611.422M14.4031 576.686V611.422"
                    stroke="black"
                    stroke-width="4"
                  />
                  <path
                    d="M571.873 582C558.6 593.579 527.648 609.789 510.026 582C495.623 590.755 462.751 602.78 446.485 581.769C433.776 590.241 403.869 603.288 385.908 587.699C373.341 593.489 343.209 601.594 323.214 587.699C305.705 591.371 268.399 596.511 259.249 587.699C247.388 591.371 219.26 596.511 201.638 587.699C184.553 591.371 147.67 596.511 136.826 587.699C118.752 593.912 89.8057 602.102 74.1318 587.699C57.0807 591.371 23.3695 597.311 13.5004 588.5"
                    stroke="black"
                    stroke-width="3"
                  />
                  <circle cx="571.965" cy="574.965" r="2.96527" fill="#06162A" />
                  <circle cx="510.026" cy="574.568" r="2.96527" fill="#06162A" />
                  <circle cx="446.484" cy="575.416" r="2.96527" fill="#06162A" />
                  <circle cx="385.965" cy="574.965" r="2.96527" fill="#06162A" />
                  <circle cx="322.965" cy="574.965" r="2.96527" fill="#06162A" />
                  <circle cx="259.249" cy="575.416" r="2.96527" fill="#06162A" />
                  <circle cx="201.638" cy="574.568" r="2.96527" fill="#06162A" />
                  <circle cx="136.965" cy="574.568" r="2.96527" fill="#06162A" />
                  <circle cx="73.9653" cy="576.262" r="2.96527" fill="#06162A" />
                  <circle cx="13.9653" cy="577.965" r="2.96527" fill="#06162A" />
                  <path d="M56.7639 45.479L69.4722 56.4928L82.1805 45.479" stroke="black" stroke-width="4" />
                  <path d="M8.47162 38.7016L21.1799 49.7154L33.8882 38.7016" stroke="black" stroke-width="4" />
                  <path d="M63.5413 16.675L76.2496 27.6889L88.9579 16.675" stroke="black" stroke-width="4" />
                  <path d="M133.014 20.9098L145.722 31.9236L158.431 20.9098" stroke="black" stroke-width="4" />
                  <path d="M255.86 390.298H210.11L211.805 458.076H255.86V390.298Z" fill="#0F1F4C" />
                  <path d="M244.847 401.736H221.125V446.638H244.847V401.736Z" fill="#142553" />
                </svg>
              </div>
            </div>
          </div>
        </div>
      </div>
</code>```
```<code>.hero {
  position: relative;
  background-color: $blueElis;
  font-size: 16px;
}

.hero--wrapper {
  display: flex;
  column-gap: 4.1875em;
  padding-top: 7.125em;
}

.hero--blok-left {
  flex: 0 0 50.37%;
  margin-top: 5.6875em;
}

.hero--descr {
  margin-bottom: 0.444em;
  @include SWCL(1.125em, 500, $pigeonBlue, 1.6875);
}

.hero--title {
  margin-bottom: 0.46875em;
  @include SWCL(4em, 700, $darkBlue, 1.1875);
}

.hero--subtitle {
  @include SWCL(1.125em, 400, $marengo, 2);
  margin-bottom: 2.222em;
}
.hero--button {
}

.hero--block-right {
  display: flex;
  align-items: flex-end;
}
.hero--img {
  width: 36.5em;
  height: auto;
  & svg {
    max-width: 100%;
    height: auto;
  }
}

// Adaptive

@media only screen and (max-width: 1024px) {
  .header {
    font-size: 14px;
  }
}

</code>```

答:
As an easy workaround you could set your background-size using a relative unit like %, vw, vmin or vmax like so:

```<code>/* small devices */
.hero{
    background-size: 50%;
}

/* large devices */
@media (min-width:1024px){
    .hero{
        background-size: 36.5em 38.75em;
    }
}
</code>```

You original background size will be applied for viewports larger than 1024px.

You will of course need to tweak the values to get your desired results.

Body:
Maket link: https://www.figma.com/file/hYoPHDHOzzgzEPo4crMmy1/UH15U7CD4WZkbhcW?node-id=2%3A334

Project link: https://plupiks.github.io/Real-Estate-LandingPage/

I have a layout, it has an image of a building. This image is outside of the container. I was able to take the image out of the container, but I can’t adapt it anymore. If I give the image width: 100%; height: auto; , its dimensions no longer correspond to those specified in the layout.

The question is, how to move images outside the container so that they can then be adapted without changing the original image dimensions?

Worked with preprocessor SCSS.

Welcome to Besnik Agency

Discover a place you’ll love to live.

                Get the best real estate deals first, before they hit the mass market! hot foreclosure deals with one simple search

              <button class="button hero--button">More About Us</button>

                <svg width="584" height="620" viewBox="0 0 584 620" fill="none" xmlns="http://www.w3.org/2000/svg">
                  <path d="M241.032 610.998L231.713 201.367L58.0327 201.367L60.5743 610.998H241.032Z" fill="#F1F6FF" />
                  <path d="M302.879 608.881V337.77L512.566 343.89V608.881H302.879Z" fill="#FEFCED" />
                  <path d="M58.033 201.367L60.5747 610.998H159.276L154.616 201.367H58.033Z" fill="#7398F7" />
                  <path d="M182.997 159.855H110.983V201.369H182.997V159.855Z" fill="#1F1D42" />
                  <path d="M110.983 159.855V201.369H159.698C136.315 196.285 129.057 171.575 128.351 159.855H110.983Z" fill="#1F1717" />
                  <path
                    d="M152.498 89.1111L144.026 88.2639C141.908 87.4167 141.484 77.6737 149.533 79.7917C155.971 81.4861 154.192 86.7107 152.498 89.1111Z"
                    fill="#0E173D"
                  />
                  <path d="M152.498 89.112L144.026 88.2648V100.549L152.498 101.397V89.112Z" fill="#0E173D" />
                  <path d="M144.025 100.548L152.497 101.396L183.845 123.847H110.56L144.025 100.548Z" fill="#1F1D42" />
                  <path d="M323.636 403.007H316.859V451.298H313.893V456.381H326.602V449.604H323.636V403.007Z" fill="#1B2A63" />
                  <path d="M512.566 612.269H302.879V473.325L512.566 476.385V612.269Z" fill="#A3BDFF" />
                  <path d="M448.177 242.458L221.546 235.257L302.879 337.77L520.614 344.124L448.177 242.458Z" fill="#063183" />
                  <path d="M302.879 337.77L520.614 344.124L316.011 238.258L221.546 235.257L302.879 337.77Z" fill="#7087FB" />
                  <path
                    d="M221.546 235.257L302.879 337.77V605.915L152.921 613.117V476.291V337.77L193.164 284.819H184.268L221.546 235.257Z"
                    fill="#CFDEF3"
                  />
                  <path d="M250.776 297.527H206.297V350.902H250.776V297.527Z" fill="#0C183F" />
                  <rect x="211.38" y="303.033" width="15.2499" height="18.6388" fill="#1F326B" />
                  <rect x="232.56" y="303.033" width="15.2499" height="18.6388" fill="#1F326B" />
                  <rect x="232.56" y="328.451" width="15.2499" height="18.6388" fill="#1F326B" />
                  <path d="M110.562 123.846H183.846H188.929V125.964H104.631V123.846H110.562Z" stroke="black" />
                  <path d="M150.804 378.012H303.727H512.99" stroke="black" stroke-width="4" />
                  <path d="M151.652 486.457H301.186H511.297" stroke="black" stroke-width="5" />
                  <path d="M151.652 486.457H301.186" stroke="#5267FA" stroke-width="6" />
                  <rect x="211.38" y="328.451" width="15.2499" height="18.6388" fill="#1F326B" />
                  <path d="M113.525 289.901H91.0741V350.901H115.22L113.525 289.901Z" fill="#0E173D" />
                  <path d="M113.525 395.381H91.0741V456.381H115.22L113.525 395.381Z" fill="#0C193F" />
                  <path d="M114.797 267.027H91.9224V220.43C97.3446 205.18 106.325 214.076 110.138 220.43L114.797 267.027Z" fill="#1F1D42" />
                  <path
                    d="M352.019 247.118H327.873L306.693 240.763V201.368V199.25L327.873 198.677L353.714 197.979L353.597 201.368L352.019 247.118Z"
                    fill="#1F326B"
                  />
                  <path d="M352.019 247.118H327.874V201.368V198.677L353.714 197.979L353.597 201.368L352.019 247.118Z" fill="#FEFDE8" />
                  <path d="M306.693 199.25L327.873 198.677L353.714 197.979L353.597 201.368H327.873H306.693V199.25Z" fill="#112F7F" />
                  <rect x="180.881" y="125.966" width="1.69444" height="33.8888" fill="#0C1942" />
                  <rect x="241.032" y="166.632" width="1.69444" height="189.777" transform="rotate(90 241.032 166.632)" fill="#0C1942" />
                  <rect x="241.032" y="199.673" width="1.69444" height="189.777" transform="rotate(90 241.032 199.673)" fill="#0C1942" />
                  <path d="M58.0009 231.867H155.855H232.501" stroke="#18265D" stroke-width="4" />
                  <rect x="241.032" y="186.118" width="1.69444" height="189.777" transform="rotate(90 241.032 186.118)" fill="#081334" />
                  <rect x="110.56" y="125.966" width="1.69444" height="33.8888" fill="#132355" />
                  <rect x="128.352" y="131.895" width="1.69444" height="27.9582" fill="#132355" />
                  <rect x="131.741" y="131.895" width="1.69444" height="27.9582" fill="#132355" />
                  <rect x="136.824" y="131.895" width="1.69444" height="27.9582" fill="#132355" />
                  <path
                    d="M221.546 235.257L227.259 244.153M302.879 337.77L296.72 330.145M227.259 244.153L453.308 249.66M227.259 244.153L237.524 256.861M237.524 256.861L462.061 261.944M237.524 256.861L248.816 270.84M248.816 270.84L470.813 274.229M248.816 270.84L257.976 282.18M257.976 282.18L479.566 286.514M257.976 282.18L269.004 295.833M269.004 295.833L488.42 298.939M269.004 295.833L278.243 307.27M278.243 307.27L497.739 312.019M278.243 307.27L290.561 322.52M290.561 322.52H505.221M290.561 322.52L296.72 330.145M296.72 330.145L512.918 333.322"
                    stroke="#A3BDFF"
                    stroke-width="4"
                  />
                  <rect x="83.4506" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="51.2557" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="239.338" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <path d="M377.436 511.026H363.88V579.651H377.436V511.026Z" fill="#0C183F" />
                  <path d="M363.88 579.651H377.436V545.339H363.88V579.651Z" fill="#17275F" />
                  <path d="M489.691 548.304H467.24V580.499H489.691V548.304Z" fill="#17275F" />
                  <path d="M148.687 79.7914L146.992 1" stroke="black" stroke-width="3" />
                  <rect x="210.534" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="151.227" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="77.5193" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="204.602" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="204.602" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="145.298" y="168.327" width="1.69444" height="31.3471" fill="#121B3A" />
                  <rect x="158.853" y="131.895" width="1.69444" height="27.9582" fill="#121B3A" />
                  <rect x="162.241" y="131.895" width="1.69444" height="27.9582" fill="#121B3A" />
                  <rect x="152.921" y="131.895" width="1.69444" height="27.9582" fill="#121B3A" />
                  <path d="M467.24 580.499H489.691V564.402H467.24V580.499Z" fill="#0F1C49" />
                  <path d="M503.67 556.353H495.198V574.145L503.67 573.721V556.353Z" fill="#FAF2E2" />
                  <path
                    d="M200.365 511.449V548.727H204.601V604.643H211.803V546.185H207.143V517.803H248.657V546.185H241.879V604.643H246.115V548.727H254.164V511.449H200.365Z"
                    fill="#0D0808"
                  />
                  <path d="M241.881 546.186V604.644H211.805V546.186H207.145V517.804H248.659V546.186H241.881Z" fill="#17275F" />
                  <path d="M584 611.421H0V620H584V611.421Z" fill="#091D39" />
                  <path
                    d="M571.873 611.422V576.686M510.026 576.686V611.422M446.485 576.686V611.422M385.909 576.686V611.422M323.214 576.686V611.422M259.249 576.686V611.422M201.638 576.686V611.422M136.826 576.686V611.422M74.132 576.686V611.422M14.4031 576.686V611.422"
                    stroke="black"
                    stroke-width="4"
                  />
                  <path
                    d="M571.873 582C558.6 593.579 527.648 609.789 510.026 582C495.623 590.755 462.751 602.78 446.485 581.769C433.776 590.241 403.869 603.288 385.908 587.699C373.341 593.489 343.209 601.594 323.214 587.699C305.705 591.371 268.399 596.511 259.249 587.699C247.388 591.371 219.26 596.511 201.638 587.699C184.553 591.371 147.67 596.511 136.826 587.699C118.752 593.912 89.8057 602.102 74.1318 587.699C57.0807 591.371 23.3695 597.311 13.5004 588.5"
                    stroke="black"
                    stroke-width="3"
                  />
                  <circle cx="571.965" cy="574.965" r="2.96527" fill="#06162A" />
                  <circle cx="510.026" cy="574.568" r="2.96527" fill="#06162A" />
                  <circle cx="446.484" cy="575.416" r="2.96527" fill="#06162A" />
                  <circle cx="385.965" cy="574.965" r="2.96527" fill="#06162A" />
                  <circle cx="322.965" cy="574.965" r="2.96527" fill="#06162A" />
                  <circle cx="259.249" cy="575.416" r="2.96527" fill="#06162A" />
                  <circle cx="201.638" cy="574.568" r="2.96527" fill="#06162A" />
                  <circle cx="136.965" cy="574.568" r="2.96527" fill="#06162A" />
                  <circle cx="73.9653" cy="576.262" r="2.96527" fill="#06162A" />
                  <circle cx="13.9653" cy="577.965" r="2.96527" fill="#06162A" />
                  <path d="M56.7639 45.479L69.4722 56.4928L82.1805 45.479" stroke="black" stroke-width="4" />
                  <path d="M8.47162 38.7016L21.1799 49.7154L33.8882 38.7016" stroke="black" stroke-width="4" />
                  <path d="M63.5413 16.675L76.2496 27.6889L88.9579 16.675" stroke="black" stroke-width="4" />
                  <path d="M133.014 20.9098L145.722 31.9236L158.431 20.9098" stroke="black" stroke-width="4" />
                  <path d="M255.86 390.298H210.11L211.805 458.076H255.86V390.298Z" fill="#0F1F4C" />
                  <path d="M244.847 401.736H221.125V446.638H244.847V401.736Z" fill="#142553" />
                </svg>

.hero {
  position: relative;
  background-color: $blueElis;
  font-size: 16px;
}

.hero--wrapper {
  display: flex;
  column-gap: 4.1875em;
  padding-top: 7.125em;
}

.hero--blok-left {
  flex: 0 0 50.37%;
  margin-top: 5.6875em;
}

.hero--descr {
  margin-bottom: 0.444em;
  @include SWCL(1.125em, 500, $pigeonBlue, 1.6875);
}

.hero--title {
  margin-bottom: 0.46875em;
  @include SWCL(4em, 700, $darkBlue, 1.1875);
}

.hero--subtitle {
  @include SWCL(1.125em, 400, $marengo, 2);
  margin-bottom: 2.222em;
}
.hero--button {
}

.hero--block-right {
  display: flex;
  align-items: flex-end;
}
.hero--img {
  width: 36.5em;
  height: auto;
  & svg {
    max-width: 100%;
    height: auto;
  }
}

// Adaptive

@media only screen and (max-width: 1024px) {
  .header {
    font-size: 14px;
  }
}

Body:
As an easy workaround you could set your background-size using a relative unit like %, vw, vmin or vmax like so:

/* small devices */
.hero{
    background-size: 50%;
}

/* large devices */
@media (min-width:1024px){
    .hero{
        background-size: 36.5em 38.75em;
    }
}

You original background size will be applied for viewports larger than 1024px.

You will of course need to tweak the values to get your desired results.