text:
Q: im trying to fetch values from db but getting errors which say cmd,dr, doesnt exist in the current context
Possible Duplicate:
C# having some errors from fetching

public partial class BioreCottonPurchaseSlip2011 : Form
{

    Library obj = new Library();

    public BioreCottonPurchaseSlip2011()
    {
        InitializeComponent();
    }

    public void enableDisableControls(bool flag)
    {
        TxtExtensionNo.Enabled = flag;
        TxtFarmerCode.Enabled = flag;
        TxtFarmerName.Enabled = flag;
        TxtBasicPrice.Enabled = flag;
        TxtPremium.Enabled = flag;
        TxtWeight.Enabled = flag;
        TxtTotalAmountBasic.Enabled = flag;
        TxtTotalAmountPremium.Enabled = flag;
        TxtBalancePay.Enabled = flag;
        BtnSave.Enabled = flag;
        BtnCancel.Enabled = flag;

    }

    public void clearControls()
    {
        TxtExtensionNo.Text = "";
        TxtFarmerCode.Text = "";
        TxtFarmerName.Text = "";
        TxtBasicPrice.Text = "";
        TxtPremium.Text = "";
        TxtWeight.Text = "";
        TxtTotalAmountBasic.Text = "";
        TxtTotalAmountPremium.Text = "";
        TxtBalancePay.Text = "";

    }

    private void BtnNew_Click(object sender, EventArgs e)
    {
        if (obj.GetConnection() == true)
        {
            lblError.Text = "Connected !!!";
        }
        else
        {
            lblError.Text = "Not connnected !!!";
        }
        enableDisableControls(true);
        BtnNew.Enabled = false;
        // lblError.Text = "";
        string connectionString = "Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True";
        string sql = "SELECT * FROM cottonpurchase";
        SqlConnection connection = new SqlConnection(connectionString);
        SqlDataAdapter da = new SqlDataAdapter(sql, connection);
        DataSet ds = new DataSet();

        connection.Open();
        da.Fill(ds, "cottonpurchase");
        connection.Close();
        dataGridView1.DataSource = ds;
        dataGridView1.DataMember = "cottonpurchase";

    }

    private void BtnSave_Click(object sender, EventArgs e)
    {
        if (obj.GetConnection() == true)
        {

            //dateTimePicker1.Value = DateTime.Today;
            MessageBox.Show("insert into cottonpurchase values(" + TxtExtensionNo.Text + ",'" + monthCalendar1.TodayDate + "'," + TxtFarmerCode.Text + ",'" + TxtFarmerName.Text + "'," + TxtBasicPrice.Text + "," + TxtPremium.Text + "," + TxtWeight.Text + "," + TxtTotalAmountBasic.Text + "," + TxtTotalAmountPremium.Text + "," + TxtBalancePay.Text + ")");

            if (obj.ExecuteSQLStatement("insert into cottonpurchase values(" + TxtExtensionNo.Text + ",'" + monthCalendar1.TodayDate + "'," + TxtFarmerCode.Text + ",'" + TxtFarmerName.Text + "'," + TxtBasicPrice.Text + "," + TxtPremium.Text + "," + TxtWeight.Text + "," + TxtTotalAmountBasic.Text + "," + TxtTotalAmountPremium.Text + "," + TxtBalancePay.Text + " )") == true)
            {
                lblError.Text = "Item(s) Saved";
                clearControls();
                BtnSave.Enabled = false;
                BtnNew.Enabled = true;
                enableDisableControls(false);
            }

            else
            {
                lblError.Text = "Item(s) Not Saved";
            }
        }

        else
        {
            lblError.Text = "Connection Error. Please contact your administrator.";
        }

        enableDisableControls(false);
        clearControls();
        BtnNew.Enabled = true;

        try
        {
            //double getvat = 0;
            //double calculatevat = 0;
            //getvat = Convert.ToDouble(TxtTotalAmountBasic.Text);
            //calculatevat = getvat * 0.18;
            //TxtBasicPrice.Text = calculatevat.ToString();
            //TxtBasicPrice.Enabled = false;
        }

        catch (Exception)
        {
            // lblError.Text = "Please contact your administrator. (Error - TARS0001DATMIS)";
            clearControls();
            enableDisableControls(false);
            BtnNew.Enabled = true;
            //lblInvoiceNo.Text = "INVOIC NO";
        }
    }

    private void BtnCancel_Click(object sender, EventArgs e)
    {
        enableDisableControls(false);
        clearControls();
        BtnNew.Enabled = true;
    }

    private void panel1_Paint(object sender, PaintEventArgs e)
    {

    }

    private void TxtFarmerCode_TextChanged(object sender, EventArgs e)
    {
         try
        {
            SqlConnection conn= new SqlConnection("Data Source=TANYA-PC;Initial Catalog=biore1;Integrated Security=True");
            conn.Open();
            cmd = new SqlCommand("Select farmername, from cottonpurchase where farmercode=@aa", conn);
            cmd.Parameters.Add("@aa", SqlDbType.Int).Value = TxtFarmerCode.Text;
            dr = cmd.ExecuteReader();
            if (dr.HasRows == false)
            {
                throw new Exception();
            }
            if (dr.Read())
            {
                // textBox1.Text = dr[0].ToString(); Since U r going to give the ID and retrieve in textBox1.
                TxtFarmerName.Text = dr[0].ToString();
                //textBox3.Text = dr[1].ToString();
                //textBox4.Text = dr[2].ToString();
                //textBox7.Text = dr[3].ToString();
                //dateTimePicker1.Text = dr[4].ToString();
                //dateTimePicker2.Text = dr[5].ToString();
                //textBox5.Text = dr[6].ToString();
            }
        }
        catch
        {
        //    lblError = "THE GIVEN ID IS UNAVAILABLE";
        }
        finally
        {
            conn.Close();
        }
    }

    }

A: You have to define your variable types
SqlCommand cmd = new SqlCommand(...);
SqlReader dr = cmd.ExecuteReader();

A: In TxtFarmerCode_TextChanged, you haven't defined the variables cmd or dr.
You'll want something like this:
        SqlCommand cmd = new SqlCommand("Select farmername, from cottonpurchase where farmercode=@aa", conn);
        [...]
        SqlDataReader dr = cmd.ExecuteReader();


text:
Q: "Undefined reference to `avcodec_alloc_frame" Error when compile and install Opencv on linux I am compiling and installing OpenCV using the steps in http://docs.opencv.org/2.4/doc/tutorials/introduction/linux_install/linux_install.html
But during "making" it, it has error when it reaches 45%. The error message is
...
[ 43%] Built target pch_Generate_opencv_video
[ 44%] Built target opencv_video
[ 44%] Built target opencv_perf_video_pch_dephelp
[ 45%] Built target pch_Generate_opencv_perf_video
Linking CXX executable ../../bin/opencv_perf_video
../../lib/libopencv_videoio.so.3.1.0: undefined reference to `avcodec_alloc_frame'
../../lib/libopencv_videoio.so.3.1.0: undefined reference to `avcodec_encode_video'
collect2: error: ld returned 1 exit status
make[2]: *** [bin/opencv_perf_video] Error 1
make[1]: *** [modules/video/CMakeFiles/opencv_perf_video.dir/all] Error 2
make: *** [all] Error 2

I downloaded and installed the latest version of ffmpeg from https://www.ffmpeg.org/.
Anyone knows how can I fix the errors?
Thank you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: d3.js (v3) enter() not working in bar chart update I have a bar chart which is working fine except when an update with longer data is passed to it in the updateChart function new bars are not created although the existing bars do transition correctly.
jsFiddle
    var initialData = [
    {Date: '2017-01-01', Volume: 56},
    {Date: '2017-01-02', Volume: 98},
    {Date: '2017-01-03', Volume: 45},
    {Date: '2017-01-04', Volume: 21},
    {Date: '2017-01-05', Volume: 40}
  ];
  var updatedData = [
    {Date: '2016-12-27', Volume: 89},
    {Date: '2016-12-28', Volume: 81},
    {Date: '2016-12-29', Volume: 75},
    {Date: '2016-12-30', Volume: 160},
    {Date: '2016-12-31', Volume: 65},
    {Date: '2017-01-01', Volume: 56},
    {Date: '2017-01-02', Volume: 98},
    {Date: '2017-01-03', Volume: 120},
    {Date: '2017-01-04', Volume: 21},
    {Date: '2017-01-05', Volume: 40}
];

var bottomPadding = 20;
var leftPadding = 30;
var topPadding = 0;
var rightPadding = 40;
var width = 375 - leftPadding-rightPadding;
var height = width * .75;
var xScale,volScale;
var xAxis,volAxis,volAxisGroup;

drawChart();

function drawChart() {

  var gData = initialData;

  var minDate = getDate(gData[0]);
  var maxDate = getDate(gData[gData.length - 1]);
  var maxVol = d3.max(gData, function (d) { return +d.Volume });

  xScale = d3.time.scale()
  .range([leftPadding, width + leftPadding]);

  volScale = d3.scale.linear()
  .rangeRound([height, (topPadding+10)]);

  //set up canvas
  var stockLineCht = d3.select("#chart")
  .append("svg:svg")
  .attr("width", width + leftPadding + rightPadding)
  .attr("height", height + bottomPadding + topPadding);

  //add x-axis
  xAxis = d3.svg.axis()
  .scale(xScale)
  .orient("bottom")
  .ticks(5);

  //add r-axis
  volAxis = d3.svg.axis()
  .scale(volScale)
  .orient("right")
  .tickFormat(d3.format("s"))
  .ticks(5);

  volAxisGroup = stockLineCht.append("g")
  .attr("class", "axis")
  .attr("transform", "translate(" + (leftPadding + width) + ",0)");

  xScale.domain([minDate, maxDate]);
  volScale.domain([0, maxVol]);

  //VOLUME bars
  var y1Bars = stockLineCht.selectAll("bars")
    .data(gData)
    .enter()
    .append("svg:rect")
    .attr("class", "bar");

  y1Bars.attr("x", function (d) { return xScale(getDate(d)) - (width/(gData.length * 1.5)) ; })
    .attr("y", function (d) { return volScale(d.Volume); })
    .attr("height", function (d) { return height - volScale(d.Volume); })
    .attr("width", function (d) {return width/(gData.length * 1.5);});

  volAxisGroup
    .attr("class", "r axis")
    .call(volAxis);

  stockLineCht.append("g")
    .attr("class", "x axis")
    .attr("transform", "translate(0," + height + ")")
    .call(xAxis);
}

window.updateChart = function() {
    console.log('update called');
  var newData = updatedData;
  console.log(newData);

  var minDate = getDate(newData[0]);
  var maxDate = getDate(newData[newData.length - 1]);
  var maxVol = d3.max(newData, function (d) { return +d.Volume });

  xScale.domain([minDate, maxDate]);
  volScale.domain([0, maxVol]);

  var stockLineCht = d3.select("#chart");

  var y1Bars = stockLineCht.selectAll(".bar")
  .data(newData);

  y1Bars.enter()
  //.append("g")
  .append("svg:rect")
  .attr("class", "bar");
  //.append("svg:rect");

  y1Bars.transition()
  .duration(750)
  .attr("x", function (d) { return xScale(getDate(d)) - (width/(newData.length * 1.5)) ; })
  .attr("y", function (d) { return volScale(d.Volume); })
  .attr("height", function (d) { return height - volScale(d.Volume); })
  .attr("width", function (d) { return width/(newData.length * 1.5); });

  y1Bars.exit().transition().duration(750)
      .selectAll("rect")
      .attr("height", 0)
      .remove();

  stockLineCht.select(".x.axis") // change the x axis
  .transition()
  .duration(750)
  .call(xAxis);

  stockLineCht.select(".r.axis") // change the r axis
  .transition()
  .duration(750)
  .call(volAxis);
}

  // helper function
  function getDate(d) {
    return new Date(d.Date);
  }

A: This looks like a working solution. I changed a few things.
First, the bars were somehow not being correctly added to the graph. So instead we're adding it directly through the svg now. I don't think it was getting the correct parent element in the previous method.
  var y1Bars = d3.select("svg").selectAll(".bar")
    .data(newData);

I also changed the part where you're entering the bars so it looks more like a transition-
  y1Bars.enter()
    //.append("g")
    .append("rect")
    .attr("class", "bar")
    .attr("x", width)
    .attr("y", function(d) {
      return height - volScale(d.Volume);
    })
    .attr("width", (width / (newData.length * 1.5)))
    .attr("height", function(d) {
      return volScale(d.Volume);
    });

Solution here - https://jsfiddle.net/w7eaf3o5/6/


text:
Q: Output 'do_settings_sections()' as tabs, not one under the other I'm using the Settings API on an admin page and it's marvelously simple and all that.
public function on_show_page(){

?>

<?php _e('Admin Bar Button Settings', 'djg-admin-bar-button'); ?>

        <form action="options.php" method="post">

            <?php settings_fields('admin_bar_button_group'); ?>
            <?php do_settings_sections('djg_admin_bar_button'); ?>

                <?php submit_button('Save Changes', 'primary', 'submit', false); ?>
                <?php submit_button('Restore Defaults', 'delete', 'delete', false); ?>

        </form>

<?php
}

However, as far as I can tell there is no way to display my four different sections as tabs (using jQuery UI Tabs), rather than one under the other.
Does anybody know of an out of the box way to do this? Thanks.

A: So because I couldn't find an out of the box way, I created this.  Don't forget to enqueue the jquery-ui-tabs script -
/** Replace the call to 'do_settings_sections()' with a call to this function */
function do_settings_sections_tabs($page){

    global $wp_settings_sections, $wp_settings_fields;

    if(!isset($wp_settings_sections[$page])) :
        return;
    endif;

    echo '
';
    echo '
';

    foreach((array)$wp_settings_sections[$page] as $section) :

        if(!isset($section['title']))
            continue;

        printf('
%2$s
',
            $section['id'],     /** %1$s - The ID of the tab */
            $section['title']   /** %2$s - The Title of the section */
        );

    endforeach;

    echo '
';

    foreach((array)$wp_settings_sections[$page] as $section) :

        printf('
',
            $section['id']      /** %1$s - The ID of the tab */
        );

        if(!isset($section['title']))
            continue;

        if($section['callback'])
            call_user_func($section['callback'], $section);

        if(!isset($wp_settings_fields) || !isset($wp_settings_fields[$page]) || !isset($wp_settings_fields[$page][$section['id']]))
            continue;

        echo '
';
        do_settings_fields($page, $section['id']);
        echo '
';

        echo '
';

    endforeach;

    echo '
';

}

Here is the CSS for it.  You could download and enqueue a style from the jQuery UI website if you wish, but none suited me, so I made this -
.ui-tabs ul.ui-tabs-nav{
    border-bottom: 2px solid #E2E2E2;
    line-height: 31px;
}
.ui-tabs ul.ui-tabs-nav li{
    border-top: 1px solid transparent;
    border-right: 1px solid transparent;
    border-left: 1px solid transparent;
    border-bottom: none;
    display: inline;
    padding: 8px 20px;
}
.ui-tabs ul.ui-tabs-nav li.ui-state-active{
    background-color: #F1F1F1;
    border-top: 1px solid #E2E2E2;
    border-right: 1px solid #E2E2E2;
    border-left: 1px solid #E2E2E2;
    border-bottom: none;
}
.ui-tabs ul.ui-tabs-nav li a{
    color: #6BACD9;
    font-size: 1.3em;
    font-weight: bold;
    text-decoration: none;
}
.ui-tabs ul.ui-tabs-nav li a:hover{
    color: #4A89BF;
}
.ui-tabs ul.ui-tabs-nav li.ui-state-active a{
    color: #222222;
    cursor: default;
}

And one simple jQuery function -
$(function(){
    $('#abb-tabs').tabs();
});

A: The MarkUp to produce tabs in the admin UI is the following:

    Tab #1
    Tab #2
    Tab #3

Now, when you are requesting an admin page, you can use any query args:
http://example.com/wp-admin/tabshow?tab=1

If you register your admin menu page, you simply add a query arg of ?tab=1 directly to the nav menu link. In your UI callback, you then use admin_url() (escaped):
$link = esc_url( admin_url( 'tabshow' ) );

You could as well use $_SERVER['REQUEST_URI'] to simply refer to the same page. On top of that, you just add the query args for tab=1, tab=2, tab=n. You get the point.
Then just switch through the different contents
switch ( $_GET['tab'] )
{
    default :
    case '1' :
        // contents of page 1
        break;
    case '2' :
        // contents of page 2
        break;
    case 'n' :
        // contents of page 'n'
        break;
}


text:
Q: Swift 3 - Tesseract recognize throwing errors for any image manipulation I am using Swift 3 and developing an application where the user takes a photo and uses Tesseract OCR to recognize the text in it.
The following code block works.
func processPhoto() {
    if let tesseract = G8Tesseract(language: "eng") {
        tesseract.delegate = self

        // this is the resulting picture gotten after running the capture delegate
        tesseract.image = stillPicture.image!
        tesseract.recognize()
    }
}

However, if I try to manipulate the picture at all (stillPicture.image!), I get the following error:
Error in pixCreateHeader: depth must be {1, 2, 4, 8, 16, 24, 32}
Error in pixCreateNoInit: pixd not made
Error in pixCreate: pixd not made
Error in pixGetData: pix not defined
Error in pixGetWpl: pix not defined
2017-03-13 11:13:05.336796 ProjectName[35238:9127211] Cannot convert image to Pix with bpp = 64
Error in pixSetYRes: pix not defined
Error in pixGetDimensions: pix not defined
Error in pixGetColormap: pix not defined
Error in pixClone: pixs not defined
Error in pixGetDepth: pix not defined
Error in pixGetWpl: pix not defined
Error in pixGetYRes: pix not defined
Please call SetImage before attempting recognition.Please call SetImage before attempting recognition.2017-03-13 11:13:05.343568 EOB-Reader[35238:9127211] No recognized text. Check that -[Tesseract setImage:] is passed an image bigger than 0x0.

Some things that I do to manipulate the picture is to rotate it:
// Rotate taken picture
let orig_image = stillPicture.image!

let new_image_canvas = UIGraphicsImageRenderer(size: CGSize(width: stillPicture.image!.size.height,
                                                                  height: stillPicture.image!.size.width))
let new_image = new_image_canvas.image { _ in
    let curr_context = UIGraphicsGetCurrentContext()!
    curr_context.translateBy(x: 0, y: stillPicture.image!.size.width)
    curr_context.rotate(by: -.pi/2)
    stillPicture.image!.draw(at: .zero)
}

tesseract.image = new_image

If I do that, BOOM! The error above occurs.
Another manipulation I do is to crop portion of the image.
let finalImage : UIImage

let crop_section = CGRect(x: 590.0, y: 280.0, width: 950.0, height: 550.0)

let cg_image = stillPicture.image!.cgImage?.cropping(to: crop_section)
finalImage = UIImage(cgImage: cg_image!)

tesseract.image = final_image

Again, BOOM! Error appears.  Any idea why this is happening and why my image manipulations are causing problems?  Thanks for your help!

A: Whatever transformations you make to the image leave it in a format which Tesseract cannot understand. Tesseract uses the Leptonica library to handle image formats, and Leptonica can understand only images in a certain format.
The first line:
Error in pixCreateHeader: depth must be {1, 2, 4, 8, 16, 24, 32}

already is a big hint on what the error is. Bit depth means how many bits per pixel you have. For example a 24-bit image is usually RGB - you have 8-bits (or one byte) for red, green and blue each - total of 24-bits. 32-bits is for ARGB (RGB+alpha channel). 1 bit is monochrome.
See http://search.cpan.org/dist/Image-Leptonica/lib/Image/Leptonica/Func/pix1.pm#pixCreateHeader - pixCreateHeader is a leptopnica function.
So try the following - save the image to a file, and open it in some image editor and check what type of image it is, esp. the bit depth.
Apparently your image is using some weird bit depth. Also look at Node.js 20x slower than browser (Safari) with Tesseract.Js, because this is the only question that I could find where Error in pixCreateHeader: depth must be {1, 2, 4, 8, 16, 24, 32} is also mentioned.


text:
Q: What's the advantage of splitting a mysql table into smaller ones without physical distribution? I've seen such design in my company.
A big mysql table is split into tens of smaller ones of identical schema on the same server in the same db, without any physical distribution, no innodb_file_per_table, no partitioning, etc. The data is distributed evenly and the read/write access pattern is uniform across all tables.
What's advantage of doing so performance-wise?

A: If your reads/writes are distributed evenly, I think there's no performance advantage. If you were write heavy and writing to, for example, just 2-3 of the tables - then you could benefit (see slides 28-34 of this presentation).
A few ideas about operational benefits:

*

*It'll be easier to scale out/shard once there's too much data or too much traffic.

*Depending on how your backups are made, it might be quicker to recover something if you can determine in which of the tables lost data was located.

Edit: one more thought: if the queries are executed in parallel, there might be performance benefits - you can get more IOPS from your RAID, and better localisation of multi-core system if the working set fits in the memory.


text:
Q: js addclass function not working as expected, intereaction or special WP somethign needed? I am having an issue adding a class via jsto an existing html set up. If I inspect, it simply doesnt show up. It doesnt add it. I have it on a delay to ensure everything is done loading. I have also set a console.log message just to ensure that the function is running and it is.
It does not show in the console as even having been added. Is there something below that is specific to wordpress that is interfering? The example below works on its own but not in its environment.
What am I doing wrong here?
function classadd() {
      window.setTimeout(function () {

        var ideal = document.getElementById( 'test' )
        var parent = document.getElementById('t_options')
        if(ideal){
          parent.classList.add('black');
          console.log('running');
        } else {
          console.log('uh-oh');
        }
      },7000);
    }

  classadd();

    .black{background:black!important;}

        some content


text:
Q: Implement HTML CSS and Javascript Template in Angular 7 I purchased a template which includes HTML, CSS, and Javascript files for a static webpage. I'm trying to use these existing files in my Angular project so I can connect it with a Nodejs app to make it a full stack webpage with backend. However, when I tried to put these files into Angular, everything is broken and is not functioning as it would when I manually open the HTML files on Chrome.
I've tried creating components for each HTML pages and adding the CSS and Javascript files into assets folder. Then I went on angular.json and added each CSS files into the styles array and the Javascript files into scripts array.
The HTML files look something like this:
<!doctype html>
<html lang="en">
<head>

<!-- Basic Page Needs
================================================== -->
<title>Hireo</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

<link rel="stylesheet" href="../../../assets/css/style.css">
<link rel="stylesheet" href="../../../assets/css/colors/blue.css">

</head>

<body>
.........body code...........
<!-- Scripts
================================================== -->
<script src="js/jquery-3.3.1.min.js"></script>
<script src="js/jquery-migrate-3.0.0.min.js"></script>
<script src="js/mmenu.min.js"></script>
<script src="js/tippy.all.min.js"></script>
<script src="js/simplebar.min.js"></script>
<script src="js/bootstrap-slider.min.js"></script>
<script src="js/bootstrap-select.min.js"></script>
<script src="js/snackbar.js"></script>
<script src="js/clipboard.min.js"></script>
<script src="js/counterup.min.js"></script>
<script src="js/magnific-popup.min.js"></script>
<script src="js/slick.min.js"></script>
<script src="js/custom.js"></script>
</body>
</html>

A: In your angular.json file add the static .html files to the assets array with their respective paths. You can then access the files i.e www.your-domain.com/your-static-file.html

A: Anything you put in your assets folder will be available to the application, just remember to provide the relative/absolute path including assets.
If you have files in other folders or have specific errors (e.g. in the Network tab in Dev Tools), please provide more details that so I can advise. Until then, you can find most common solutions in https://lukasznojek.com/blog/2019/03/angular-cli-different-ways-to-include-assets/.


text:
Q: How can I remove apps from Launchpad in Mac OS X 10.10 (Yosemite)? Is there a way to delete unwanted app icons from Launchpad without using any management app?
This is possible in Mac OS X 10.7 (Lion) using some commands in the "Terminal;" but what about Mac OS X 10.10 (Yosemite)?

A: Apparently you can search for things in spotlight and hit Command-Enter instead of just Enter, and it pulls up the file location, so I promptly deleted it!

A: I came up with a solution via terminal. The location of the SQLite database was changed in Mac OS X 10.10 (Yosemite).
You can still delete apps from the Launchpad with this "Terminal" command. Just replace the APPNAME with the app you want to delete.

sqlite3 $(sudo find /private/var/folders -name com.apple.dock.launchpad)/db/db "DELETE FROM apps WHERE title='APPNAME';" && killall Dock

I tested if it is still deleted after reboot. So far it seems to work.

A: Follow these steps:

*

*Open Finder,

*Open Applications,

*Search for the name of the application which you want to remove from launch pad,

*Drag the application to Trash.

*Process complete.

A: Clicking on an Icon or holding the option key until icons start jiggling, only works for Apps downloaded from the App Store,
I would caution against following answers where you are Trashing the Icon, as often deleting it is not what you want, it has a function it just doesn't belong in Launchpad deleting it could cause further problems down the road.
The Best option for just removing the Icon from Launchpad, but not deleting it is the terminal command posted by davidtrautmann.

A: So, David's answer was pretty close but for some reason it didn't work properly on my computer. (OS X 10.11.6) The find didn't want to recursively search for the database. Since I have knack for poking around where I shouldn't be, I did find a solution that worked. This will require some manual work.
In my case I wanted to remove the Dashboard app since I have it disabled. I frequently use Dash, an offline API documentation app, but Dashboard is the first thing in the list of apps when I search from launchpad. This means I can't just hit ENTER when searching, I have to use my trackpad. And I don't like having to do that. You also can't remove it by click-holding apps because it's a built-in app. Pretty annoying, right?

Search for the folder
In my account, the database was in a subdirectory from /private/var/folders/cn. After reading Tim's comment on David's answer, I realized that multiple folders will exist here; probably one per user. I haven't tested this myself, but I've modified my answer to check first which folder belongs to you.
In the Terminal, copy-paste ls -l /private/var/folders/cn and hit ENTER. Look for the one where your account name shows up by it. Jump to the "Open the DB" section.
(If you want to search with Finder)
If you're not Terminal-savvy and/or prefer to search with Finder, you can create a shortcut. (Please remove it when finished. We're venturing into dangerous territory!) To create one, copy-paste ln -s /private/var/folders ~/Desktop/private into the Terminal and hit ENTER. Open Finder, navigate to your Desktop, open the shortcut, and browse through the folders until you locate com.apple.dock.launchpad. It'll probably be in the cn/(gobbly-gook name)/db folder. If you have several folders under cn, highlight one and hit Command + i and view the owner. Search until you find which one has you as the owner.
Putting it into action in Terminal
Open the DB
You'll want to copy-paste sqlite3 /private/var/folders/cn/(folder name)/0/com.apple.dock.launchpad/db/db into the Terminal, replacing the (folder name) with the one you found. (Remove the parenthesis.) Hit ENTER to open the sqlite3 shell.
(If cn is not the folder, all I can say is to try another one in that /folders directory.)
Remove Apps
Copy-paste DELETE FROM apps WHERE title='APPNAME'; into the Terminal, replace APPNAME with the application you want to remove. Keep the quote marks! Repeat this for as many apps as you need to remove. You can remove system-defaults.
Exit and kill dock
Type .exit to return to bash. Now type sudo killall Dock and hit ENTER. Give the system a moment before opening Launchpad. All the apps you wanted to remove should be gone!

A: I found that my applications were duplicated on the secondary drive and normal procedures only deleted them from the primary drive. I had to remove the files from the secondary drive as well by going into user>applications then delete them from that folder.
good luck!

A: Hold down the option key causes the launchpad icons to shake and some will be removable by clicking the "X" in their corner.  Perhaps that is obvious, but in my case it allowed me to rid my launchpad of the icon I was attempting to remove.

A: In Yosemite open Launchpad, hold down control key and click on icon you wish to remove. A question mark should appear over the icon. Just drag and drop to Trash.


text:
Q: Exposing properties in Composite Controls vs ViewState The common way to expose child controls' properties in CompositeControl is following:
public class MyControl : CompositeControl {
    private TextBox _box;
    public override short TabIndex
    {
        get
        {
            EnsureChildControls();
            return _box.TabIndex;
        }
        set
        {
            EnsureChildControls();
            _box.TabIndex = value;
        }
    }

    protected override void CreateChildControls()
    {
        Controls.Clear();
        _box = new TextBox {ID = "box"};
        Controls.Add(_box);
    }
// ...

}
Is that approach correct? Because since EnsureChildControls adds TextBox to control collection and therefore, triggers its ViewState tracking, so for declarative constructs like this:
<uc:MyControl ID="My" runat="server" TabIndex="10"  />

ViewState is unnecessarily cluttered (or is it not?)


text:
Q: Fixed Points of a Reflection This question is about problem 2.C.5 from Allen Hatcher's Topology. The statement of the problem is as follows:

Let $M$ be a closed orientable surface embedded in $\mathbb{R}^3$ in such a way that reflection across a plane $P$ determines a homeomorphism $r:M\rightarrow M$ fixing $M\cap P$, a collection of circles. Is it possible to homotope $r$ to have no fixed points?

Progress I've made so far: The Euler characteristic of set of fixed points (ie $M\cap P$, a disjoint union of copies of  $S^1$) is 0, which implies by some previous work (Hatcher 2.C.4) that the Lefshetz number of $r$ is 0. So we can't give a definitive no by using the Lefshetz theorem.
Issues I'm having: This question seems like there's so much room to do things that I'm getting a little freaked out. I think I might be able to do this homotoping by taking $[-\delta,\delta]\times S^1$, then for each circle fixed by $r$ rotating the $S^1$ a bit while fixing the ends- but this seems like the might be problems about actually doing this.
I'd appreciate any suggestions or comments about the problem or a means of solution.
EDIT: Turns out I can make this work by twisting the collars as described above. Apparently all I needed to do to figure this out was to write about it.


text:
Q: When I console.log class it returns null I make class userData to get a value of inputs of forms then make another class with LoginData with the same value but with another purpose. My problem when I console.log userData its work fine but when console.log loginData it returns null.
constructor(private alertCtrl: AlertController, public navCtrl:
    NavController, public navParams: NavParams, public authService:
    UserProvider, public loadingCtrl: LoadingController, private toastCtrl:
    ToastController) {

    console.log(this.loginData)
}

userData = {
    "name":  "",
    "email": "" ,
    "Type_Id" : "",
    "Mobile" : "",
    "password": "",
};

loginData = {
    UserEmail: this.userData.name ,
    Password:  this.userData.email
}

signup(){
  this.showLoader();
  console.log(this.loginData)

  this.authService.postData(this.userData,'Regestier').then((result) => {
    var userinfo = this.responseData;

    console.log(this.responseData);
    localStorage.setItem('userinfo', this.responseData);

    this.login()
    /* if (this.responseData.Type_Id = "1"){
    this.navCtrl.push(CompanyProfilePage, {}, {animate: true, direction:
    'forward'});
    }
    else
    {
      this.navCtrl.setRoot(DashboardPage, {}, {animate: true, direction:
      'forward'});

    }*/

    this.loading.dismiss();
    this.presentPrompt()
 },

 (err) => {
   // Error log
    this.loading.dismiss();

  });

}

I want to use UserData to store signup form Data and LoginData to store login Data. The sign up working but login does not work. The problem is loginData returns null.

A: Put your userData and loginData inside constructor.
export class MyComponent {

  userData; loginData;

  constructor(public navCtrl: NavController) {

    this.userData = {
    "name":  "",
    "email": "" ,
    "Type_Id" : "",
    "Mobile" : "",
    "password": "",
    };

    this.loginData = {
    UserEmail: this.userData.name ,
    Password:  this.userData.email
    };
  }

  ngOnInit() {

    console.log(this.loginData);
  }

}

exmaple

A: You need to make some changes to your declaration process.
Make use of the Angular lifecycle hook ngOnInit() to do your declarations:
ngOnInit(){
    this.loginData = {
       UserEmail: this.userData.name ,
       Password:  this.userData.email
    }
}

The Constructor is a default method of the class that is executed when
  the class is instantiated and ensures proper initialization of fields
  in the class and its subclasses.
ngOnInit is a life cycle hook called by Angular2 to indicate that
  Angular is done creating the component.

A: You can use Reactive forms which are very easy to use. First import it in your app.module.ts like this:
import { ReactiveFormsModule, FormsModule } from '@angular/forms';

then add them to your imports array like this,
  imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],

this is how your component.ts can look like :
import { Component } from '@angular/core';
import { FormGroup,FormControl,FormBuilder } from '@angular/forms';

 @Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
 name = 'Angular';
 userData:FormGroup;
 constructor(fb:FormBuilder){
this.userData = fb.group({
  name : new FormControl(''),
  email : new FormControl(''),
  Type_Id : new FormControl(''),
  Mobile : new FormControl(''),
  Password : new FormControl(''),
 })
}

signup(){
console.log(this.userData.value.email);
console.log(this.userData.value.Password);
 }
}

Then your component.html file can look like this:
<form [formGroup]="userData" (ngSubmit)="signup()">
 <input type="text" formControlName="email">
 <input type="password" formControlName="Password">
 <button (click)="signup()">signup</button>
</form>

It should work now. Look more into reactive forms they are really awesome !


text:
Q: How to boot to command-line interface in Ubuntu 16.04 I want to permanently switch from GUI mode to text mode interface in Ubuntu 16.04.
I tried editing the configuration in /etc/default/grub as follows:

*

*Adding # before GRUB_CMDLINE_LINUX_DEFAULT="quite splash"

*Adding "text" in GRUB_CMDLINE_LINUX="text"

*Removing # before GRUB_TERMINAL=console

*And at last running update-grub.

But it didn't work. So what should I do to permanently switch to command line/text interface in Ubuntu?

A: You need to disable display-manager service since ubuntu 16.04 moved to systemd.
sudo systemctl disable display-manager.service

After a reboot it will boot into text mode. Be cautious however, some hardware driver combinations have dead virtual consoles...if that happens, add nomodeset into your kernel parameter to boot the system, it will boot with default graphic settings from boot loader.

A: Almost.  I think you just want to change:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

to:
GRUB_CMDLINE_LINUX_DEFAULT="text"

Then, update GRUB:
sudo update-grub

Assuming you get that to work , you may want to also remove any window manager and display manager, in which case this could help you.


text:
Q: CURL's weird behavior (error 400) when making http request I have such code that makes http request to Yandex Translate API:
const char url[] = "https://translate.yandex.net/api/v1.5/tr.json/translate";
const char key[] = "secret.key.here";
char buf[4096] = { 0 };
char input[1024] = "Hello world. H";
snprintf(buf, sizeof(buf), "%s?key=%s&lang=ru&text=\"%s\"",
         url, key, input);

struct string response;
init_string(&response);

CURL *curl;
CURLcode res;
curl = curl_easy_init();
if(curl) {
    curl_easy_setopt(curl, CURLOPT_URL, buf);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
    curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response);
    res = curl_easy_perform(curl);
    if(res != CURLE_OK) {
        fprintf(stderr, "curl_easy_perform() failed: %s\n",
                curl_easy_strerror(res));
    }
    curl_easy_cleanup(curl);
}

printf("%s\n", response.data);

After snprintf execution, buf contains such url:
https://translate.yandex.net/api/v1.5/tr.json/translate?key=secret.key.here&lang=ru&text="Hello world. H"

and after response, response.data contains:

<title>400 Bad Request</title>

400 Bad Request

nginx/1.6.2

but if I reassign char input[1024] = "Hello world."; (without "H"), after http request, I get the proper response:
{"code":200,"lang":"en-ru","text":["\"Здравствуй, мир!\"."]}.
What could be the problem?

A: You need to encode your input text for usage in URL. Try this curl function
char *input = curl_easy_escape(curl, "Hello world. H", 0);


text:
Q: Identical objects in list is it possible to detect identical objects as different variables, say object1=(1,2,3) and object2=(1,2,3).
list = []

If i now put object 1 in the list together with object 2 the list becomes:
list.append(object1)
list.append(object1)
print(list)
list = [(1,2,3),(1,2,3)]

How can i let python decide whether or not the first element in the list is object1?
This is something i have to do for my school project.

A: The computer does only what you tell it to do. So if you append something twice, it will listen. If you want it to do it under a condition, you need to use an if statement and compare the values within the list to the value you are trying to add. To make this easier, I would put this in a function so you can call this logic easily
In your case, I'm assuming you only want to add the object if it doesn't exist:
list = []
def addToList(elem):
    global list # allows the function to modify this variable that would be normally out of scope
    if elem not in list:
        list.append(elem)

object1 = [1,2,3]
addToList(object1)
addToList(object1)
print(list)

A: you could cast to set then back to list:
my_list = [(1,2,3),(1,2,3)]
print(list(set(my_list)))
# [(1, 2, 3)]

or you could check first if your object is already in the list:
if object1 not in my_list:
    my_list.append(object1)

A: I found it.
You can do this with the is function.
Block1 is Block2
list[0] is list[1]

response: False


text:
Q: Cordova AutoStart in Background I am developing an ionic cordova application. I want my app to auto start on ios and to remain in background. The app should be able to receive push notifications and to scan for bluetooth while being in background. I have checked ToniKorin/cordova-plugin-autostart plugin, but it only works on android not on ios.
any suggestion ?

A: You can not set an app to start automatically into iPhone using Cordova, generally iOS apps do not start with the system, and there is no way to make them do so. One exception is made, for VOIP-enabled apps to establish connections and begin listening for incoming calls, all apps with the appropriate plist keys are launched on system startup, then backgrounded without user interaction. This behavior is documented by Apple.
In the iPhone Native apps you can set BootLaunch - an iOS startup app to setup your apps to launch an app when booting an iOS device.


text:
Q: TypeScript Clientside usage I am in the process of migrating my project from JavaScript to TypeScript, so far everything went according to plan, but now I encountered a problem.
On the server side the TypeScript files are seen as modules, due to the use of import {controller} from "module" for example.
On the server side this is not an obstacle.
But now I'm wondering how I can use my types on the client side as well, for example the User.ts class - this can be used on the server side part without any problems. How can I use this client-side, since importing modules is not supported so far?
Are there any ways to achieve this without using Webpack or Browserify or similar?


text:
Q: Installing GRUB2 I need to install grub2 on Ubuntu 16 LTS.
When I try to boot both Windows 10 and Ubuntu, Windows 10 loads fine, But Ubuntu loads once and twice does not. I am afraid to damage the hard disk because i have to press power button to boot again!


text:
Q: python mock patch error I have multiple unit_test files created in my project.
When i run all the test files independtely, all files passes all the test cases.
But when i run all the test through TestRunner, i get error as
TypeError: 'NoneType' object is not callable.

I have noticed that this error is thrown because of patching.
======================================================================
ERROR [0.001s]: test_create_pull_requests (test_custom_logs_manager.TestCustomLogManager)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/x/local/dmali/githome/am-repo/unit_tests/lib/mock/mock.py", line 1201, in patched
    return func(*args, **keywargs)
  File "/x/local/dmali/githome/am-repo/unit_tests/data_process/caldata/test_custom_logs_manager.py", line 71, in test_create_pull_requests
    cal_handlers)
TypeError: 'NoneType' object is not callable

...

Code Snippet:
@patch('data_process.caldata.custom_logs_manager.CustomLogsPullTrack',
       MagicMock(return_value = MockCustomLogsPullTrack()))
def test_create_pull_requests(self):
    """
    Unit Test for create_pull_requests
    """
    report_times = [datetime.datetime.now()]
    group_id = 1
    data_center = MockDataCenterCalLoc()
    data_center_cal_loc_id = 1
    mock_pull_config = MockPayMonCalBizConfig()
    mock_pull_config.id = 1
    cal_handlers = {'TEST_CAL': 'TEST_CLASS'}
    result = custom_logs_manager.create_pull_requests(report_times,
                                                      group_id,
                                                      data_center,
                                                      data_center_cal_loc_id,
                                                      mock_pull_config,
                                                      cal_handlers)

    self.assertEqual(result[0].paymon_calbiz_config_id, 1)
    self.assertEqual(result[0].pool_name, 'TEST')
    self.assertEqual(result[0].data_center_cal_loc_id, 1)

A: We had the similiar problem in our unit testing framework. If the method that you are testing through unit test has the decorator "transaction.commit_manually", you need to have the same decorator in the unit test method. Otherwise you get this excpetion "None type object is not callable" which will give no clue about the actual issue.


text:
Q: How to resolve a reload loop issue in the frontend when logged in to WordPress multi-site backend admin area The issue is the websites stemmed from our WordPress multi-site area going into a reload loop on initial load.
Note,this is not a redirect loop, but the page continually attempts to reload in quick succession and doesn't load on first go.
If you do a hard refresh or press ctrl + F5 the website loads fine. This only occurs when you are logged in as an admin user of the Multi-site environment.
We have attempted to resolve by disabling plugins 1 by 1 including any cache related plugins.
Which leads me to think the issue is with the .htaccess file settings for the multi-site environment?
Relevant part of the .htaccess file is below:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin #
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
</IfModule>


text:
Q: Intellij IDEA doesn't show compile errors for Scala project I can't see any compile errors in the project.
I've already tried to

*

*to restart IDE.

*to enable Scala type-aware highlighting(ctrl+shift+alt+e)

It didn't help.
Below is my IDE Version:
Intellij IDEA 2021.2.2(Ultimate Edition)

A: I've figured it out with the following steps.

*

*Update Scala plugin if possible.

*Disable other plugins(e.g. Andoroid).

*Restart IDE.

*Enable all the needed plugins again.


text:
Q: Can I use the CastCompanionLibrary if I don't use an ActionBar I currently am in the process of migrating my Chromecast app to the new sdk. I am trying to use the CastCompanionLibrary to make my life easier, but I am running into a problem.  I don't currently use an actionBar in my app and I plan to add it later on when I redesign the app so for now I can't use an ActionBar.   Can I use the CastCompanionLibrary even if I don't use an ActionBar?
Thanks!!

A: Currently it only supports ActionBar, at least for discovery part. What implementation of discovery are you having in mind?

A: You can use android.support.v7.app.MediaRouteButton instead android.support.v7.app.MediaRouteActionProvider on Actionbar.


text:
Q: Smart PayPal Buttons in React, disable the button I have this implementation of the PayPal smart buttons in React:
function PayPalButtonComponent(props: PayPalButtonProps) {
  const [show, set_show] = useState(false);
  const [error, set_error] = useState<string>();

  const create_order = (_: any, actions: any) => {
    return actions.order.create({
      purchase_units: [
        {
          amount: {
            currency: props.currency || "EUR",
            value: props.total
          }
        }
      ]
    });
  };
  const handle_approve = (_: any, actions: any) => {
    return actions.order.capture().then((details: any) => {
      if (props.onSuccess) props.onSuccess(details);
    });
  };
  const handle_cancel = () => {
    if (props.onCancel) props.onCancel();
  };
  const handle_error = () => {
    if (props.onError) props.onError();
  };
  const render_button = () => {
    const Button = paypal.Buttons.driver("react", { React, ReactDOM });
    return (
      <Button
        style={{
          layout: "horizontal",
          size: "responsive",
          shape: "rect",
          color: "gold",
          tagline: false
        }}
        funding={{
          allowed: [paypal.FUNDING.CARD, paypal.FUNDING.PAYPAL],
          disallowed: [paypal.FUNDING.CREDIT]
        }}
        createOrder={create_order}
        onApprove={handle_approve}
        onError={handle_error}
        onCancel={handle_cancel}
      />
    );
  };

  useEffect(() => {
    if (props.isScriptLoaded) {
      if (props.isScriptLoadSucceed) set_show(true);
      else set_error("Unable to load the paypalscript");
    }
  }, [props.isScriptLoaded, props.isScriptLoadSucceed]);

  if (error) return <p>{error}</p>;
  if (!show) return <FakeButton />;

  return render_button();
}

I have struggled to implement these buttons in react since there is no documentation, I have found and copied some code from here and trying to guess other stuff. But I can't understand how to disable the button.
In this guide they state that one can call the disable() method on the actions object but can't figure out how I can accomplish that with my configuration.
Have you ever try something similar? Do you know any documentation one can follow?
edit
What I'm trying to accomplish is to set the button in a disable state during the payment. I know there is the paypal overlay, but when the transaction completes I change the app route and since it happen when onSuccess is called, due to the apparent async nature of actions.order.capture() this can't happen instantaneously, and so there is a moment when one can click again on the paypal button. If i can disable the button i have solve the problem.
The onInit implementation allows you to disable/enable the button before clicking on it, useful for some sort of validation before the checkout (like terms checked) but doesn't apply to my case. I have also tried to call actions.disable() in create_order but that breaks the button.

A: Have same situation here and the onInit example from documentation is not that straight forward as some think... You would need to create hidden imput and assign somsort of variable to it when payment made in order to achieve buttons to be disabled after payment. To bad no one solve this one.


text:
Q: How can I create a checked listbox of Wordpress categories? The first thing I tried was the following
<input type="checkbox" id="check1" />

<?php wp_list_cats(); ?>

This just creates a single checkbox. What I want to have is a listbox with a checkbox beside each item.

A: <?php
$categories = get_categories();
foreach ($categories as $category) { ?>
<input type="checkbox" name="check" value="<?php echo $category->cat_ID; ?>"><?php echo $category->cat_name;?>

<?php } ?>


text:
Q: Lebesgue Integral and Gradient I am currently studying on Mixed Method to solve Stokes Equation. I encounter this problem when it says $p:\Omega \to \mathbb{R}$ has a zero-mean over a domain $\Omega \subset \mathbb{R}^n$, then $\int_{\Omega}p dx = 0$. May I know how should I understand this statement?
Also, given $\int_{\Omega}p dx = 0$ and $\nabla p = 0$ over $\Omega$, why does this imply $p=0$? I know these may be basic knowledge on Lebesgue Integral, but I hope someone can explain it clearly. Thanks.

A: For Lebesgue measures, nonempty open sets (as a domain $\Omega$ must be) have positive measure. The mean of a function $f$ on $\Omega$ is defined to be $\frac{1}{\mu(\Omega)}\int_{\Omega} f\ dx$, so if this equals zero, the desired integral must of course equal zero.
To show the second statement, $\nabla f = 0$ on $\Omega$ implies that $f$ is constant on $\Omega$. If you want to justify that, suppose $f(x)\ne f(y)$. Then we can find a path $\gamma$ in $\mathbb{R}^n$ connecting $x$ to $y$ such that the path is piecewise composed of segments in which only one coordinate changes. Then, apply the mean value theorem to each of these segments, as you would in single variable calculus. Having justified this, if $f = C$ on $\Omega$, then $0 = \int_{\Omega} f\ dx = \mu(\Omega)C$ implies that $C = 0$ since $\mu(\Omega) \ne 0$.


text:
Q: Raising Javascript confirm box from code behind I am trying to raise a Javascript confirm box from code behind.
I am using the following syntax
ScriptManager.RegisterStartupScript(this, GetType(), "key", "javascript:return confirm('Are you sure you want to delete?');", true);

It is throwing an error:

return statement out of function

Please help.

A: Remove the return, you are not returning this value anywhere. The RegisterStartupScript is executing the function in the global context:
ScriptManager.RegisterStartupScript(
    this,
    GetType(),
    "key",
    "confirm('Are you sure you want to delete?');",
    true
);

But this is probably something you should not even be doing on the server. You should ask for confirmation BEFORE calling the server side. By subscribing to the onclick javascript handler of the corresponding control that is raising the server side event to delete.
For example if you have a delete link:
<asp:LinkButton
    ID="DeleteButton"
    runat="server"
    CausesValidation="False"
    CommandName="Delete"
    Text="Delete"
    OnClientClick="return confirm('Are you sure you want to delete?');"
/>


text:
Q: Passing fields (instance variables) by arguments (parameters) inside an object - does it make sense? I believe this is language agnostic question - if it's not then please correct me.
Let's say I have a class (code snippet is a kind of 'pseudo code')
class Car:
  private steering_wheel
  private engine
  public Car(steering_wheel, engine):
    this.steering_wheel = steering_wheel
    this.engine = engine

  public void service():
     clean_steering_wheel()
     repair_engine()

  private void clean_steering_wheel():
    this.steering_wheel.do_stuff()

  private void repair_engine():
    this.engine.do_stuff()

which works well! But I could also change private methods a bit and let them use fields (i.e steering_wheel and engine) via arguments, not directly
   class Car:
  private steering_wheel
  private engine
  public Car(steering_wheel, engine):
    this.steering_wheel = steering_wheel
    this.engine = engine

  public void service():
     clean_steering_wheel(this.steering_wheel)
     repair_engine(this.engine)

  private void clean_steering_wheel(steering_wheel):
    steering_wheel.do_stuff()

  private void repair_engine(engine):
    engine.do_stuff()

Let's assume that all parameters(arguments) are passed by reference.
What are the advantages and disadvantages of these solutions? Which is considered as better practice? Which one do you prefer?

A: Sounds very much a judgement call to your specific situation, but a couple considerations come to mind.  If the methods are private, and you don't have any reason to pass the parameter, I would probably avoid it if for no reason other than it being less complex.  You could also argue that there is a performance reason to avoid it, as there is no reason to pass additional parameters on the stack if they aren't needed.
One time I do find that I do pass a member as a parameter is with protected members.   Let's say a child class does something like add a second steering wheel that also needs to be cleaned.  In that case, it could (presumably) re-use the clean_steering_wheel method from the base class and pass a different steering wheel member.

A: Passing the field as an explicit parameter is better
if you're not invoking a method, but a function/static method:
The less data is available in a function,
the more explicit all dependencies are,
the easier it is to reason about that code.
So a function clean_steering_wheel(steering_wheel) will not surprise a user
by actually doing something with the engine.
However, a (private) method will already receive references
to the engine and steering_wheel
via the implicit this parameter.
If you have a this parameter in addition to an explicit steering_wheel parameter,
you are duplicating your data – which can lead to inconsistencies.
In particular, I'd be wondering why you didn't use the steering_wheel from this:
Are you operating on the steering_wheel of a different Car?
On a steering_wheel that does not belong to any Car?
In light of this, it would be less confusing to define clean_steering_wheel as
private void clean_steering_wheel():
  this.steering_wheel.do_stuff()

However, it would be even better to use a free function:
void function clean_steering_wheel(steering_wheel):
  steering_wheel.do_stuff()

void function repair_engine(engine):
  engine.do_stuff()

class Car:
  ...

  public void service():
    clean_steering_wheel(this.steering_wheel)
    repair_engine(this.engine)

, or static method:
class Car:
  ...

  public void service():
    clean_steering_wheel(this.steering_wheel)
    repair_engine(this.engine)

  private static void clean_steering_wheel(steering_wheel):
    steering_wheel.do_stuff()

  private static void repair_engine(engine):
    engine.do_stuff()

Which precise approach to use is quite language-specific, and also has impact on testability.
E.g. in C++, using free functions in an anonymous namespace affords the best encapsulation,
but actively hinders testability.
Private static member functions might be better, since they can be tested by a friend class.
In Java, you can't have free functions but must use "static methods",
so the discussion is unnecessary.


text:
Q: graph algorithm, approximation algorithm After removing the leaves of the dfs tree of a random graph , suppose the number of edges left is |S|, can we prove that the matching for that graph will be |S|/2?

A: Here's a proof.
Theorem: Let T be any tree with i leaves.  There is a (|T|-i)/2 matching in T.
Proof: by induction.  If T is a tree with i leaves, let T' be the tree that results when removing all the leaves from T.  T' has j <= i leaves.  Similarly, let T'' be the tree that results when removing all the leaves from T'.  T'' has k <= j leaves.
Apply the theorem by induction to T'', so there exists a matching of size (|T''|-k)/2 = (|T|-i-j-k)/2 in T''.  The set of edges T-T' contains at least j edges that are not incident to any edge in T'' or to each other (pick one incident to each leaf in T'), so add those edges to make a matching in T of size (|T|-i+j-k)/2.  Since j >= k, this is at least (|T|-i)/2 edges. QED.
I've glossed over the floor/ceiling issues with the /2, but I suspect the proof would still work if you included them.


text:
Q: How to get a subcollection from a document firestore flutter Im trying to fetch the documents from a subcollection which is in another document, and when I try to fetch the docs and fill a local list with the "docs data" it doesn't fill it, can anyone tell me what I'm doing wrong here?
My method of when I try to fetch the subcollection:
  static Stream<List<CheckInOutModel>> employeeCheckInOutStream() {
    return firebaseFirestore
        .collection('employees')
        .doc(auth.currentUser!.uid)
        .collection('employeeList')
        .snapshots()
        .asyncMap((QuerySnapshot querySnapshot) {
      final List<CheckInOutModel> employeesCheckInOutList = [];
      for (final element in querySnapshot.docs) {
        firebaseFirestore
            .collection('employees')
            .doc(auth.currentUser!.uid)
            .collection('employeeList')
            .doc(element.id)
            .collection('checkInOutList')
            .snapshots()
            .asyncMap((QuerySnapshot query) {
          for (final element in query.docs) {
            final employeeCheckInOutModel =
                CheckInOutModel.fromDocumentSnapshot(
              documentSnapshot: element,
            );
            employeesCheckInOutList.add(employeeCheckInOutModel);
          }
        });
      }
      return employeesCheckInOutList;
    });
  }

My method when I fetch the fields of the documents that the subcollection is in:
  static Stream<List<EmployeeModel>> employeeStream() {
    return firebaseFirestore
        .collection('employees')
        .doc(auth.currentUser!.uid)
        .collection('employeeList')
        .snapshots()
        .map((QuerySnapshot query) {
      final List<EmployeeModel> employees = [];
      for (final employee in query.docs) {
        final employeeModel =
            EmployeeModel.fromDocumentSnapshot(documentSnapshot: employee);
        employees.add(employeeModel);
      }
      return employees;
    });
  }

A: So I figured out what I did wrong here, I tried to call a stream of it when I only needed it when a callBack is called, so I changed the logic accordingly and went with Future instead Stream
My updated code:
  static Future<List<CheckInOutModel>> employeeCheckInOutStream({
    required String id,
  }) async {
    final List<CheckInOutModel> employeesCheckInOutList = [];
    final query = await firebaseFirestore
        .collection('employees')
        .doc(auth.currentUser!.uid)
        .collection('employeeList')
        .doc(id)
        .collection('checkInOutList')
        .get();

    for (final employee in query.docs) {
      final employeeCheckInOutModel = CheckInOutModel.fromDocumentSnapshot(
        documentSnapshot: employee,
      );
      employeesCheckInOutList.add(employeeCheckInOutModel);
    }

    return employeesCheckInOutList;
  }


text:
Q: Passing character as variable name in R I am trying to solve an implicit equation in R using multiroot function from package rootSolve.
I am reading the implicit equation from a text file using parse. Also, the variable to be solved for is read from a text file as a character.
For using multiroot,
multiroot(function, initial_guess, ....))

we have to generate a function from the read equation. I did this by
fun <- function(op) {fun <- eval(expr.im)}
op = as.name(opim.names)

where expr.im is the read implicit equation as an expression from the text file, and opim.names is the variable to be solved for, as character.
But the problem arises when I pass the variable op to be solved as a symbol to the function. It gives an error saying that the object

"variable to be solved for" not found.

I think that the variable symbol is not being passed correctly in the function.
Please tell me how to do it correctly.
Since a lot of stuff is going on in my code, I cannot post the whole thing here.
Let me just state a small example for it.
var.name = "x1" # This is what I read from the text file #
var.sym = as.name(var.name)

func <- function(var.sym){
func = x1^2      # the expression x1^2 is also read from a text file  #
}                  # I am trying to solve the implicit equation x1^2 = 0  #
initial_guess = 1
root = multiroot(f=func, start = initial_guess)

As requested by nicola here's what I want -
I have a text file giving me the name of the variable and its initial guess.
I read the variable name (say "x") and the initial guess value (say 1) into variables var (character) and guess(numeric).
I also have another text file containing the following equation -
x^3-1

I read this as an expression in the variable expr.
I want to find the solution to the implicit equation expr.
(The text files can have different names of variables and correspondingly an implicit expression in another file)
As you know, for using the multiroot function, we need to have a function.
The problem is I am not able to pass the variable name stored in var to the function.
Any further clarification will be given if asked.

A: Not able to understand the description fully. But to answer the heading, you can try this procedure-
a = "random_string"
b = "a"
eval(parse(text = b))
[1] "random_string"

A: You can build your function in the following way.
#input: function expression, variable names and initial guess
expr<-"x^3-1"
var.name<-"x"
initial.guess<-2
#we build an "empty" function
func<-function() {}
#now we set the formal arguments and the body of the function
formals(func)<-eval(parse(text=paste0("alist(",paste(var.name,collapse="=,"),"=)")))
body(func)<-parse(text=expr)
#we can see that func is correctly defined
func
#function (x)
#x^3 - 1
#now we can call multiroot
multiroot(func,initial.guess)
#$root
#[1] 1
#$f.root
#[1] 3.733019e-08
#$iter
#[1] 6
#$estim.precis
#[1] 3.733019e-08

You need a little more care if you are dealing with function of more than one variable. See ?multiroot to check how to pass the arguments. Basically you have to pass just one argument which is a vector of all the function arguments. It shouldn't be difficult if you take some time to see how I managed to build func. If you are exclusively dealing with one variable function, you should use the base uniroot function.


text:
Q: When I try to expose Vue type according official website, I still get error

// shims-vue.d.ts
declare module 'vue/types/vue' {
  interface Vue {
    // ...
    // 以下是在main.ts中挂载到Vue.prototype上的变量
    $someFn: () => void;
  }
}

// About.vue
<template>

This is an about page

</template>

12:10 Property '$someFn' does not exist on type 'About'.
    10 | export default class About extends Vue {
    11 |   public created(): void {
  > 12 |     this.$someFn();
       |          ^
    13 |   }
    14 | }
    15 | </script>

https://cn.vuejs.org/v2/guide/typescript.html#%E5%A2%9E%E5%BC%BA%E7%B1%BB%E5%9E%8B%E4%BB%A5%E9%85%8D%E5%90%88%E6%8F%92%E4%BB%B6%E4%BD%BF%E7%94%A8


text:
Q: Solving $\lim\limits_{n\to\infty} \frac{\cot{\frac{2}{n}}+n\csc{\frac{3}{n^3}}}{\csc{\frac{3}{n}} + n\cot{\frac{2}{n^2}}}$ How to get from
$$\lim_{n\to\infty} \frac{\cot{\frac{2}{n}}+n\csc{\frac{3}{n^3}}}{\csc{\frac{3}{n}} + n\cot{\frac{2}{n^2}}} = \lim_{n\to\infty} \frac{\frac{\frac{2}{n}}{\tan{\frac{2}{n}}}\cdot\frac{1}{2n^2}+\frac{\frac{3}{n^2}}{\sin{\frac{3}{n^2}}}\cdot\frac{1}{3}}{\frac{\frac{3}{n}}{\sin{\frac{3}{n}}}\cdot \frac{1}{3n^2}+\frac{\frac{2}{n^2}}{\tan{\frac{2}{n^2}}}\cdot\frac{1}{2}}=...=\frac{2}{3}$$
? It doesn't appear like l'Hôpital's Rule was applied here?

A: Here is how I'd do with maybe more of an intuitive approach (all of this can be made more rigorous using taylor expansion for example)
$\sin(x)$ goes like $x$ in the neighborhood of the origin,
using that you have (for example):
$\csc(3/n^3)$ behaves like $n^3/3$ for very large $n$
Similarly, $\cos(x)$ can be approximated by $1$ around the origin thus $\cot(1/x)$ goes like $1/(1/x)$ with very large $x$ (ie. goes like $x$).
using that kind of approach, it is rather straightforward to obtain the solution. Hope this helps.
EDIT: hm, I did it for fun on the side and you might have forgotten something as, if I'm not mistaken, the limit does not converge. (Leading term in the numerator goes like $n^4$ and leading term in the denominator goes like $n^3$, to be more precise the leading term of the expansion at infinity is $\frac23 n$). you might want to check your equation but it doesn't change that you can still use that kind of approach for trigonometric functions.

A: I think you have to check your question because i don't think answer is $\frac{2}{3}$. But i am given a solution of that question which you are write here.
We know that $\displaystyle \lim_{x\to 0}\frac{x}{\sin x}=1$ and $\displaystyle \lim_{x\to 0}\frac{x}{\tan x}=1$.
$\displaystyle \lim_{n\to\infty}\frac{\cot \frac{2}{n}+n\csc \frac{3}{n^{3}}}{\csc \frac{3}{n}+n\cot \frac{2}{n^{2}}}$
$=\displaystyle \lim_{n\to\infty}\frac{\frac{1}{\tan \frac{2}{n}}+n\frac{1}{\sin \frac{3}{n^3}}}{\frac{1}{\sin \frac{3}{n}}+n\frac{1}{\tan\frac{2}{n^2}}}$
$=\displaystyle \lim_{n\to\infty}\frac{\frac{\frac{2}{n}}{\tan \frac{2}{n}}.\frac{n}{2}+n\frac{\frac{3}{n^3}}{\sin \frac{3}{n^3}}.\frac{n^3}{3}}{\frac{\frac{3}{n}}{\sin \frac{3}{n}}.\frac{n}{3}+n\frac{\frac{2}{n^2}}{\tan\frac{2}{n^2}}.\frac{n^2}{2}}$
$=\displaystyle \lim_{n\to\infty}\frac{\frac{n}{2}+n.\frac{n^3}{3}}{\frac{n}{3}+n.\frac{n^2}{2}}$
$=\displaystyle \lim_{n\to\infty}\frac{3n+2n^{4}}{2n+3n^3}$
$=\displaystyle\lim_{n\to\infty}\frac{\frac{3}{n^3}+2}{\frac{2}{n^3}+\frac{3}{n}}$
$=2.$

A: $$\Large{\lim\limits_{n\to\infty} \frac{\cot{\frac{2}{n}}+n\csc{\frac{3}{n^3}}}{\csc{\frac{3}{n}} + n\cot{\frac{2}{n^2}}} = 2}$$
There should be a typo in the book. ( the second term in the bottom should have $n^3$ )
$$\Large{\lim\limits_{n\to\infty} \frac{\cot{\frac{2}{n}}+n\csc{\frac{3}{n^3}}}{\csc{\frac{3}{n}} + n\cot{\frac{2}{n^3}}} = \frac{2}{3}}$$


text:
Q: Western digital caviar green and raid I would like to use the low cost Caviar Green (Western Digital WD20EADS 2TB or WD10EADS 1TB) hard drives in a raid hardware for a not mission critical purpose: is anyone aware about problems due to the rotation scaling (5400 - 7200) typical for these hard drives?
thank you

A: The only problem we've had with them at work (we don't have many, but a few) is that they're pretty darned slow.  If you need a lot of storage, but not a lot of IOPS, then they seem to be a pretty decent way to go.

A: I've been running the 4x WD10EADS on 3Ware 9650se SATAII RAID without any issues. While I'm aware of the scaling issue, I don't think it's a problem for hardware RAID controllers in general.

A: I've ran the greenpower drives in a RAID configuration for a couple of years now in three different setups: connected to motherboard for software RAID, connected to a RAID card, inside of a Drobo.  Performance was always the best on the RAID card because it never let the drives go to sleep, so there wasn't a delay while the drives woke up.  However, because of this it always meant that power savings came only from lower rotational speeds and not their ability to sleep.  Directly to the motherboard worked pretty well, but the spin up times were annoying.  I was using the drives to record hdtv and I'd tend to lose the first few seconds while the drives woke up.  Finally, I got a Drobo and put the drives in there.  Spin up times are really annoying now, but I've stopped using them for primary storage.  I just migrate data there as long term storage.
So, no problems with rotational speeds.  It seemed that my rather cheap (~$200) RAID card handled it with no problem.  But just be aware that you're not going to get the same power savings you'd get on a desktop machine if you've get them connected to a dedicated card.


text:
Q: Snippet expansion without pressing Tab or similar completion/expansion/trigger keys I have been using Vim with VimTeX and Ultisnips plugins as my LaTeX front end and I would now like to try VSCode and LaTeX-Workshop extension out.
Is the equivalent of the following possible via VSCode snippets?
snippet mm "Inline Math" wA
\\( $1 \\) $0
endsnippet

This snippet has option wA and the functionality here is that if the user types mm in any line (the wA option stands for the beginning of a new word and the expansion is automatic with no need to press a snippet trigger/expansion/completion (e.g., Tab) key.  Within a line, this provides the \( | \) inline math environment.
My initial thought was to have the following in latex.json snippets file:
"mm": {
        "prefix": "mm",
        "body": [
            "\( $1 \)"
        ],
        "description": "inline math"
}

but this needs the snippet expansion/completion/trigger key which is the Tab key pressed after mm
I think this is not possible -- every snippet expansion seems to require the snippet trigger/expansion/completion key. I would like to confirm that it is indeed possible/not possible within VSCode.
The use case is that pressing mm is a lot easier since the keys are close to the home row rather than pressing any other snippet trigger/expansion/completion key.

ETA: I got confirmation that this is currently not possible in VSCode. See here
20 upvotes on VSCode Github page is likely to get work started for eventual completion in several years.


text:
Q: Compiling a batch file into a exe I have a simple launcher for my program:
@echo off
del /s /f /q "Log.txt"
for /f "delims=" %%x in (lic.dll) do set "lic=%%x"
if %lic%==1 goto full
if %lic%==0 goto normal
goto fail
:full
start m1.hta
rem Hideself
goto fail
:normal
start m2.hta
rem Hideself
goto fail
:fail
goto :eof

When i virus scan it i get this: https://www.virustotal.com/en/file/4091db406700b751ab4b01df901a4992226235abc16b87adb047911e0e256b08/analysis/1398529283/
Saying that the file is clean. My problem arises when i compile it in to a exe.
If i use advanced bat to exe converter To convert it i get this:https://www.virustotal.com/en/file/ab3bac03bcdd6aa1305764a1f64e77e651522246c2d7abbd1da427d76604ec2e/analysis/
This is the same batch file just compiled and it coming up as a virus is a real problem. So i decided to search for a different bat to exe program. I got similar results.
My question is: Can any one ether help me find a solution or a alternative piece of software i can use. It must be able to compile the above code in to a exe with a virus detection of less than 4. Also it must be secure (cant be revers engendered easily or unzipped). This is a problem that has been on going and may stop the release of the program so whoever manages to help i will also award 50 rep as an extra bounty.

A: Using autoit Fileinstall function i get a 5/51
https://www.virustotal.com/pt/file/b3241a6458469908db157a211fcff66c240f4872bd0feaaea15dce5dff98632f/analysis/1398538044/
Here is the code i tried :
FileInstall("C:\PROGRAMMATION\test.bat",@ScriptDir&"\test.bat")
RunWait(@ComSpec & " /c " & "test.bat")
FileDelete(@scriptdir&"\test.bat")

This code was compilated as stephen.exe.

A: Any bat-to-exe compiler can be bypassed and the code viewed, as they all extract the code to a temporary file and this can be tracked down.
You could install the trial version of PureBasic/another BASIC dialect and write the code in basic and then compile it for real.

A: VBScript to exe is easy and requires no software other than what you've already got. http://social.msdn.microsoft.com/Forums/en-US/adcae113-4758-481a-a367-60d5d14d97d6/this-is-how-to-turn-vbs-and-js-files-into-exe-files-from-the-command-line-without-third-party-tools?forum=scripting
Unlike VBScript, batch files are run by an exe. The above techniques won't work.
Putting command prompt commands into brackets gives you almost batch functionally. EG
echo off
echo Hello

becomes
(echo off
echo hello)

You could paste/send keys (both vbscript)/send message (vb.net) this to a hidden command prompt. This is how to start a hidden command prompt in vbscript.
CreateObject("Wscript.Shell").Run "cmd /k", 0, False

Whether you use a temporary file or send the commands some other way you can use iexpress to make your exe. Type in Start - Run
iexpress

EG for your launcher bat you could (note 1 means normal and 0 hidden)
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile("lic.dll", 8, true)
If ts.readline = 0 then
    CreateObject("Wscript.Shell").Run "cmd /k hta1.hta", 1, False
Else
    CreateObject("Wscript.Shell").Run "cmd /k hta2.hta", 1, False
End if


text:
Q: Iterate sub object in union type - typescript I have a union type with a sub object containing different properties. Is there a way to accept this union in a function and iterate over it's sub object's keys in a typescript safe way?
// TYPES

type A = {
    bools: {
        a: boolean;
        b: boolean;
    };
};

type B = {
    bools: {
        b: boolean;
        c: boolean;
    };
};

type U = A | B;

// ATTEMPTED TYPING

type GetKeyGroups<T> = T extends T ? Array<keyof T> : never;
type keygroups = GetKeyGroups<U['bools']>

// WANTED USE

const a: A = {
    bools: {
        a: false,
        b: false,
    },
};

const test = ( obj: U ) => {
    const bools: U["bools"] = obj.bools
    const keys = Object.keys(bools) as keygroups

    keys.forEach((key) => console.log(bools[ key ]));
}

test(a)

This ^ seemed like a good solution until typescript complained that key was of type any in keys.forEach((key) => console.log(bools[ key ]));
Is there any way to accomplish this in the current version of TypeScript?

A: Sure. Something like this should work
const test = ( obj: U ) => {
    const bools: U["bools"] = obj.bools
    const keys = Object.keys(bools) as (keyof typeof bools)[]

    keys.forEach((key) => console.log(bools[key]));
}


text:
Q: what are benefits of meteor's phonegap wrapper vs a native app with a webview? Building with phonegap can be a flaky furstrating process. What are the actual benefits of using phonegap layers vs. just a plain native app which opens a webview?
I understand MDG's cordova build added some caching on parts of the app JS code but since a new meteor release updates the whole single JS file each time, this wouldn't be much of a benefit. Maybe some image caching? Does the local webserver do anything?
If you are using native APIs from JS then the cordova bridge is of some use.
But by using a plain native app, you get access to all the build stability, and it's fairly trivial to just open a webview. A JS bridge opens access to any native APIs fairly easily too.
There are various phonegap plugins, but most of these are wrappers around native SDKs anyway, introducing nothing more than leaky problems (eg getting facebook login to work with phonegap and then meteor)
I've built a native android wrapper which is ~1MB, uses latest chrome webview, and can be extended with any native features easily.
I'd like to know more what the benefits of using phonegap are, especially since MDG put time into it.
update: meteor forums discussion
https://forums.meteor.com/t/cordova-benefits-vs-custom-native-wrapper/5356

A: Meteor uses Cordova for its wrapper amid a few amendments:

*

*A web server so your app is accessed from http://meteor.local instead of file://www/...

*An autoupdater that updates the files from the server via a hot code push.

*A few modifications to allow the login with facebook/twitter/google to popup a UIWebView to log in as a better UI alternative to opening the browser. This used to be really bad issue.

The web server allows you to use typical iron routing for your app. You can route to /, /page/:id instead of index.html. This makes it significantly easier to develop "hybrid apps" & to use URI schemes locally.
There are also a few modifications set to use app-config.js to generate a config.xml.
So in addition to these for the phonegap wrapper itself you get the typical Meteor style app where you can use Meteor code and packages, such as HTTP.
Apart from this the functionality is nearly the same as with cordova. You can add cordova packages into your meteor app using meteor add cordova:<cordova package>@<package_version>
There are also a few interesting developments such as the ability to use WKWebView on iOS which is not currently possible on cordova due to the reliance on file:// urls. WKWebView uses significantly less resources over a UIWebView and gives out more performance. Quite useful on a mobile device.


text:
Q: Bootstrap wrong alignment of items I'm new to bootstrap, I use col-md-* grid system to make a list of items. Each item is something like the picture below

The source code in JSFiddle.
The problem is when I decrease the size of the browser windows, the red rectangle goes in the wrong place. How can I fix it?

A: If you want something to be the right but not all the way to the right you should use the bootstrap grid off-sets.
Second
Take a look at this grid example and see what resizes at smaller windows to full-width.
also the the responsiveness of bootstrap at certain widths makes col-md-6 100%
it seems like you will need to  col-xs-6 instead.
I have updated the fiddle here
http://jsfiddle.net/ZTgGX/2/


text:
Q: What is the copy constructor bug causing parsing errors? I'm writing a compiler for a small language, and my Parser class is currently in charge of building an AST for use later. However, recursive expressions are not working correctly because the vector in each AST node that holds child nodes are not working correctly. Currently my AST's header file looks like this:
class AST
{
public:
    enum ASTtype {nil, fdecl, pdecl, vdecl, rd, wr, set, rdLV, setLV, exprLV, add, sub, mul, fcall,
        divide, mod, lt, gt, lte, gte, eq, ne, aAnd, aOr, aNot, aNeg, nConst, t, f, vs, dl, loop,
        cond, ss};
    enum scalarType {tNA, tINVALID, tINT, tLONG, tBOOL};
    AST ();
    AST (AST const&);
    AST (ASTtype);
    AST (ASTtype, std::string);
    void addChild(AST);
    ASTtype getNodeType();
    std::string text;
    ASTtype nodeType;
    int size;
    scalarType evalType;
    std::vector<AST> children;
};

Here's the expression parsing code that is causing trouble:
void Parser::e(AST& parent)
{
    AST expr;
    AST::ASTtype check = AST::nil;
    bool binOp = false;

    switch (lookahead.type)
    {
        case Lexer::AND    : check = AST::aAnd  ; binOp = true; break;
        case Lexer::OR     : check = AST::aOr   ; binOp = true; break;
        case Lexer::NOT    : check = AST::aNot  ; break;
        case Lexer::NEG    : check = AST::aNeg  ; break;
        case Lexer::PLUS   : check = AST::add   ; binOp = true; break;
        case Lexer::MINUS  : check = AST::sub   ; binOp = true; break;
        case Lexer::SPLAT  : check = AST::mul   ; binOp = true; break;
        case Lexer::FSLASH : check = AST::divide; binOp = true; break;
        case Lexer::MOD    : check = AST::mod   ; binOp = true; break;
        case Lexer::EQ     : check = AST::eq    ; binOp = true; break;
        case Lexer::LT     : check = AST::lt    ; binOp = true; break;
        case Lexer::GT     : check = AST::gt    ; binOp = true; break;
        case Lexer::GTE    : check = AST::gte   ; binOp = true; break;
        case Lexer::LTE    : check = AST::lte   ; binOp = true; break;
        case Lexer::NE     : check = AST::ne    ; binOp = true; break;
    }
    if (check != AST::nil && binOp)
    {
        match(lookahead.type);
        expr = AST(check);
        e(expr);
        e(expr);
    } else if (check != AST::nil && !binOp) {
        match(lookahead.type);
        expr = AST(check);
    } else if (lookahead.type == Lexer::IDENT) {

        if (symbols.resolve(lookahead.text).sym_type == symbol::FUNC)
        {
            expr = AST(AST::fcall, lookahead.text);
            match(Lexer::IDENT);
            while (lookahead.type != Lexer::BANG)
            {
                e(expr);
            }
            match(Lexer::BANG);
        } else {
            expr = AST(AST::exprLV);
            lv(expr);
        }
    } else if (lookahead.type == Lexer::T) {
        match(Lexer::T); //true
        expr = AST(AST::t);
    } else if (lookahead.type == Lexer::F) {
        match(Lexer::F); //false
        expr = AST(AST::f);
    } else {
        expr = AST(AST::nConst, lookahead.text);
        match(Lexer::NUM);
    }
    parent.children.push_back(expr);
}

An example expression that doesn't work is + 1 + 2 + 3 4.
It should parse into an AST like this: + [1, + [2, + [3, 4]],
but instead I get this: + [1, + []]
Any advice on what I'm doing wrong?

A: parent.children.push_back(expr) copies the expression. Hence, it calls AST::AST(AST const&). A bug in that could certainly cause the problem you see. However, without the code, we can't find bugs in it.


text:
Q: Android - Sending/Receiving POJOs across Applications via Broadcast Receiver I am doing two Android Applications.

*

*Application 1 sends a Broadcast which has an "Extra" Custom POJO placed into it.

*Application 2 receives the Broadcast and gets the "Extra"(Custom POJO) and displays it.

Here is my Custom POJO in that implements Parcelable
 package com.steven.app1;

 public class Customer implements Parcelable {

    private int id;
    private String firstName;
    private String lastName;

    public static final Parcelable.Creator<Customer> CREATOR = new Parcelable.Creator<Customer>() {
        public Customer createFromParcel(Parcel in) {
            return new Customer(in);
        }

        public Customer[] newArray(int size) {
            return new Customer[size];
        }
    };

    public Customer(int id, String firstName, String lastName) {
        super();
        this.id = id;
        this.firstName = firstName;
        this.lastName = lastName;
    }

    public Customer(Parcel source) {
        id = source.readInt();
        firstName = source.readString();
        lastName = source.readString();
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeInt(id);
        dest.writeString(firstName);
        dest.writeString(lastName);
    }
}

Application 1 then broadcasts like this
Intent i = new Intent("com.steven.app1.RECEIVE_CUSTOMER");
i.putExtra("customer", customer);
sendBroadcast(i);

In Application 2, I would receive the broadcast of Application 1 like this
package com.steven.app2;

public class CustomerBroadcastReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
            Bundle data = intent.getExtras();
            Customer customer = (Customer) data.getParcelable("customer");
        }
    }

}

I get an error in the line
Customer customer = (Customer) data.getParcelable("customer");

because Application 2 does not have a Customer class
So I copied the Customer class of Application 1 and pasted it in Application 2 sources to remove the error. But after running the Application 2, shows up this error.

"Class not found when unmarshalling:com.steven.app1.Customer"

So how would I get the Customer class in Application 1 and use it in Application 2?
Any help or suggestions would greatly be appreciated. Thank you very much.

A: Take Customer class and place it in a library project that can be referenced by the 2 app projects. Then, to make it easier you can implement the Serializable interface in the Customer class. Something like:
public class Customer implements Serializable{

/**
 * Auto generated
 */
private static final long serialVersionUID = -559996182231809327L;
private int id;
private String firstName;
private String lastName;
public Customer(int id, String firstName, String lastName) {
    super();
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
}
// Add getters/setters here
}

Which is gonna be a much more simple and clean solution.
Your onReceive(..) method should look like:
@Override
public void onReceive(Context context, Intent intent) {
        Bundle data = intent.getExtras();
        Customer customer = (Customer) data.getSerializable("customer");
    }
}

To pass the data, pass it as a serializable extra and you should be good to go.
Hope it helps.


text:
Q: Предварительно объявление структуры Есть две структуры, реализующие геометрические понятия точки и вектора. Для инициализации вектора требуется две точки. Аналогично присутствует операция сложения точки и вектора через перегрузку оператора +. Компилятор ругается на отсутствие структуры Vector в перегрузке, что понятно, т.к. она реализована после. Каким образом предварительно объявить структуру Vector. (struct Vector;) не работает. Или тут ошибка самой логики объявления.
struct Vector;

struct Point
{

    int X;
    int Y;

    [***]

    Point operator + (const Vector& ab)
    {
        this->X += ab.X;
        this->Y += ab.Y;
        return *this;
    }
};

struct Vector
{
    int X;
    int Y;

    [***]

    Vector(Point& a, Point& b)
    {
        X = b.X - a.X;
        Y = b.Y - a.Y;
    }
};

A: С логикой предварительного объявления все в порядке. Просто определение вашего оператора надо делать там, где определения обоих классов уже полностью известны. Т.е. не внутри первого класса, а снаружи - после обоих определений классов, как inline
inline Point Point::operator + (const Vector& ab)
{
    this->X += ab.X;
    this->Y += ab.Y;
    return *this;
}

Внутри первого класса должно остаться только объявление оператора.
Однако реализовано у вас тут нечто странное. Бинарный оператор +, который вдруг ни с того ни с сего портит (модифицирует) свой первый операнд - это ужасно. Зачем вам понадобился такой странный оператор?

A: Вынесите определение оператора вне класса, после объявлений обоих классов. В классе оставьте только объявление оператора, без тела. Примерно так:
struct Vector;

struct Point
{

    int X;
    int Y;

    [***]

    Point operator + (const Vector& ab);
};

struct Vector
{
    int X;
    int Y;

    [***]

    Vector(Point& a, Point& b)
    {
        X = b.X - a.X;
        Y = b.Y - a.Y;
    }
};

Point Point::operator + (const Vector& ab);
{
    X += ab.X;
    Y += ab.Y;
    return *this;
}

A: Проблема в том, что для того, чтобы разместить какой-то объект в классе, компилятор должен знать его размер. Поэтому вы не можете запихнуть еще не описанный объект в ваш класс - никак... кроме указателя или ссылки. Дело в том, что их размеры всегда одинаковы, независимо от объектов, на какие они указывают. Что же касается указания имени класса, для объявления указателя (или ссылки) на него, то просто пишите
class my_class;

перед классом, в котором будете размещать указатель на my_class.
UPD говоря класс - я имел ввиду понятие в общем, а не конкретно class


text:
Q: ¿Cómo importar con PHP contenido de texto de un  desde otro archivo HTML? Mi pregunta es la siguiente:
Supongamos que tengo un archivo llamado ejemplo1.html. Dentro del archivo tengo esto:

 Aquí tengo el texto que quiero importar.

Ahora supongamos también que tengo otro archivo llamado ejemplo2.php.
¿Cómo podría asignarle a una variable $texto dentro de ejemplo2.php como valor el HTML -o texto- interno que contenga
, teniendo en cuenta que a su vez está dentro de ejemplo1.html?
¡Muchas gracias de antemano!

A: Puedes hacer una función que primero abra y lea el contenido de un fichero, en este caso de "ejemplo1.html", y guarde este contenido en una variable, ahora ya tienes todo el contenido que necesitas (y algo más) como un string, solo necesitas extraer la parte que necesitas y volcarla como resultado de la función en la variable $texto, es decir algo como esto:
    getHtmlContent( $path ) {

       //logic here

       return $str;
    }
    $path  = "ejemplo1.html";
    $texto = getHtmlContent( $path );

o algo más complicado pero que te permita extraer otros contenidos, con un segundo parámetro para indicar los elementos delimitadores del texto a extraer:
getHtmlContent( $path, $delimiters ) {

    //logic here

    return $str;
}

$path  = "ejemplo1.html";
$delimiters = "div#textoejemplo";
$texto = getHtmlContent( $path, $delimiters );

Esta segunda función tendría que extraer un contenido dinámicamente segun lo pasado, aceptando por ejemplo tags HTML sin más, o con una cierta clase, ID, elementos anidados, etc.
Yo te lo pongo como una sencilla manipulación de string, pero si vas a hacer algo complejo, existen librerías para generar y manipular un DOM a partir de documentos HTML.

A: Usar DOM
Para obtener el contenido de una página en una variable, la forma más sencilla es utilizando file_get_contents().
Una vez que se tiene la variable con el texto de una página HTML, la forma de procesarlo es utilizando DOM. Toda la información que necesitás para procesar un X/HTML, ya sea en este caso o cualquier otro, está en http://php.net/manual/en/book.dom.php.

Pasos
Estos son los pasos necesarios para obtener el contenido de un elemento por su ID:

*

*Generar el objeto del documento con DOMDocument antes de empezar.

*Cargar el texto del HTML en el documento con loadHTML().

*Obtener el div por su id llamando a getElementById().

*Extraer el texto del elemento desde la propiedad textContent.

Código demo en phpfiddle.org
<?php

    $url = 'https://pastebin.com/raw/Kp8Wu5QM'; //subí tu ejemplo a pastebin

    //Obtener el texto de la página web
    $html = file_get_contents($url);

    //Generar el DOM
    $doc = new DOMDocument;
    $doc->loadHTML($html, LIBXML_COMPACT | LIBXML_HTML_NOIMPLIED | LIBXML_NONET);

    //Obtener el elemento por el id "textoejemplo"
    $textoejemplo = $doc->getElementById('textoejemplo');

    //Obtener el texto del elemento
    $texto = $textoejemplo->textContent;

    //Imprimir el resultado
    echo "Texto: " . $texto;


text:
Q: scraping article with scrapy but results null I try to scrape all articles in a website to get the full text, date and also title.
I am using xpath to capture the information I need. I try to be very careful in writing the xpath, but when I run my code it results nothing.
The error message:
    result = xpathev(query, namespaces=nsp,
  File "src/lxml/etree.pyx", line 1582, in lxml.etree._Element.xpath
  File "src/lxml/xpath.pxi", line 305, in lxml.etree.XPathElementEvaluator.__call__
  File "src/lxml/xpath.pxi", line 225, in lxml.etree._XPathEvaluatorBase._handle_result
lxml.etree.XPathEvalError: Invalid expression

As what I understand, the message means something wrong with the xpath.
Here is the code I have created:
import scrapy
from scrapy import Request
from scrapy.crawler import CrawlerProcess

class barchart(scrapy.Spider):
    name = 'barchart'
    start_urls = ['https://www.barchart.com/news/commodities/energy']
    custom_settings = {
        'CONCURRENT_REQUESTS_PER_DOMAIN': 1,
        'DOWNLOAD_DELAY': 1,
        'USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36'
    }

    def start_requests(self):
        for url in self.start_urls:
            yield Request(url, callback=self.parse)

    def parse(self, response):
        for link in response.xpath('//*[@class="stories-list"]//*[@class=["story clearfix "]/a/@href'):
            yield response.follow(
                url=link.get(),
                callback=self.parse_item
            )

    def parse_item(self, response):
        yield {
            'date': response.xpath('//*[@class="field__item"]/time/text()').extract(),
            'title': response.xpath('//*[@class="article-header-wrapper"]//h1//text()').get(),
            'text':''.join([x.get().strip() for x in response.xpath('//*[@class="article-content ng-binding ng-scope"]//p//text()')])
        }

if __name__ == '__main__':
    process = CrawlerProcess()
    process.crawl(barchart)
    process.start()

How should I write the xpath in order to capture all the information I need for this web scrapping?
Thank you very much for any help

A: After some minor changes to your initial xpath expression I was able to get the all of the links from the first page okay, However it seems that the inner articles themselves are rendered differently, possibly using angular, so for those I ended up using the scrapy-selenium extension.
With this configuration I was able to get the results.
import scrapy
from scrapy import Request
from scrapy.crawler import CrawlerProcess

from scrapy_selenium import SeleniumRequest

class barchart(scrapy.Spider):
    name = 'barchart'
    start_urls = ['https://www.barchart.com/news/commodities/energy']
    custom_settings = {
        'CONCURRENT_REQUESTS_PER_DOMAIN': 1,
        'DOWNLOAD_DELAY': 10,
        'USER_AGENT': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
        'SELENIUM_DRIVER_NAME' : "chrome",
        'SELENIUM_DRIVER_EXECUTABLE_PATH' : "chromedriver.exe",
        'SELENIUM_DRIVER_ARGUMENTS' : [],
        "DOWNLOADER_MIDDLEWARES" : {
            'scrapy_selenium.SeleniumMiddleware': 800
        }
    }

    def start_requests(self):
        for url in self.start_urls:
            yield Request(url, callback=self.parse)

    def parse(self, response):
        sections = response.xpath('//div[contains(@class,"story clearfix ")]')
        for section in sections:
            link = section.xpath('.//a[contains(@class,"story-link")]/@href').get()
            yield SeleniumRequest(url=link, callback=self.parse_item, wait_time=10)

    def parse_item(self, response):
        item = {
            'date': response.xpath('//div[@class="article-meta"]/span[contains(@class,"article-published")]/text()').get().strip(),
            'title': response.xpath('//h1[contains(@class,"article-title")]/text()').get().strip(),
            'text':''.join([x.get().strip() for x in response.xpath('//div[contains(@class,"article-content")]//p/text()')])
        }
        yield item

if __name__ == '__main__':
    process = CrawlerProcess()
    process.crawl(barchart)
    process.start()


text:
Q: Qml Vertical Text Orientation How can I display a text in QML with vertical orientation like below
Text {
    id: name13
    text: qsTr("KITCHEN")
}

A: Set width to 1, and wrapMode to Text.WrapAnywhere. This forces each letter to appear on its own line.
Text {
    text: "KITCHEN"
    anchors.centerIn: parent
    color: "white"
    width: 1
    wrapMode: Text.WrapAnywhere

    // -- additional parameters for prettiness --
    lineHeight: 0.9
    font.pixelSize: 50
    horizontalAlignment: Text.AlignHCenter
}

QMLOnline KDE Demo

A: In the following example, I use Frame to allow you to set the background to grey. I used Column with a Repeater and I break up the "KITCHEN" string with split() and render each character in its own Text component:
import QtQuick 2.15
import QtQuick.Controls 2.15

Frame {
    background: Rectangle { color: "grey" }
    Column {
        Repeater {
            model: "KITCHEN".split("")
            Text {
                anchors.horizontalCenter: parent.horizontalCenter
                text: modelData
                font.pointSize: 24
                color: "white"
            }
        }
    }
}