text:
Q: How to validate a input boxes(present in a Div container) values with new incoming values? I have two Dropdowns with multiple as attribute, if I select first Dropdown then I am appending input type checkbox to second Dropdown with selected row. But If I select first row and deselect once again I am getting duplicate options in second box.
This is my Code Snippets

$('.search-box').on("change", function(e) {

                  var inputVal1 = $(this).val();

 $('#checkboxes input:checked').each(function() {

  $("#txtSelectedVal").val($("#txtSelectedVal").val()+ $(this).attr('value')+ ", ");

                });

                  var inputVal = (inputVal1) == null ? 0 : inputVal1;
                    if (inputVal.length) {

                    $.get("sub_category.php", {term: inputVal}).done(function(data) {

                      var lclObj = JSON.parse(data);

                      // $('#checkboxes').empty();

                       for(var i = 0; i < lclObj.length; i++) {
                        var lclSubCat = lclObj[i].sub_category1;
                          $('#checkboxes').append("<input type='checkbox' id='chkBox' value="+lclSubCat+">"+lclSubCat+"
");

                        }
 $("#checkboxes :checkbox").each(function() {

                              var subCat =
                 $(".txtSelectedValuesSubFromCategory1").html();

                      var array = subCat.split(",");

                        $.each(array,function(i) {

        $("input[type=checkbox[value='"+array[i]+"']").prop('checked',true);

                                });
                            });

                  });
                  }
                });

  Category:*

  <select class="form-control search-box" id="selCategory"
name="selCategory" multiple style="width: 300px;">
    <option>1</option>
    <option>2</option>
    <option>3</option>
  </select>

  Sub Category:

    <select class="form-control">
      <option value="">Select an option</option>
    </select>

I don't want to show duplicate values in second Dropdown.
I don't want to use empty() method  because I want to preserve previously selected check boxes.

A: Here is below a small example of how it could be done.
There are some steps:

*

*Declare an array variable that will updated eahc time a checkbox is clicked (checkedCheckboxes here).

*Executes an AJAX call when the value of the dropdown changes.

*When the AJAX is over, you got the categories. Removes all already existing checkboxes, then creates a new one for each category by looping through them. Do not forget to check if checkedCheckboxes contains the current looped category to recheck it if needed.

*Adds an event listener to these checkboxes that will update checkedCheckboxes.

// Here's the variable that keep the checked checkboxes.
let checkedCheckboxes = [];

$('#multiple').on('change', function() {
  const values = $(this).val();

  // Simulates your AJAX call.
  let categories = [];

  values.forEach((value) => {
    // Avoids to make another loop and to push at each iteration.
    categories = [].concat(categories, getCategories(value));
  });
  // ^^^ Simulating your AJAX call finished.

  // Empties the checkbox container.
  $('#checkboxes').empty();

  // For each got categories...
  categories.forEach((cat) => {
    // Creates a checkbox <input>.
    const checkbox = $('<input>')
        .attr('type', 'checkbox')
        .val(cat);

    // If that category was already checked,
    // then check it again.
    if (checkedCheckboxes.includes(cat)) {
      checkbox.prop('checked', true);
    }

    // On click on a checkbox...
    checkbox.on('change', handleOnClickCheckbox);

    // Appends the checkbox to DOM.
    $('#checkboxes').append(checkbox, cat);
  });
});

// Adds or removes from the concerned variable which checkboxes
// is or isn't checked.
function handleOnClickCheckbox() {
  const value = $(this).val(),
    isChecked = $(this).is(':checked');

  // Keep in memory that that checkbox was checked.
  if (isChecked && !checkedCheckboxes.includes(value)) {
    checkedCheckboxes.push(value);
  } // Removes that checkbox if we are unchecking it.
  else if (!isChecked && checkedCheckboxes.includes(value)) {
    checkedCheckboxes.splice(checkedCheckboxes.indexOf(value), 1);
  }
}

// Simulates ajax.
function getCategories(id) {
  const cats = {
    '1': ['1-A', '1-B'],
    '2': ['2-A'],
    '3': ['3-A', '3-B', '3-C']
  };

  return cats[id];
}

<select id="multiple" multiple>
  <option value="1">Cat 1</option>
  <option value="2">Cat 2</option>
  <option value="3">Cat 3</option>
</select>

And here your code snippet following the steps I stated sooner:
// Here's the variable that keep the checked checkboxes.
let checkedCheckboxes = [];

$('.search-box').on('change', function (e) {
    // "VAL = A || B" syntax is the same as:
    // "VAL = (!VAL) ? 0 : VAL"
    const inputVal = $(this).val() || 0;

    if (inputVal.length > 0) {
        $
            .get("sub_category.php", {term: inputVal})
            .done(function (data) {
                const lclObj = JSON.parse(data);

                $('#checkboxes').empty();

                for (let item of lclObj) {
                    const cat = item.sub_category1,
                        jLabel = $(`<label><input type='checkbox' value=${cat}>${cat}</label>`),
                        jCheckbox = jLabel.find('input');

                    // If that category was already checked,
                    // then check it again.
                    if (checkedCheckboxes.includes(cat)) {
                        jCheckbox.prop('checked', true);
                    }

                    // On click on a checkbox...
                    jCheckbox.on('change', handleOnClickCheckbox);

                    // Appends the label (containing the checkbox) to DOM.
                    $('#checkboxes').append(jLabel);
                }
            });
    }
});

// Adds or removes from the concerned variable which checkboxes
// is or isn't checked.
function handleOnClickCheckbox() {
    const value = $(this).val(),
        isChecked = $(this).is(':checked');

    // Keep in memory that that checkbox was checked.
    if (isChecked && !checkedCheckboxes.includes(value)) {
        checkedCheckboxes.push(value);
    } // Removes that checkbox if we are unchecking it.
    else if (!isChecked && checkedCheckboxes.includes(value)) {
        checkedCheckboxes.splice(checkedCheckboxes.indexOf(value), 1);
    }
}


text:
Q: c++ read and write files simultaneously I am trying to read all .png files in a folder then get their gray scale and rewrite them in a new folder (with the same name).
my path_in files : 1.png, 2.png, ... (different number of total files everytime)
so by the end, path_out should contains same numbers of png files, all with the same name as in path_in.
But I am now stuck. As I am new to c++, I could not get myself to get this right.
The error is on the overloads '+' operators.
int main()
{
Mat pic,gray;
vector<cv::String> fn;
glob(path_in + "*.png", fn, false);

vector<Mat> images;
size_t count = fn.size();
for (size_t i = 1; i < count + 1; i++)
{
    pic = imread(path_in + i, CV_LOAD_IMAGE_COLOR);
    cvtColor(pic, gray, CV_BGR2GRAY);

    imwrite(path_out + i + ".png", gray);

}
}

Edited code:
#include "stdafx.h"
#include "iostream"
#include <direct.h>
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"

using namespace cv;
using namespace std;

std::string path_in("C:/Users/t/");
std::string path_out("C:/Users/New folder/");

int main()
{
    _mkdir(path_out.c_str()); //create folder if does not exist

    Mat pic, gray;

    vector<cv::String> fn;
    glob(path_in + "*.png", fn, false);

    //vector<Mat> images;
    size_t count = fn.size();
    for (size_t i = 1; i < count; ++i)
    {
        pic = imread(path_in + fn[i], CV_LOAD_IMAGE_COLOR);
        cvtColor(pic, gray, CV_BGR2GRAY); //error : Unhandled exception

        imwrite(path_out + fn[i] + ".png", gray);
    }

waitKey(0);
return 0;
}

**apologize for not showing the complete code at the beginning, here is the combination code of mine with the suggested answer.
can anyone shed some lights?

A: Assuming path_in and path_out are std::string or cv::String variables, you can't use the + operator to append size_t values as-is to them, you have to convert the integer values to std::string/cv::String values first, eg:
int main()
{
    Mat pic, gray;
    vector<cv::String> fn;
    glob(path_in + "*.png", fn, false);

    size_t count = fn.size();
    for (size_t i = 1; i <= count; ++i)
    {
        pic = imread(path_in + std::to_string(i) + ".png", CV_LOAD_IMAGE_COLOR);
        cvtColor(pic, gray, CV_BGR2GRAY);

        imwrite(path_out + std::to_string(i) + ".png", gray);
    }
    return 0;
}

However, you shouldn't assume the filenames are sequentially numbered. glob() returns a vector of strings, so presumably it returns the actual filenames, so use them as-is instead, eg:
int main()
{
    Mat pic, gray;
    vector<cv::String> fn;
    glob(path_in + "*.png", fn, false);

    size_t count = fn.size();
    for (size_t i = 0; i < count; ++i)
    {
        pic = imread(path_in + fn[i], CV_LOAD_IMAGE_COLOR);
        cvtColor(pic, gray, CV_BGR2GRAY);

        imwrite(path_out + fn[i], gray);
    }
    return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to calculate percentage of features without zero in all columns in R? I have a dataframe with first column as features and other columns with values in the set {0,1,2,-1,-2}.
Here is the dataframe structure.
df <- structure(list(Features = structure(c(1L, 11L, 12L, 13L, 14L,
15L, 16L, 17L, 18L, 2L, 3L, 4L, 5L, 6L, 7L, 8L, 9L, 10L), .Label = c("Var1",
"Var10", "Var11", "Var12", "Var13", "Var14", "Var15", "Var16",
"Var17", "Var18", "Var2", "Var3", "Var4", "Var5", "Var6", "Var7",
"Var8", "Var9"), class = "factor"), Column1 = c(0L, 0L, 0L, 0L,
0L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 0L, -1L, -1L, -1L, 0L, 0L), Column2 = c(0L,
0L, 0L, 1L, 1L, 1L, 1L, 0L, 0L, 0L, 0L, -2L, -2L, -2L, -2L, -2L,
0L, 0L), Column3 = c(0L, 0L, 0L, 0L, 2L, 2L, 2L, 2L, 2L, 2L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L), Column4 = c(0L, 0L, 0L, 2L,
2L, 2L, 2L, 0L, 0L, 0L, 0L, 0L, -2L, -2L, -2L, -2L, 0L, 0L),
    Column5 = c(0L, 0L, 0L, 0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 0L, 0L, 0L, 0L, 0L), Column6 = c(0L, 0L, 0L, 2L, 2L,
    2L, 0L, 0L, -1L, -1L, -1L, -1L, -1L, -1L, 0L, 0L, 0L, 0L),
    Column7 = c(-1L, -1L, 2L, 2L, 2L, 2L, 2L, 2L, -1L, -1L, -1L,
    -1L, -1L, -1L, -1L, -1L, -1L, -1L), Column8 = c(1L, 1L, 1L,
    1L, 0L, 0L, 0L, 0L, 1L, 1L, 1L, 2L, 2L, 2L, 2L, 1L, 1L, 1L
    )), class = "data.frame", row.names = c(NA, -18L))

For each column I wanted to calculate the percentage of features without 0 in the columns.
Any help is appreciated. Many thanks.

A: Maybe something like the following will do what you want.
df[-1] != 0 returns a logical matrix, its colSums are the number of non-zero entries in each column. Divide by the number of rows and multiply by 100 to get the percentage you want.
100*colSums(df[-1] != 0)/nrow(df)
# Column1   Column2   Column3   Column4   Column5
# 44.44444  50.00000  33.33333  44.44444  50.00000
#  Column6   Column7   Column8
# 50.00000 100.00000  77.77778

A: We can just use colMeans on a logical matrix
colMeans(df[-1] != 0)
#    Column1   Column2   Column3   Column4   Column5   Column6   Column7   Column8
# 0.4444444 0.5000000 0.3333333 0.4444444 0.5000000 0.5000000 1.0000000 0.7777778

Or using tidyverse
library(tidyverse)
map_dbl(df[-1], ~ mean(.x != 0))

A: We can use colSums and divide by number of rows in the dataframe
colSums(df[-1] != 0)/nrow(df)

#Column1 Column2 Column3 Column4 Column5 Column6 Column7 Column8
#  0.444   0.500   0.333   0.444   0.500   0.500   1.000   0.778

Or using dplyr
library(dplyr)
df %>%  summarise_at(-1, ~sum(.!= 0)/n())


text:
Q: Rcpp package registering both .C and .Call Symbols: compileAttributes() wrongly exports .C symbol as .Call symbol I am writing an R package mainly in Rcpp (thus using // [[Rcpp::export]] and compileAttributes() to export my functions), but my /src directory also includes a few .c files taken from other packages. Up to this point these were all .Call functions which compileAttributes() faithfully finds and exports, but now I have the issue with a .C function which compileAttributes() unfortunately also exports like the others. In particular my RcppExports.cpp looks like this:
#include <Rcpp.h>
using namespace Rcpp;

... all .cpp functions

RcppExport SEXP pacf1(SEXP, SEXP);
RcppExport void multi_yw(void *, void *, void *, void *, void *, void *, void *, void *, void *, void *); // This is the .C function wrongly exported here.
// ... and some other .c functions

static const R_CallMethodDef CallEntries[] = {
    ... all .cpp functions
    {"multi_yw", (DL_FUNC) &multi_yw, 10}, // This is the .C function wrongly exported here.
    {"pacf1",    (DL_FUNC) &pacf1,     2},
    ... and some other .c functions
    {NULL, NULL, 0}
};

RcppExport void R_init_mypackage(DllInfo *dll) {
    R_registerRoutines(dll, NULL, CallEntries, NULL, NULL);
    R_useDynamicSymbols(dll, FALSE);
}

Instead of the above, I am of course expecting an additional entry like:
static const R_CMethodDef CEntries[]  = {
  {"multi_yw", (DL_FUNC) &multi_yw, 10},
  {NULL, NULL, 0}
};

And then at the end it should be:
RcppExport void R_init_mypackage(DllInfo *dll) {
    R_registerRoutines(dll, CEntries, CallEntries, NULL, NULL);
    R_useDynamicSymbols(dll, FALSE);
}

So what can I do here? I figgurred I could probably remove all the // [[Rcpp::export]] tags and manually set up a RcppExports.cpp, but perhaps there is a solution with compileAttributes()?
Related to this, I also wondered whether I could export the .cpp function symbols with a prefix "CPP_" and the others with "C_" prefix and use .C / .Call them directly in my R code (as I am never directly using an exported .cpp function and thus don't really need the R-function wrapper acound .Call('_mypackage_myfun', ...) generated by compileAttributes(). Thanks for helpful suggestions.

A: Ok, so I found a workaround which allows me to .Call and .C external functions and also to .Call directly customized cpp symbols from R code: The recipe is:
2.) create a header file mysymbols.h, and include in it for every cpp function the line of code starting with "RcppExport" in RcppExports.cpp, i.e. RcppExport SEXP _mypackage_mycppfun(SEXP agr1SEXP, SEXP arg2SEXP, SEXP arg3SEXP); for cpp function mycppfun.
1.) create my_RcppExports.cpp in /src, but leave RcppExports.cpp intact. In that file put #include "mysymbols.h" and #include <Rcpp.h>, using namespace Rcpp;, at the top paste all the C-functions you want to export like RcppExport SEXP mycfun(SEXP, SEXP);. Below paste the static const R_CallMethodDef CallEntries[] = {... block from RcppExports.cpp, in that block you can add the C-functions to be called with .Call, and you can rename the symbols to anything you want. You can now also create a similar static const R_CMethodDef CEntries[]  = {... block listing all the functions to be called with .C. At last, include
RcppExport void R_init_mypackage(DllInfo *dll) {
  R_registerRoutines(dll, CEntries, CallEntries, NULL, NULL);
  R_useDynamicSymbols(dll, FALSE);
}

When you compileAttributes again, the symbol exporting part is gone from RcppExports.cpp.
3.) Create my_RcppExports.R in /R, and paste the content from RcppExports.R, but adjust the symbol names to what you set in my_RcppExports.cpp. This will simply overwrite RcppExports.R every time you load the package. Another options is to do // [[Rcpp::export(.mycppfun)]], so these functions will be hidden (if you are not already adjusting the NAMESPACE file). I see no option to get rid of RcppExports.R alltogether.
I am happy to still get feedback on this solution. Is there a way to get rid of RcppExports.R?


text:
Q: convert base type to derived type Base class is Task.  There are several derived classes such as PhoneCall, Fax, Email....
The framework is .NET 3.5 and the language is C#
In our application, we want to create some automatic tasks based on certain rules for a customer.  For eg. if the customer has been signed up for 30 days, a task will get created by the rules engine.
The owner of the task should then be able to convert this task into a PhoneCall, Fax..... based on the scenario.  Also, another requirement will be to convert a PhoneCall to Fax or Email or vice versa.
1) Should there be a converted class that should facilitate this conversion or each business object should allow methods to perform conversion?
2) If there are any design patterns or guidance someone can provide, that will be great.
Pratik

A: Inheritance is not necessarily the best way to model problems where instances of types can change over time.
You may want to consider using composition instead. Something like:
class Task
{
    private TaskDetail m_Detail;

    public TaskDetail Detail { get { return m_Detail; } }
}

abstract class TaskDetail { ... }

class PhoneCallDetail : TaskDetail { ... }
class FaxDetail : TaskDetail { ... }
class EmailDetail : TaskDetail { ... }

Tasks would not change when their task details shift from one type to another. You would also need to implement some utility code to convert between the different task types, as appropriate.
So example use might look like:
Task theTask = new Task( ... );
theTask.ConvertToEmail(); // internally establishes this as an email task

EmailDetail detail = (EmailDetail)theTask.Detail;
detail.EmailAddress = "wiley.coyote@acme.com";

theTask.ConvertToFax();   // may transfer or lose some detail...
FaxDetail faxDetail = (FaxDetail)theTask.Detail;
faxDetail.FaxDate = DateTime.Now;

// and so on.

The primary disadvantage to the approach above is that consumers of the Task class must use runtime checks to determine the type of detail associated with the task before operating on it; which also then requires casting of the detail property everywhere:
Task someTask = ...;
if( someTask.Detail is EmailDetail )
{
    EmailDetail detail = (EmailDetail)someTask.Detail;
    /* operate on email detail ... */
}
else if( someTask.Detail is FaxDetail )
{
    FaxDetail detail = (FaxDetail)someTask.Detail;
    /* operate on fax detail ... */
}

As the number of different subtypes grows, this approach becomes harder to maintain and evolve. If the number of subtypes is small, and likely to be stable over time, then it may be a reasonable choice.
In general, it's difficult to model situations like these - and you often have to compromise based on what persistence provider you use, how many different detail types they are, and what use cases you intend to support involving conversions from one detail type to another.
Another design approach that is often employed in such cases is Key-Value-Coding. This approch uses a dictionary of keys/values to model the various data elements of different kinds of details. This allows details to be very flexible, at the cost of less compile-time safety. I try to avoid this approach when possible, but sometimes it does model certain problem domains better.
It's actually possible to combine key-value coding with a more strongly typed approach. This allows details to expose their properties (usually for read-only purposes) without requiring the caller to perform runtime checks or casts:
abstract class TaskDetail
{
    public abstract object this[string key] { get; }
}

public class FaxDetail : TaskDetail
{
    public string FaxNumber { get; set; }
    public DateTime DateSent  { get; set; }

    public override object this[string key]
    {
        get
        {
            switch( key )
            {
                case "FaxNumber": return FaxNumber;
                case "DateSent":  return DateSent;
                default:          return null;
            }
        }
    }
}

public class EmailDetail : TaskDetail
{
    public string EmailAddress { get; set; }
    public DateTime DateSent { get; set; }

    public override object this[string key]
    {
       get
       {
           switch( key )
           {
               case "EmailAddress": return EmailAddress;
               case "DateSent":     return DateSent;
               default:             return null;
           }
       }
    }
}

// now we can operate against TaskDetails using a KVC approach:
Task someTask;
object dateSent = someTask.Detail["DateSent"]; // both fax/email have a DateSent
if( dateSent != null )
   // ...

A: 1) to create such tasks you may use factory method
2) I don't think it would be good idea that owner has to convert task to subclasses. may be that Strategy or State petterns would help there.

A: In your particular situation, types aren't the way to go because you have not defined the behavior of a PhoneCall, a Fax or an Email beyond that of Task.
If the only thing you will do is store a phone number in a PhoneCall object, you've already broken encapsulation. The PhoneNumber property should be on the Customer object, as should e-mail address, mailing address, fax number and so on.
You can happily use a TaskType enum as a property of Task up until the point that Task changes its behavior based on the current task type. This is the point you will need to worry about using type conversion the way LBushkin has described.
I can see you in a situation where you are using different presentation logic for each task. In this case you would use the Decorator pattern.


text:
Q: How can I conduct find and replace on columns containing dates with general formatting? I have been trying to replace all "-" to "/" in my excel spreadsheet with VBA but it is not working the way I want it. Please send help :')
Issue: Cells that contain dates in the format of 00-00-0000 are changed to 00.00.0000 instead of the desired 00/00/0000 format. The results are the same even if I do this manually using the Excel find and replace function.
Some information regarding the date cells:

*

*They are in the "general" format and changes to "Date" format (some still remain as general) after the code runs

Code:
Sub FindReplace()

Dim X, Y As Range

Set X = Range("A2").CurrentRegion

  For Each Y In X.Cells
      Y = Replace(Y, "-", "/")
  Next Y

End Sub

Thank you for reading :)

A: With out seeing the data you could try this...
Sub FindReplace()

Dim x, y As Range

Set x = Range("A2").CurrentRegion

  For Each y In x.Cells
      y = format(y,"dd/mm/yyyy")
  Next y

End Sub

A: Assuming your original data are also in the format DD.MM.YYYY, i've written this subroutine:
Sub FindReplace()

    Dim RngRange01 As Range
    Dim RngTarget As Range

    Set RngRange01 = Range("A2").CurrentRegion

    For Each RngTarget In RngRange01
        RngTarget.Value = DateSerial(Right(RngTarget.Value, 4), Mid(RngTarget.Value, 4, 2), Left(RngTarget.Value, 2))
    Next RngTarget

End Sub

I've tested it on a range with dates written with the point instead of the slash and it seems to work for me.
An extra tip: i'd not use a single letter to identify a variable. It is really hard to replace them and to track them. At least 3 letters that you usually do not find in the rest of the code are way better. Something like xyz or sss or qwe. Even better if you add a little tag to remember you what kind of variables they are (like Rng for range or Byt for byte or Dbl for double).


text:
Q: Topos Theory as a link between logic and geometry I was reading about topos theory and in many ways some people said that TT can be used to unify logic and geometry. What does that mean?
I have an OK background in category theory (at least up to adjunction theorems) and topology (general, differential and a little bit of algebraic topology) so feel free to those concepts in your explanation.

A: In topos theory, there is a way to give forcing proofs that use kinds of topologies and sheaves on the topos. So you can create proofs like Cohen's forcing proofs in topos theory, and it follows the pattern of creating sheaves in geometry.
There is a good book, "Sheaves in Geometry and Logic: A First Introduction to Topos Theory" by Mac Lane and Moerdijk which starts from the basics, so it feels fairly complete.
Topos theory also models intuitionist logic - you can have an intuitionist non-Boolean topos, and, again using a kind of "sheaf," form a Boolean topos, so that the Boolean topos is sort of a quotient.


text:
Q: Load vs LDAC pins Alright, so I'm using a TLV5628 Octal 8 bit DAC with my stm32f4-Nucleo and I'm kind of confused about the difference between LDAC and Load. I am also trying to figure out the clock rate and I might just be misreading the data sheet. Thank you!
Link to product page:
http://www.ti.com/product/TLV5628

A: LOAD controls the external serial interface while LDAC controls an internal parallel data register. See the functional block diagram in the data sheet.

A: Use Load with LDAC low to load up data for one DAC and have the level change immediately.
Use Load with LDAC high to load up multiple DACs data, then pulse it low to update all output levels together.


text:
Q: auto suggest data from grid to textboxes..in winforms Auto suggest data from grid to textboxes, in winforms.
SqlCommand cmd = new SqlCommand();
cmd.Connection = cn;
cmd.CommandText = "insert into studetail values('" + textBox1.Text + "','" + textBox2.Text + "','" + gen + "','" + textBox3.Text + "','" + clas + "','" + section + "')";
int n = cmd.ExecuteNonQuery();


text:
Q: Tensorflow autocomplete in pycharm I started to user tensorflow on pycharm and i discovered that there is not auto completion
is it possible to add it

A: i think you might want to use this format to import it:
import tensorflow as tf
....
#usage
tf.keras.callbacks.—
tf.keras.optimizers.—

The above should fix it for you.

A: You can fix it by replacing:
import tensorflow.keras

with:
import tensorflow.python.keras

A: This issue is solved in PyCharm 2021.2.4


text:
Q: AFL-fuzz not finding any crashes I am trying AFL for the first time, and for that reason i found a very simple vulnerable C code that i could use to test AFL.
The C code in questions is
#include <stdio.h>
#include <string.h>

int main(int argc, char * argv[]){
        char name[10];

        if ( argc > 1 ){
                strcpy(name, argv[1]);
                printf("HELLO %s\n", name);
        }

        return 0;
}

I compile that code by running afl-gcc test.c -o test and i tested it just to make sure it crashes when it was suppose to (running ./test $(python3 -c "print('A'*26)") will give a segmentation fault as expected)
The problem here is, i created a testcase echo -en "test\x00" > input/testcase and run AFL afl-fuzz  -i afl_in -o afl_out -- ./test but after a day it still hasn't found any crashes.
I also tried to create a test case that would force it crash python3 -c "print('A'*26)" > input/testcase but it still runs and does not find anything.
This was suppose to be the easiest example so i could get to know AFL a bit better but it is proving to be a challege. Can anyone help?

A: Just as Nick ODell post it in the comments

Seems like AFL expects the program under test to read from STDIN rather than an argument. github.com/google/AFL#6-fuzzing-binaries

Following that URL shows an experimental module that allows for AFL to read from an argument, and for that to work i just had to add 2 lines to my existing code:
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "argv-fuzz-inl.h" // <-- Argv fuzz module

int main(int argc, char * argv[]){
        AFL_INIT_ARGV(); // <-- needed near the very beginning of main().
        char name[10];

        if ( argc > 1 ){
                strcpy(name, argv[1]);
                printf("HELLO %s\n", name);
        }

        return 0;
}

After that i just compiled it again and everything worked as expected.


text:
Q: Is there a way to append incrementally-changing numbers to div class? I have a shop on Shopify, and my theme allows a good amount of customization. However, it uses a "page blocks" structure, and each block has the same wrapping div.

So on a page with 10 sections, they each have the class name. I can easily add a unique identifier to each section type (e.g., "image hero, custom HTML, rich text"), but if I have a page with 10 custom HTML sections, is there a way to dynamically add some kind of auto-generated string to a class so each one would have a different class? Example:

A: You might use the section id:

Documentation:
https://help.shopify.com/en/themes/liquid/objects/section#section-id


text:
Q: Book about missing sister, magical world in a chasm, and griffins I've been desperately searching for a book I read as a child in the early 2000's. I was born in '92 and would've been somewhere between 8 and 12 when I read this book.
I'm a bit fuzzy on details but I strongly believe this book was about these people who lived near a deep chasm in the human world and a young boy's sister goes missing after being seen near it and it's now his duty to find her. He traverses into the chasm and finds himself in a magical world. There's definitely a griffin (or possibly a giant eagle ?) he ends up befriending. This is where things get fuzzy; I'm pretty sure he finds out his sister is dead and he and the griffin make her a grave. I'm pretty sure he ends up entangled in a war of some sort and helps the magical creatures triumph, but I'm not 100% sure on this. I'm pretty sure the griffin/eagle flies him back up the chasm at the end.
It's basically like a fantasy story about this boy coming of age and proving his strength and bravery. It's been driving me nuts for years because I remember so vividly loving this book but I can't remember the name or author or much of the details, what sticks out most in my memory is the chasm and the griffin.

A: It could be The Wayfinder by Darcy Pattison. Description from Goodreads:

Young Winchal Eldras is a Wayfinder, one of the gifted few of G'il Rim
  who have the ability to locate anything: a lost ring, the way home, a
  blue dress in the marketplace, a lost child. "Finding" is a valuable
  talent in this city that sits dangerously close to the Rift, a
  mysterious, unexplored chasm. When the Rift claims his little sister
  in a bizarre accident, though, Win is reduced to a Wayfinder who's
  lost his way. But suddenly there's no time for grief--the plague has
  come to the Heartland. And only healing water from the Well of Life,
  on the other side of the Rift, can stop it. A prophecy commands that
  Win must make the terrible journey to seek the Well. But no one has
  ever braved the dangers of the Rift and returned to tell about it! To
  make matters worse, Win suddenly has a traveling companion in Lady
  Kala, a prized-and royally stubborn--Tazi hound with a few gifts of
  her own. A Wayfinder with no direction can't possibly manage this
  imperious creature from the King's kennels, much less save a
  civilization on the edge of destruction.

Booklist Review:

Winchal Eldras is an apprentice Wayfinder, a member of an elite group
  of people who can locate anything or anyone. When Win's little sister
  slips out of the house one foggy night, he tracks her to the edge of
  the Great Rift, where his fear of heights causes him to freeze, and
  she falls to her death. Bereft, Win retreats into himself. Then a
  prince of the Heartland arrives with news of a rapidly spreading
  plague and taps Win to journey through the Rift to find the Well of
  Life, whose waters are the only cure. With resignation, Win begins the
  arduous trek, joined by Lady Kala, a royal gazehound with her own
  special powers. The pair winds its way past a giant eagle, a deadly
  crocodile, a venomous tatzelwurm, and other dangers.


text:
Q: Multiply Cell range by textbox value input I'm trying to multiply a range of cells by the value of a textbox that the user inputs. My code keeps giving me a Type Mismatch error. How should I change my code?
Sub CommandButton2_Click()
    Dim cell As Range
    For Each cell In Range("F2:F25")
        cell.Formula = TextBox2.Value * Range("E2:E25").Value
    Next cell
End Sub

A: Range("E2:E25").Value is a 2D array.
If you want to successively multiply F2, F3, F4 by E2, E3, E4, then use Offset as you loop:
cell.Value = TextBox2.Value * cell.Offset(,-1).Value


text:
Q: IntelliJ: show decompiled class disassembly even when source is present IntelliJ can display and debug decompiled classes when the sources cannot be found. Is there some way to force the debugger to use disassembly instead of sources even when the sources are found, other than deleting the sources?
This would be useful in a situation where the sources are wrong (do not match the class).

A: This was added in IntelliJ IDEA 2016.1 (see IDEA-144322) and is now available in the View menu next to Show Bytecode as Show Decompiled Class. It is available for library classes only, not for project classes.


text:
Q: NSOpenGLView subclass crash in _enableNeedsDisplayInRectNotifications Updated: the crash doesn't occur on Sierra 10.12.6. But it does occur every time on my High Sierra  10.13.4 machie. So it seems like an AppKit issue introduced sometime in High Sierra. Logged a bug with Apple.

I have created a minimal example here.
My NSWindowController loads it's NSWindow from a .xib file. The window only contains an NSScrollView. In awakeFromNib, I set the scroll view document to an instance of my NSOpenGLView subclass:
- (void)awakeFromNib
{
    sessionView = [[SessionView alloc] initWithFrame:NSMakeRect(0, 0, 1024, 768) pixelFormat:[NSOpenGLView defaultPixelFormat]];
    [self.sessionScrollView setDocumentView:sessionView];
}

The NSOpenGLView subclass can be completely empty implementation, e.g.:
Header
#import <Cocoa/Cocoa.h>
#import <OpenGL/gl.h>

@interface SessionView : NSOpenGLView
{

}

@end

Imlementation
#import "SessionView.h"

@implementation SessionView

@end

Now grab the corner of the window and start resizing. Keep your finger on the mouse button, drag the edge of the window around until it crash.
Watch

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Unbalanced needs display
  in rect posting count.'

(I put the full stack trace at the end of the post, you will see that it is all framework code).
So something is happening in these methods _enableNeedsDisplayInRectNotifications and _enableNeedsDisplayInRectNotifications. Let's override them:
static int count;

- (void)_enableNeedsDisplayInRectNotifications
{
    count--;

    NSLog(@"enable");
    [super _enableNeedsDisplayInRectNotifications];
}

- (void)_disableNeedsDisplayInRectNotifications
{
    count++;

    NSLog(@"disable");
    [super _disableNeedsDisplayInRectNotifications];
}

We can see that while we are resizing the window, _enableNeedsDisplayInRectNotifications is called repeatedly. Once we let go the mouse and end the resize, _disableNeedsDisplayInRectNotifications is called once for every time that _enable... was called.
The problem is, that if we hit a count of -63; we crash.
I can workaround by overriding these methods and not calling super.
What is going on?
Complete stack trace:

0   CoreFoundation                      0x00007fff504d932b
  __exceptionPreprocess + 171 1   libobjc.A.dylib                     0x00007fff77b53c76 objc_exception_throw + 48 2   CoreFoundation
  0x00007fff504df0c2 +[NSException raise:format:arguments:] + 98 3
  Foundation                          0x00007fff525fb340
  -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 193 4
  AppKit                              0x00007fff4e2a9af2
  -[NSView(NSInternal) _disableNeedsDisplayInRectNotifications] + 190 5   test2                               0x000000010949ffb3 -[SessionView
  _disableNeedsDisplayInRectNotifications] + 83 6   AppKit                              0x00007fff4e06876b -[_NSPortalView2 setSourceView:] + 166 7   AppKit
  0x00007fff4e06802a -[NSPortalView dealloc] + 89 8   libobjc.A.dylib
  0x00007fff77b49087 _ZN12_GLOBAL__N_119AutoreleasePoolPage3popEPv + 817
  9   CoreFoundation                      0x00007fff50412a56
  _CFAutoreleasePoolPop + 22 10  Foundation                          0x00007fff525378ad -[NSAutoreleasePool drain] + 144 11  AppKit
  0x00007fff4d9e3990 -[NSApplication run] + 1031 12  AppKit
  0x00007fff4d9b2a72 NSApplicationMain + 804 13  test2
  0x000000010949ffe2 main + 34 14  libdyld.dylib
  0x00007fff7876d015 start + 1 15  ???
  0x0000000000000001 0x0 + 1
Thread 0 Crashed:: Dispatch queue: com.apple.main-thread 0
  libsystem_kernel.dylib            0x00007fff788bdb6e __pthread_kill + 10
  1   libsystem_pthread.dylib           0x00007fff78a88080 pthread_kill +
  333 2   libsystem_c.dylib                 0x00007fff788191ae abort + 127
  3   libc++abi.dylib                   0x00007fff7671df8f abort_message +
  245 4   libc++abi.dylib                   0x00007fff7671e12b
  default_terminate_handler() + 265 5   libobjc.A.dylib
    0x00007fff77b55ea3 _objc_terminate() + 97 6   libc++abi.dylib
    0x00007fff767397c9 std::__terminate(void ()()) + 8 7
  libc++abi.dylib                   0x00007fff7673926f __cxa_throw + 121 8
  libobjc.A.dylib                   0x00007fff77b53da5 objc_exception_throw
  + 351 9   com.apple.CoreFoundation        0x00007fff504df0c2 +[NSException raise:format:arguments:] + 98 10  com.apple.Foundation             0x00007fff525fb340 -[NSAssertionHandler
  handleFailureInMethod:object:file:lineNumber:description:] + 193 11
  com.apple.AppKit                  0x00007fff4e2a9af2 -[NSView(NSInternal)
  _disableNeedsDisplayInRectNotifications] + 190 12  dev.test2                      0x000000010949ffb3 -[SessionView
  _disableNeedsDisplayInRectNotifications] + 83 (SessionView.m:21) 13  com.apple.AppKit                 0x00007fff4e06876b -[_NSPortalView2
  setSourceView:] + 166 14  com.apple.AppKit
    0x00007fff4e06802a -[NSPortalView dealloc] + 89 15  libobjc.A.dylib
    0x00007fff77b49087 (anonymous
  namespace)::AutoreleasePoolPage::pop(void) + 817 16
  com.apple.CoreFoundation          0x00007fff50412a56
  _CFAutoreleasePoolPop + 22 17  com.apple.Foundation           0x00007fff525378ad -[NSAutoreleasePool drain] + 144 18
  com.apple.AppKit                  0x00007fff4d9e3990 -[NSApplication run]
  + 1031 19  com.apple.AppKit               0x00007fff4d9b2a72 NSApplicationMain + 804 20  dev.test2
    0x000000010949ffe2 main + 34 (main.m:4) 21  libdyld.dylib
    0x00007fff7876d015 start + 1


text:
Q: How to create a custom designed admob banner I've been looking into integrating admob banners into my app as iAD has shit down but as of now the banner just look really ugly and offputting.
I saw in other apps that people were using a custom design for their ad banner that works online with their ui design. See the attached images
The images below all have the google admob play logo icon thing which must mean its admob but I've checked the docs and found no way of re-creating this.
My best thought was to pull the ad data from a URL request and populate a class with that data and when the user clicks on it take them to the AppStore but I am not sure that this is allowed in admob iOS natively.
Anybody got ideas on what to do?


text:
Q: Are complete varieties in the sense of Weil the same as proper varieties? This is a continuation of a previous question; I will use the same notation and terminology.
An abstract variety (or Variety, with a big V) in the sense of Weil consists of the following data:

*

*A finite number of varieties, $V_1, \ldots, V_h$, not necessarily all embedded in the same affine space.

*For each $\alpha$ (in $\{ 1, \ldots, h \}$), a non-empty open subset $U_\alpha \subseteq V_\alpha$.

*For each $\alpha, \beta$, a birational correspondence $T_{\beta, \alpha}$ between $V_\alpha$ and $V_\beta$ with the property that if $P_\alpha$ is a point in $U_\alpha$ and $P_\beta$ is a point in $U_\beta$ such that $P_\alpha$ and $P_\beta$ correspond under $T_{\beta, \alpha}$, then $P_\alpha$ is the unique point in $V_\alpha$ corresponding to $P_\beta$ and, vice versa, $P_\beta$ is the unique point in $V_\beta$ corresponding to $P_\alpha$.

*For each $\alpha, \beta, \gamma$, we have $T_{\gamma, \alpha} = T_{\gamma , \beta} \circ T_{\beta, \alpha}$.

The definition of "field of definition" is a bit subtle but also seems irrelevant to the question I have, so I omit it.
The upshot seems to be that Weil's abstract varieties are same thing as separated integral schemes of finite type over $\mathbb{K}$.
(Despite the presence of the affine $V_\alpha$ in the definition, it is the quasi-affine $U_\alpha$ that are being glued together, and the overlaps are given by $T_{\beta, \alpha} \cap (U_\beta \times U_\alpha)$.)
Let $\hat{\mathbb{K}} = \mathbb{K} \amalg \{ \infty \}$.
A generalized quantity is an element of $\hat{\mathbb{K}}$; it is finite if it is a quantity, i.e. an element of $\mathbb{K}$.
A pseudopoint in $n$-space is an element of $\hat{\mathbb{K}}^n$ that is not a point (i.e. at least one coordinate is not finite).
Note that while $\hat{\mathbb{K}}$ may be identified with $\mathbb{P}^1 (\mathbb{K})$, $\hat{\mathbb{K}}^n$ corresponds to $(\mathbb{P}^1)^n (\mathbb{K})$, not $\mathbb{P}^n (\mathbb{K})$!
A reciprocation is a map $\sigma : \hat{\mathbb{K}}^n \to \hat{\mathbb{K}}^n$ whose $i$-th component is either the projection $(x_1, \ldots, x_n) \mapsto x_i$ or its reciprocal $(x_1, \ldots, x_n) \mapsto 1 / x_i$, where as usual we define $1 / 0 = \infty$ and $1 / \infty = 0$.
(We do not define any other arithmetic expressions involving $\infty$.)
Let $P$ and $P'$ be points or pseudopoints in $n$-space and let $k$ be a subfield of $\mathbb{K}$ such that $\mathbb{K}$ has infinite transcendence degree over $k$.
We say $P'$ is a specialisation of $P$ over $k$ if there is a reciprocation $\sigma$ such that $\sigma (P)$ and $\sigma (P')$ are both points and, for every polynomial $F$ in $n$ variables with coefficients in $k$, $F (P) = 0$ implies $F (P') = 0$.
It can be shown that the choice of reciprocation $\sigma$ is irrelevant.
A specialisation is finite if it is a point (i.e. not a pseudopoint).
Now suppose we have an abstract variety as above.
Let $k$ be a field of definition and choose points $M_1, \ldots, M_h$ with the following properties:

*

*For each $\alpha$, $M_\alpha$ is a generic point of $V_\alpha$ over $k$.

*For each $\alpha, \beta$, $M_\alpha$ and $M_\beta$ correspond under $T_{\beta, \alpha}$.

We can consider $(M_1, \ldots, M_h)$ as a point in some affine space (of high dimension).
Weil says that the abstract variety is complete if it has the following property:

*

*For every specialisation $(M'_1, \ldots, M'_h)$ of $(M_1, \ldots, M_h)$, finite or otherwise, there is at least one $\alpha$ such that $M'_\alpha$ is a point in $U_\alpha$.

Question.
Fix an abstract variety / separated integral scheme of finite type over $\mathbb{K}$.
Does completeness in the sense of Weil correspond to properness in the sense of scheme theory?
(Is this a one-way implication?)
A believe a direct translation of Weil's condition is something like this.
Consider the closed subscheme $T \subseteq V_1 \times \cdots \times V_h$ defined by the following formula:
$$T = \bigcap_{\alpha, \beta} \{ (P_1, \ldots, P_h) : (P_\beta, P_\alpha) \in T_{\beta, \alpha} \}$$
Here, we are identifying the birational correspondence $T_{\beta, \alpha}$ with its graph, which is a closed subvariety of $V_\beta \times V_\alpha$.
By definition we have a closed embedding $V_\alpha \hookrightarrow \mathbb{A}^{n_\alpha}_\mathbb{K}$, so these induce a closed embedding $T \hookrightarrow \mathbb{A}^n_\mathbb{K}$, where $n = n_1 + \cdots + n_h$.
On the other hand, $\mathbb{A}^n_\mathbb{K}$ is a dense open subvariety of $(\mathbb{P}^1_\mathbb{K})^n$.
Let $\bar{T}$ be the closure of $T$ in $(\mathbb{P}^1_\mathbb{K})^n$.
I think Weil is asking that every (closed) point of $\bar{T}$ have the property that there is at least one $\alpha$ such that its projection lies in $U_\alpha$.
Notice that $\bar{T}$ is birationally equivalent to the abstract variety in question and is (by construction) a projective variety (since it is a closed subvariety of $(\mathbb{P}^1_\mathbb{K})^n$, which is a projective variety by the Segre embedding).
Weil's condition would give us a surjective rational map from $\bar{T}$ to the abstract variety under discussion, I think.


text:
Q: Finished pods created by Kubernetes CronJob getting deleted after sometime I created a CronJob by using below yaml file.
kind: CronJob
metadata:
  name: $DEPLOY_NAME
spec:
  # Run the job once a day at 8 PM
  schedule: "0 20 * * *"
  # If the previous job is not yet complete during the scheduled time, do not start the next job
  concurrencyPolicy: Forbid
  jobTemplate:
      spec:
        # The pods will be available for 3 days (259200 seconds) so that logs can be checked in case of any failures
        ttlSecondsAfterFinished: 259200
        template:
          spec:
            containers:
            - name: $DEPLOY_NAME
              image: giantswarm/tiny-tools
              imagePullPolicy: IfNotPresent
              resources:
                requests:
                  cpu: "0.01"
                  memory: 256Mi
                limits:
                  cpu: "0.5"
                  memory: 512Mi
              command: ["/bin/sh"]
              args: ["-c", "cd /home/tapi && sh entrypoint.sh"]

As mentioned in ttlSecondsAfterFinished, k8s keeps my job in the cluster. However, the pod created by the job (after completion) gets deleted after sometime.
As per garbage collection policy, my pod object should be dependent upon my job. And since job object is not garbage collected, my pod object should also remain alive. Am i missing something?

A: The .spec.successfulJobsHistoryLimit and .spec.failedJobsHistoryLimit fields are optional.
These fields specify how many completed and failed jobs should be kept.
By default, they are set to 3 and 1 respectively.
You might need to set these fields to appropriate value


text:
Q: bash: "command not found" when calling function defined in ~/.bashrc file in `bash -c` command while opening gnome-terminal tab What I'm trying to do:

*

*Write a script to open 3 tabs.

*cd into a different folder in each tab (ie: run a unique command).

*get each tab to have a unique title

I want this scripted so I can click the script on my Desktop and have it open up terminals as I'd like for my daily development environment.
Description:
I have this script to try and open 3 terminal tabs with unique commands to be run in the tabs:
open_tabs.sh
#!/bin/bash

gnome-terminal --tab -- bash -c "source $HOME/.bashrc && set-title hey; exec bash"
gnome-terminal --tab -- bash -c "cd ~; exec bash"
gnome-terminal --tab

When I run it with ./open_tabs.sh, it opens up 3 new tabs, but unfortunately set-title doesn't work to set the tab title! I get this error in that tab that opens:
bash: set-title: command not found

I have set-title defined as a function in ~/.bashrc like this. Its purpose is to set the title string at the top of any terminal window. It works perfectly when I use it manually. Ex: set-title hey how are you? will put "hey how are you?" at the top of my terminal window.
# From: https://unix.stackexchange.com/questions/177572/how-to-rename-terminal-tab-title-in-gnome-terminal/566383#566383
set-title() {
    # If the length of string stored in variable `PS1_BAK` is zero...
    # - See `man test` to know that `-z` means "the length of STRING is zero"
    if [[ -z "$PS1_BAK" ]]; then
        # Back up your current Bash Prompt String 1 (`PS1`) into a global backup variable `PS1_BAK`
        PS1_BAK=$PS1
    fi

    # Set the title escape sequence string with this format: `\[\e]2;new title\a\]`
    # - See: https://wiki.archlinux.org/index.php/Bash/Prompt_customization#Customizing_the_terminal_window_title
    TITLE="\[\e]2;$@\a\]"
    # Now append the escaped title string to the end of your original `PS1` string (`PS1_BAK`), and set your
    # new `PS1` string to this new value
    PS1=${PS1_BAK}${TITLE}
}

How do I fix this!? I've tried exporting and sourceing and just don't know what I'm doing wrong here.
Related:

*

*Open terminal with multiple tabs and execute application which uniquely modifies PS1 variable for each tab

*https://unix.stackexchange.com/questions/177572/how-to-rename-terminal-tab-title-in-gnome-terminal/566383#566383

*Open Terminal with multiple tabs and execute application <== this is what I'm really trying to solve, but gnome-terminal's --command (-e) option is now deprecated!
# Option "--command" is deprecated and might be removed in a later version of gnome-terminal.
# Use "-- " to terminate the options and put the command line to execute after it.

A: To get bash to read and execute ~/.bashrc on startup, start it as an interactive shell:
gnome-terminal --tab -- bash -ic "set-title hey; exec bash"

Now why didn't your approach of sourcing the file in a non-interactive shell work? I strongly assume your ~/.bashrc begins with something like this:
# If not running interactively, don't do anything
case $- in
    *i*) ;;
      *) return;;
esac

This lets it return without doing anything if the shell where it is sourced doesn't have "i" anywhere in its $-, i.e. it's an interactive shell. $- is a special parameter, man bash says:

- Expands to the current option flags as specified upon invocation, by the set builtin command, or those set by the shell itself (such as the -i option).


text:
Q: confusing intergration given
$$r=4e^{3\theta} \space \space \space \space dr/d\theta=(3*4*e^{3\theta})$$
$$l=\int \sqrt(4e^{3\theta})^{2}+(3*4*e^{3\theta})^{2} \rightarrow $$
why does the integral $$ \int\sqrt(16e^{6\theta}+144e^{6\theta}) \rightarrow \int\sqrt(160e^{6\theta})$$
become $$ 4\sqrt(10) \int\sqrt(e^{6\theta} \rightarrow somehow \rightarrow (4/3) \sqrt(10) (e^{6 \pi}-1)$$
instead of $$ 4\sqrt(10) \int \sqrt(e^{12\theta} \rightarrow U=\sqrt(e^{12})\space ; \space DU=e^{12\theta}*12)$$
$$ \rightarrow(4 \sqrt(10)*[((2/3)e^{12 \theta}]*[e^{12 \theta}*12]\rightarrow
(8/3) \sqrt(10) (e^{12 \theta}*12) du\space went \space away$$
I'm confused about the integration of e after I move the constants to the other side of the integral. I don't have the steps so I can only guess that there was a 1/3 somewhere in the integration of the first equation. this in an equation for length of a polar curve. I have omitted the original function r was equal too.

A: You have not included it from your post, but from your answer I believe that your questions is to evaluate the length of the curve $r = 4e^{3\theta}$ for $0 \leq \theta \leq 2\pi$.
The formula for arc length is:
$$L = \int_a^{b} \sqrt{r^2 + (\frac{dr}{d\theta})^2} \,d\theta$$
Then we have $\frac{dr}{d\theta} = 12e^{3\theta}$, so substituting in we get:
$$L =  \int_0^{2\pi} \sqrt{160e^{6\theta}} \,d\theta = \sqrt{160}\int_0^{2\pi} \sqrt{e^{6\theta}} \,d\theta = \sqrt{160}\int_0^{2\pi} e^{3\theta} \,d\theta$$.
Then using the substitution $u = 3\theta$, we find that
$$L = \sqrt{160}\int_0^{2\pi} e^{3\theta} \,d\theta = \frac{\sqrt{160}}{3}\int_0^{6\pi} e^{u} \,du = \frac{4\sqrt{10}}{3}(e^{6\pi}-1)$$


text:
Q: Option not found at ffmpeg I tried to add watermark to a video using python by call subprocess ffmpeg. My code:
command = "C:\\VidMaker\\source\\ffmpeg.win32.exe -i C:\\VidMaker\\kq"+str(i)+".mp4 -i C:\\VidMaker\\1.png -filter_complex" "[0:v]setsar=sar=1[v];[v][1]blend=all_mode='overlay':all_opacity=0.7" "-vcodec libx264 C:\VidMaker\\Res"+str(i)+".mp4"
subprocess.check_call(command, shell = False)

the result is:
Unrecognized option 'filter_complex[0:v]setsar=sar=1[v];[v][1]blend=all_mode='overlay':all_opacity=0.7-movflags'.
Error splitting the argument list: Option not found
Traceback (most recent call last):
  File "C:\VidMaker\add.py", line 10, in <module>
    subprocess.check_call(command, shell = False)
  File "C:\Python27\lib\subprocess.py", line 186, in check_call
    raise CalledProcessError(retcode, cmd)
subprocess.CalledProcessError: Command 'C:\VidMaker\source\ffmpeg.win32.exe -n -i C:\VidMaker\kq2.mp4 -i C:\VidMaker\1.png -filter_complex[0:v]setsar=sar=1[v];[v][1]blend=all_mode='overlay':all_opacity=0.7-movflags +faststart C:\VidMaker\Res2.mp4' returned non-zero exit status 1
[Finished in 0.4s with exit code 1]

edit1: it run ok without option:
command = "C:\\VidMaker\\source\\ffmpeg.win32.exe -i C:\\VidMaker\\kq"+str(i)+".mp4 -i C:\\VidMaker\\1.png -filter_complex overlay=10:10 C:\VidMaker\\Res"+str(i)+".mp4"

What happen with the option and how can fix it?Thanks!
edit2: i need to call like that because my VPS cannot run like my computer, in my computer it run successfully with:
 subprocess.call(['ffmpeg',
  '-i', 'funvi 155.mp4',
  '-i', '1.png',
  '-filter_complex', "[1:v]format=argb,geq=r='r(X,Y)':a='0.15*alpha(X,Y)'[zork]; [0:v][zork]overlay",
  '-vcodec', 'libx264',
  'myresult6.mp4'])

A: It is concatenating your string literals:
"A" "B"

Becomes "AB", not "A B", no space is added. So either use one single quoted string with spaces between your command line parameters, or find another way to store command line parameters, e.g. in a list, then you can pass that list to subprocess or whatever later when you're ready to run it.
Sorry to be brief, on phone.


text:
Q: CSS Selector cant be applied Hi all could some please tell me where I am going wrong in the following code. I am trying to apply the following css styles to my page as below my issue is getting it to work properly.
I understand #cookieTerms is a selector which stops the elements being mixed up with the sites main style.css elements.
I thought to call these you would wrap your code in the tag

but so far no luck for me. My simple code and output is below. Any help much appreciated guys.

Cookies Policy

Like most websites we use cookies blah blah. Tell me more about cookies.

Close Cookie Message

A: Ids are case-sensitive. You named the id CookieTerms (with uppercase C), but you select the id cookieTerms (with lowercase c).
Change your id (or the selectors...) to:

A: The case on your ID doesn't match the CSS.
It should be (if I understand your problem correctly):

Cookies Policy

Like most websites we use cookies blah blah. Tell me more about cookies.

Close Cookie Message


text:
Q: maximum of the sum of polynomials Hi
I have $n$ polynomials, each one is positive over a certain range and the maximum value each can attain is 1. Also each polynomial has atmost one peak(maximum). Is there some way that I can show that the sum of these polynomials also has one peak atmost. Each polynomial is something like $x^3(1-x)^2$ where $0\leq x\leq 1$.
is this information enough.
thanks


text:
Q: how + adjective + I + be + to-infinitive
1- I can't describe to you how surprised I was to find out I loved her
2- I can't describe to you how suprised I was when I found out I loved her

I just saw the first sentence and it seemed a bit interesting to me. I would use the second one instead. Is this some kind of form that I would see often but wouldn't hear that much?

A: These two sentences are almost identical in meaning. By almost identical I mean it would take additional context to warrant preferring one over the other. The first sentence focuses on the action "find out" itself. The second sentence adds focus on the timing of the action which is useful if the timing matters and is addressed in other statements before or after this one.


text:
Q: How to customize labels in TreePlot? I want to specify the labels attached to vertices in TreePlot, allowing distinct vertices to carry the same label. The following attempt fails:
aTree =   TreeGraph[{1 -> 2, 1 -> 3}, VertexLabels -> {1 -> "a", 2 -> "b", 3 -> "b"}];
TreePlot[aTree, VertexLabeling -> True]

and so does
aTree = TreeGraph[{1 -> 2, 1 -> 3},  VertexLabels -> {1 -> "a", 2 -> "b", 3 -> "b"}];
TreePlot[ Rule @@@ EdgeList[aTree], DirectedEdges -> True,  VertexLabeling -> True]

Any idea?

A: You can specify PlotTheme in TreeGraph
TreeGraph[{1 -> 2, 1 -> 3},
 VertexLabels ->
  Thread[{1, 2, 3} -> (Placed[#, Center] & /@ {"a", "b", "b"})],
 PlotTheme -> "VintageDiagram"]

A: Update 2: Came across a hidden option "VertexNames" for TreePlot
TreePlot[{1 -> 2, 1 -> 3},
  VertexLabeling -> True,
 "VertexNames" -> {"A", "B", "B"}]

This also works for  GraphPlot and LayeredGraphPlot.
Note: In versions 12.0, TreePlot is changed substantially, and the legacy Treeplot is available under the name GraphComputation`TreePlotLegacy.
Update: If you have to use TreePlot you can  post-process the output of TreePlot to relabel the vertices.
The function reLabelF below takes a list of vertices to be relabeled (vertices)  and their new labels(labels) and post-processes a TreePlot output (tp) to get a relabeled TreePlot:
ClearAll[reLabelF]
reLabelF[verts_, labels_][tp_] := tp /. (Framed[#, p__] :> Framed[#2, p] & @@@
    Transpose[{verts, labels}])

Examples:
vertices = {1, 2, 3};
labels =  Style[#, 18, "Panel"] & /@ {"a", "b", "b"};

TreePlot[{1 -> 2, 1 -> 3}, VertexLabeling -> True] // reLabelF[vertices, labels]

Relabel only the vertices {1, 2, 3}:
 TreePlot[{1 -> 2, 1 -> 3, 1 -> 4, 2 -> 5}, VertexLabeling -> True] //
   reLabelF[vertices, labels]

Relabel all vertices:
TreePlot[{1 -> 2, 1 -> 3, 1 -> 4, 2 -> 5}, VertexLabeling -> True] //
 reLabelF[Range[5], Style[#, 18, "Panel"] & /@ {"a", "b", "b", "b", "c"}]

Original answer:
You can specify the labels for each vertex using Property and use the built-in "VintageDiagram" for GraphStyle option setting:
labeledvertices = Property[#, VertexLabels ->
  Placed[Style[#2, 18, "Panel", Background -> Transparent], Center]] & @@@
    Transpose[{{1, 2, 3}, {"a", "b", "b"}}];

TreeGraph[labeledvertices, {1 -> 2, 1 -> 3}, GraphStyle -> "VintageDiagram"]

Alternatively, use a different built-in GraphStyle:
TreeGraph[labeledvertices, {1 -> 2, 1 -> 3},  GraphStyle -> "DiagramGold"]

A: In:
rule = {1 -> "a", 2 -> "b", 3 -> "b"};
shapeRule = Rule[#1, Text[Style[#2, Black, "Text"]]] & @@@ rule;
aTree = TreeGraph[{1 -> 2, 1 -> 3}, VertexShape -> shapeRule,
  VertexSize -> Large]

Out:


text:
Q: C++, считывание из файла Надо считать значения в вектор из файла(кол-во значений в файле не известно)
 for(int i=0;!input.eof();i++){

      input>> a[i];

  }

Я хочу, что бы увеличение параметра i происходило пока не достигнут конец файла. Но видимо я что-то организовал не правильно. Заранее спасибо!
A: #include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>

...
std::vector<int> a;
std::copy(std::istream_iterator<int>(input), std::istream_iterator<int>(),
          std::back_inserter(a));

A: Так:
for (int i = 0; input; i++) {
    input >> a[i];
}

А если количество значений неизвестно, то правильнее было бы:
for (int i = 0; input; i++) {
    int tmp;
    input >> tmp;
    a.push_back(tmp);
}

Если нужно сохранить значение i после цикла, то так:
int i = 0;
for (i = 0; input; i++) {
    int tmp;
    input >> tmp;
    a.push_back(tmp);
}

Не забывайте, что таким образом последнее число считается два раза. Первый вариант:
int i = 0;
for (i = 0; input; i++) {
    int tmp;
    input >> tmp;
    if (input)
        a.push_back(tmp);
    else
        i--;
}

Второй вариант:
int i = 0;
for (i = 0; input; i++) {
    int tmp;
    input >> tmp;
    a.push_back(tmp);
}
i--;
a.pop_back();


text:
Q: How to load images (jpg) in QML generated at runtime my question is quite simple.
I have a Qt application with a Gui developed with QML.
My back-end side generates and saves jpg images in a folder called /images .
I am able to send from C++ to QML the strings holding the name of the images that I want to show. Sadly my QML Image object doesn't display anything.
It seems that if an image can be displayed only if it has been previously declared in the qml.qrc file.
Sadly, again, qrc files do not support wildcards yet!
https://bugreports.qt.io/browse/QTBUG-1400
Is there a workaround?
The name of the images are not fixed, they are generated with certain runtime values i.e. timestamp.
Thank you

A: By default it will search the image source in the qrc file. To make it go to the actual file system, prepend a file:/// to the path.


text:
Q: How to make an overlay on top of JavaFX 2 webview? Is it possible to to overlay any JavaFx2 widgets or canvas on top of a JavaFX 2 webview?
I want to generate a transparent heatmap by means of JavaFX 2 on top of a webview.

A: Adding overlay is very easy: just put webview and any pane to StackPane.
Another story is to synchronize overlay and webview data. To achieve that you need to ask webview for object coordinates through javascript. Here is an example which finds stackoverflow question area and marks it on overlay:

public class WebOverlay extends Application {
    @Override
    public void start(Stage stage) {
        StackPane root = new StackPane();
        WebView webView = new WebView();

        final WebEngine webEngine = webView.getEngine();
        Canvas overlay = new Canvas(600,600);
        overlay.setOpacity(0.5);
        final GraphicsContext gc = overlay.getGraphicsContext2D();
        gc.setFill(Color.RED);

        root.getChildren().addAll(webView, overlay);
        stage.setScene(new Scene(root, 600, 600));

        webEngine.getLoadWorker().workDoneProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue.intValue() == 100) {
                // find coordinates by javascript call
                JSObject bounds = (JSObject)webEngine.executeScript("document.getElementsByClassName('question-hyperlink')[0].getBoundingClientRect()");

                Number right = (Number)bounds.getMember("right");
                Number top = (Number)bounds.getMember("top");
                Number bottom = (Number)bounds.getMember("bottom");
                Number left = (Number)bounds.getMember("left");

                // paint on overlaing canvas
                gc.rect(left.doubleValue(), top.doubleValue(), right.doubleValue(), bottom.doubleValue());
                gc.fill();
            }
        });
        webEngine.load("http://stackoverflow.com/questions/10894903/how-to-make-an-overlay-on-top-of-javafx-2-webview");

        stage.show();
    }

    public static void main(String[] args) { launch(); }
}

A: Do you mean something like this:
import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.scene.shape.RectangleBuilder;
import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.scene.text.TextBuilder;
import javafx.scene.web.WebView;
import javafx.stage.Stage;

public class Demo extends Application {

    @Override
    public void start(Stage primaryStage) {
        WebView webView = new WebView();
        webView.getEngine().load("http://www.google.com");
        StackPane root = new StackPane();
        root.getChildren().addAll(webView, getOverlay());
        primaryStage.setScene(new Scene(root, 300, 250));
        primaryStage.show();
    }

     private Pane getOverlay() {
        StackPane p = new StackPane();
        Rectangle r = RectangleBuilder.create()
                .height(100).width(100)
                .arcHeight(40).arcWidth(40)
                .stroke(Color.RED)
                .fill(Color.web("red", 0.1))
                .build();

        Text txt=TextBuilder.create().text("Overlay")
                .font(Font.font("Arial", FontWeight.BOLD, 18))
                .fill(Color.BLUE)
                .build();
         p.getChildren().addAll(r, txt);
         return p;
    }

     public static void main(String[] args) {
        launch(args);
    }
}


text:
Q: PHP: send html email from microsoft exchange server 2007 I can't send e-mail to outside of my domain using basic php mail function.It shows error when i want to send e-mail to yahoo or gmail or outside of my domain.The error is:Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay in C:\-----\email.php on line 6.My code is below.
 $to = "testabc@gmail.com";
 $subject = "Hi!";
 $body = "Hi,\n\nHow are you?";
 if (mail($to, $subject, $body)) {
   echo("
Message successfully sent!
");
  } else {
   echo("
Message delivery failed...
");
  }

My e-mail server is Microsoft exchange server 2007.
Is their any well stablished php class or code available to send email.
pls help

A: That's a server configuration issue, it doesn't have anything to do with how you send emails. Apparently relaying is not allowed, and thus you are unable to send mails to external email addresses. So either change the "to" address to one that is allowed, use another SMTP server to send the mails or change the configuration of the current one.

A: Did you try using a email library like swift? http://swiftmailer.org/


text:
Q: WPF RotateTransform question on offset In the following:
<Rectangle Height="60" HorizontalAlignment="Left" Margin="50,100,0,0" Name="rectangle2" Stroke="Black" VerticalAlignment="Top" Width="60" >
<Rectangle.RenderTransform>
    <TransformGroup>
        <RotateTransform Angle="45" CenterX="30" CenterY="30"/>
    </TransformGroup>
</Rectangle.RenderTransform>

To rotate the rectangle on its centre I have to set the CenterX and Y to half of the Rectangle's size. Is there a way to do that in markup?
Something like CenterX="{Binding  Path=Width\2}" ?

A: You can set RenderTrasformOrigin property on the Rectangle itself:
<Rectangle Height="60" HorizontalAlignment="Left" Margin="50,100,0,0" Name="rectangle2"
           Stroke="Black" VerticalAlignment="Top" Width="60"
           RenderTrasformOrigin="0.5,0.5">
<Rectangle.RenderTransform>
    <TransformGroup>
        <RotateTransform Angle="45" />
    </TransformGroup>
</Rectangle.RenderTransform>


text:
Q: Visual Studio 'Attach to Unity' button disappeared when I double clicked on editor console debug log line I'm using VS2019 16.10.0 with Unity2020.3.0
Every time I double click on the Console window debug log line, the VS 'Attach to Unity' button will disappear from the toolbar and become a 'Start' button.

I have to click 'Regenerating the project files' to make it back to normal.

How do I fix this?


text:
Q: Is the speed of light the upper bound on CPU speed? Edit: As this my first question in this site I was a bit confused how to pose the question. Because of the way I had put the question before has made it trouble to understand
What is the fastest speed that a CPU can ever reach without breaking the Laws of Physics?
Is it determined by the speed of light only?
Are there any experiments or related articles published that describe how we can overcome limits imposed by the of speed of light or other phenomena? What is the highest clock frequency of a chip designed so far?
What is the max. speed that a CPU ever reached. What was that?

A:
Can the CPU can run faster than the speed of light?

Information cannot travel between parts of a CPU faster than the speed of light. Ref

I have seen a news saying that some quantum action is 10,000 times faster than light

You (originally) linked to a news article which says

Whereas the result may sound like a way to send faster-than-light messages, it isn't


text:
Q: Getting the index of a random item in a list and the index next to it? I'm probably going about this in the wrong way but in this scenario how do I obtain the index of the random item in the list, and how to compare it to the index of the random item +1? i know if it was the last item in the list this would not work, however lets ignore that for now.
import random
class Test:
    def __init__(self):
        self.dataItem = ["item1","item2","item3","item4"]
    def Function1(self):
        self.randomItem = random.choice(self.dataItem)
        #if self.dataItem[self.randomItem] > self.dataItem[self.randomItem +1]:
        return True
v1 = Test()
print(v1.Function1())

A: Instead of using random.choice to get a random list item, you could just use random.randrange to get a random list index.
You could also make sure that way that you get an index before the last element, so there is always a next element you could compare it to:
index = random.randrange(len(self.dataItem) - 1)
if self.dataItem[index] > self.dataItem[index + 1]:
    return True


text:
Q: Not Equal to condition in codeigniter is not working Not equal to condition is not working in my sql query of codeigniter.
I also tried with <> but this also not working please some one help to solve this.
output is displaying with equal to condition
 $result = $this->db->query("select a.user_email  from users as a, result as b where b.exam_id = '".$exam_id."' and a.user_id  != b.user_id  and  a.active =  1 and a.user_role_id != 1 group by a.user_id")
->result();

A: Try to use this as you query is not clearly understandable to the compiler that's why it's giving wrong output.
$query="select a.user_email  "
        . "from users as a, result as b "
        . "where b.exam_id = '".$exam_id."'"
        ."a.active =  1 and"
        . "(a.user_id  != b.user_id)  "
        . "and "
        . "(a.user_role_id != 1 group by a.user_id)"

A: Thanks every1 one for your suggestions. here is the correct query
select * from users
where user_id not in (select user_id from result  where exam_id = '".$exam_id."')  and  active = 1 and user_role_id != 1


text:
Q: Trying to Connect R to Spark using Sparklyr I'm trying to connect R to Spark using Sparklyr.
I followed the tutorial from rstudio blog
I tried installing sparklyr using

*

*install.packages("sparklyr") which went fine but In another post, I saw that there was a bug in sparklyr_0.4 version. So I followed the instruction to download the dev version using

*devtools::install_github("rstudio/sparklyr") which also went fine and now my sparklyr version is sparklyr_0.4.16.
I followed the rstudio tutorial to download and install spark using
spark_install(version = "1.6.2")

When I tried to first connect to spark using
sc <- spark_connect(master = "local")

got the following error.
Created default hadoop bin directory under: C:\Users\rkaku\AppData\Local\rstudio\spark\Cache\spark-1.6.2-bin-hadoop2.6\tmp\hadoop
Error:
To run Spark on Windows you need a copy of Hadoop winutils.exe:
1. Download Hadoop winutils.exe from:
   https://github.com/steveloughran/winutils/raw/master/hadoop-2.6.0/bin/
2. Copy winutils.exe to C:\Users\rkaku\AppData\Local\rstudio\spark\Cache\spark-1.6.2-bin-hadoop2.6\tmp\hadoop\bin
Alternatively, if you are using RStudio you can install the RStudio Preview Release,
which includes an embedded copy of Hadoop winutils.exe:
  https://www.rstudio.com/products/rstudio/download/preview/**

I then downloaded winutils.exe and placed it in C:\Users\rkaku\AppData\Local\rstudio\spark\Cache\spark-1.6.2-bin-hadoop2.6\tmp\hadoop\bin - This was given in instruction.
I tried connecting to spark again.
sc <- spark_connect(master = "local",version = "1.6.2")

but I got the following error
Error in force(code) :
Failed while connecting to sparklyr to port (8880) for sessionid (8982): Gateway in port (8880) did not respond.
Path: C:\Users\rkaku\AppData\Local\rstudio\spark\Cache\spark-1.6.2-bin-hadoop2.6\bin\spark-submit2.cmd
Parameters: --class, sparklyr.Backend, --packages, "com.databricks:spark-csv_2.11:1.3.0", "C:\Users\rkaku\Documents\R\R-3.2.3\library\sparklyr\java\sparklyr-1.6-2.10.jar", 8880, 8982
Traceback:
  shell_connection(master = master, spark_home = spark_home, app_name = app_name, version = version, hadoop_version = hadoop_version, shell_args = shell_args, config = config, service = FALSE, extensions = extensions)
  start_shell(master = master, spark_home = spark_home, spark_version = version, app_name = app_name, config = config, jars = spark_config_value(config, "spark.jars.default", list()), packages = spark_config_value(config, "sparklyr.defaultPackages"), extensions = extensions, environment = environment, shell_args = shell_args, service = service)
  tryCatch({
gatewayInfo <- spark_connect_gateway(gatewayAddress, gatewayPort, sessionId, config = config, isStarting = TRUE)
}, error = function(e) {
abort_shell(paste("Failed while connecting to sparklyr to port (", gatewayPort, ") for sessionid (", sessionId, "): ", e$message, sep = ""), spark_submit_path, shell_args, output_file, error_file)
})
  tryCatchList(expr, classes, parentenv, handlers)
  tryCatchOne(expr, names, parentenv, handlers[[1]])
  value[[3]](cond)
  abort_shell(paste("Failed while connecting to sparklyr to port (", gatewayPort, ") for sessionid (", sessionId, "): ", e$message, sep = ""), spark_submit_path, shell_args, output_file, error_file)

---- Output Log ----
The system cannot find the path specified.

Can somebody please help me to solve this Issue. I'm sitting on this issue from past 2 weeks without much help. Really appreciate anyone who could help me resolve this.

A: I finally figured out the issue and am really happy that could do it all by myself. Obviously with lot of googling.
The issue was with Winutils.exe.
R studio does not give the correct location to place the winutils.exe. Copying from my question - location to paste winutils.exe was C:\Users\rkaku\AppData\Local\rstudio\spark\Cache\spark-1.6.2-bin-hadoop2.6\tmp\hadoop\bin.
But while googling i figured out that there's a log file that will be created in temp folder to check for the issue, which was as below.
java.io.IOException: Could not locate executable C:\Users\rkaku\AppData\Local\rstudio\spark\Cache\spark-1.6.2-bin-hadoop2.6\bin\bin\winutils.exe in the Hadoop binaries
Location given in log file was not same as the location suggested by R Studio :) Finally after inserting winutils.exe in the location referred by spark log file, I was able to successfully connect to Sparklyr ...... wohooooooo!!!! I'll have to say 3 weeks of time was gone in just connecting to Spark, but all worth it :)

A: please mind any proxy
    Sys.getenv("http_proxy")
    Sys.setenv(http_proxy='')

did the trick for me


text:
Q: splitting a column and accessing the resulting list I have a dataframe called standard, with a column named '# genes'. I'd like to split that one and assign elements of the resulting list to a new column. That is, it looks like this:
standard['# genes'].str.split("+")
0     [3798 ,  144 part]
1     [3556 ,  138 part]
2     [3783 ,  135 part]
3     [3974 ,  115 part]
4     [3813 ,  135 part]
5     [3830 ,  141 part]
6     [3944 ,  128 part]
7     [3926 ,  129 part]
8     [3803 ,  126 part]
9     [3838 ,  127 part]
10    [3732 ,  141 part]
Name: # genes, dtype: object

Thus, I'd like to be able to assign 3798, 3556, 3783 and so on to a new column in standard. However, I have not been able to comprehend enough of indexing in pandas to understand how to get to it.

A: Use parameter expand=True to split for convert lists to columns:
df = standard['# genes'].str.split("+", expand=True)

If want add 2 new columns to original DataFrame:
standard[['a','b']] = standard['# genes'].str.split("+", expand=True)


text:
Q: SNMP ping support for IPv6 address Whether "SNMP ping" is supported for IPv6 address ? Also whether latest NET-SNMP library provides support for "SNMP ping" .
RFC 4560 talks about snmp ping but it doesn't mention anything about IPv6 address.
https://www.rfc-editor.org/rfc/rfc4560
Thanks
-Ravi

A: pingCtlTargetAddressType is of type InetAddressType which allows ipv6.


text:
Q: How do I get an Epson SX235W printer working? I have just installed Ubuntu on my laptop. But have a problem getting my Epson SX235W to work. I have installed the printer after finding the driver software, However when I try to print a document the printer just spits out sheet after sheet of blank paper until I switch the printer off. Please help.
Tony

A: Try to go into your printer settings ( System Setting > Printer ), unplug your printer and delete the printer. After, plug your printer back and go into your printer settings again to see if there's your printer. If not, add it with the button and follow the instruction. If you can see your printer in the printer settings, try to print the ubuntu test page ( System setting > Printer > right click printer > properties > print test page)
If it doesn't work, try to look on epson's website.


text:
Q: Fixed div with respect to container NOT body I want to fix position of div with respect to it's container div, NOT with respect to body. I played a lot and searched as well but didn't find the solution.
Please not .container and .content both are of responsive height and can't take a fixed height. height:2000px; given to .container for demontration purposes only.
While the actual case is: heights are responsive. Here is jsFiddle

content
content
content
content
content

content

Loading Spinner

CSS:
.content {
    background:green;
}
.container {
    position: relative;
    background:orange;
    height:2000px;
}
.loaderWrap {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background: red
}
.loader2 {
    position: fixed;
    top: 50%;
    left: 50%;
}


text:
Q: Show the following inequality. Let $a,b,c \in \mathbb R^+$ and $$\frac{1}{a} + \frac{1}{b} + \frac{1}{c} =1$$
Show that $$(a^2 -3a +3)(b^2-3b+3)(c^2-3c+3) \ge 27$$
I tried using using the AM-GM inequality and some algebraic manipulation to who each of the quadratic terms cannot be smaller than $0.75$ and other little results but I am struggling to be able to solve this. Any help would be appreciated.

A: For positive variables let $\frac{1}{a}=\frac{x}{3},$ $\frac{1}{b}=\frac{y}{3}$ and $\frac{1} {c}=\frac{z}{3}.$
Thus, $x+y+z=3$ and we need to prove that
$$\sum_{cyc}\left(\ln\left(\frac{9}{x^2}-\frac{9}{x}+3\right)-\ln3\right)\geq0$$ or
$$\sum_{cyc}\left(\ln(x^2-3x+3)-2\ln{x}\right)\geq0$$ or
$$\sum_{cyc}\left(\ln(x^2-3x+3)-2\ln{x}+3(x-1)\right)\geq0.$$
Let $f(x)=\ln(x^2-3x+3)-2\ln{x}+3(x-1).$
Thus, $$f'(x)=\frac{2x-3}{x^2-3x+3}-\frac{2}{x}+3=\frac{3(x-1)(x^2-2x+2)}{x(x^2-3x+3)},$$
which gives $x_{min}=1$ and we are done!


text:
Q: Keras binary classification probabilities to labels Keras predicted output for binary classification is probabilities. Not classes, i.e., 1 or 0.
for example the following code generates probabilities.
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout

# Generate dummy data
x_train = np.random.random((100, 20))
y_train = np.random.randint(2, size=(100, 1))
x_test = np.random.random((10, 20))
y_test = np.random.randint(2, size=(10, 1))

model = Sequential()
model.add(Dense(64, input_dim=20, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(64, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy',optimizer='rmsprop',metrics=['accuracy'])

model.fit(x_train, y_train,  epochs=20,    batch_size=128)
y_predicted = model.predict(x_test)
print(y_predicted)

and the output is:
Epoch 1/20
100/100 [==============================] - 1s 5ms/step - loss: 0.8134 - acc: 0.4300
Epoch 2/20
100/100 [==============================] - 0s 17us/step - loss: 0.7429 - acc: 0.4600
Epoch 3/20
100/100 [==============================] - 0s 20us/step - loss: 0.7511 - acc: 0.4300
Epoch 4/20
100/100 [==============================] - 0s 18us/step - loss: 0.7408 - acc: 0.5000
Epoch 5/20
100/100 [==============================] - 0s 21us/step - loss: 0.6922 - acc: 0.5700
Epoch 6/20
100/100 [==============================] - 0s 31us/step - loss: 0.6874 - acc: 0.5600
Epoch 7/20
100/100 [==============================] - 0s 29us/step - loss: 0.7005 - acc: 0.5600
Epoch 8/20
100/100 [==============================] - 0s 23us/step - loss: 0.6960 - acc: 0.5200
Epoch 9/20
100/100 [==============================] - 0s 24us/step - loss: 0.6988 - acc: 0.5200
Epoch 10/20
100/100 [==============================] - 0s 26us/step - loss: 0.7276 - acc: 0.4000
Epoch 11/20
100/100 [==============================] - 0s 20us/step - loss: 0.6967 - acc: 0.5000
Epoch 12/20
100/100 [==============================] - 0s 30us/step - loss: 0.7085 - acc: 0.5000
Epoch 13/20
100/100 [==============================] - 0s 24us/step - loss: 0.6993 - acc: 0.5500
Epoch 14/20
100/100 [==============================] - 0s 26us/step - loss: 0.7278 - acc: 0.4600
Epoch 15/20
100/100 [==============================] - 0s 27us/step - loss: 0.6665 - acc: 0.5500
Epoch 16/20
100/100 [==============================] - 0s 24us/step - loss: 0.6784 - acc: 0.5500
Epoch 17/20
100/100 [==============================] - 0s 24us/step - loss: 0.7259 - acc: 0.4800
Epoch 18/20
100/100 [==============================] - 0s 26us/step - loss: 0.7093 - acc: 0.5500
Epoch 19/20
100/100 [==============================] - 0s 28us/step - loss: 0.6911 - acc: 0.5700
Epoch 20/20
100/100 [==============================] - 0s 34us/step - loss: 0.6771 - acc: 0.5500
[[0.4875336 ]
 [0.47847825]
 [0.4808622 ]
 [0.5032022 ]
 [0.4556646 ]
 [0.48644704]
 [0.4600153 ]
 [0.47782585]
 [0.49664593]
 [0.5001673 ]]

Now, how can I get the classes from that probabilities? I tried manually setting a threshold like this:
print([1 if x >0.4 else 0 for x in y_predicted])

Is there any other method to do that from Keras API? I could not find any.

A: Yes, model.predict_classes.
model.predict_classes(x_test)

https://github.com/keras-team/keras/blob/f0eb8d538c82798944346b4b2df917a06bf5e9d4/keras/engine/sequential.py#L254 (predict_classes)
which uses a threshold of 0.5 in case of binary classification or argmax in case of multi-class.


text:
Q: Waiting for operation to finish in node.js I'm new to Node.js. I'm trying to use the Node Redis plugin. What I'm trying to do is get the list of key/value pairs from a REDIS database. The asynchronous nature of Node is creating a challenge for me. When I try to print the key/value pairs, my array is empty. I think its because my query to the database hasn't completed yet.
The reason I'm creating an array first instead of just printing out the key/value pairs, is because I want to sort the results alphabetically by either key or value. Currently, I"m trying the following:
redisClient.on('connect', function() {
  var pairs = [];
  redisClient.keys('*', function (err, keys) {
    if (err) { return console.log(err); }
    for(var i = 0, len = keys.length; i < len; i++) {
      (function(key) {
        redisClient.get(key, function(err, v) {
          pairs.push({ key: key, value: v });
        });
      })(keys[i]);
    }
  });

  // List of key/value pairs ordered alphabetically
  console.log(pairs);
});

Can someone tell me how to get beyond this issue? Thank you

A: You are right in your assertion that when console.log is executed, nothing has happened yet. To deal with this kind of problem in Node.js, some people like to use modules like async and others prefer to use promises (a popular library for promises is Q).
Here is a solution using async.
var async = require('async');

redisClient.on('connect', function() {
  redisClient.keys('*', function (err, keys) {
    if (err) { return console.log(err); }

    async.map(keys, function(key, callback) {
      redisClient.get(key, function(err, value) {
        callback(null, {key: key, value: value});
      });
    }, function(err, pairs) {
      console.log(pairs);
    });
  });
});

async just happens to have a map function that takes an array, applies a function asynchronously to each elements and creates an array with the results.

A: You need to use recursion:
do = function(i, data, callback){
    // if the end is reached, call the callback
    if(data.length === i+1)
       return callback()
    obj = data[i]
    redisClient.get(key, function(err, v) {
      pairs.push({ key: key, value: v });
      i++;
      // call do with the next object
      do(i, data, callback)
    });

}
// Redis...
do(0, keys, function(){
    // List of key/value pairs ordered alphabetically
    console.log(pairs);
});


text:
Q: Combine dictionary of dataframes into 1 single dataframe I am looking for a solution to put all my dataframes which are in a dictionary into 1 single giant dataframe. I am relatively new to Python so I am unable to understand how to iterate over a dictionary and put all the dataframes into 1. The code I have implemented so far, is as below:
import sys
from ftplib import FTP
import os
import socket
import time
import pandas as pd
import numpy as np
from glob import glob

path = 'path_to_file'

files = glob(path + '/*Mail*.xlsx')

print files

get_df = lambda f: pd.read_excel(f, sheetname=None)

dodf = {f: get_df(f) for f in files}  ### dictionary of dataframes

Now, I need to put all the different dataframes into 1 dataframe and then do my operations on that. Any advise would be appreciated.
I have tried this,
for df in dodf:
pd.concat(dodf.values(), ignore_index=True)

But it does not seem to work right.

A: df_list = [ v for k,v in dodf.items()]
df = pd.concat(df_list ,axis=1)

does this work?
It also depends whether the concat is by columns or by rows...

A: I think need concat with dict comprehension:
dodf = {f: pd.read_excel(f, sheet_name=None) for f in files}
df = pd.concat([v for k,v in dodf.items()])

Or:
dodf = {f: pd.read_excel(f, sheet_name=None) for f in files}
df = pd.concat([pd.concat(v) for k,v in dodf.items()])


text:
Q: Error with find and activate functions in excel with vba I'm having a really bad time trying to understand why I get an error which I thing should not appear.
I'm using Office 2007. I have two sheets in Excel, "Ver" and "Encargado", in "Ver" sheet I have one cell in which to put a number and then I press one button. The code inside the button is:
Private Sub CommandButton1_Click()
   Dim buscar As Range
   dato = Range("b2").Value
   If dato = "" Then Exit Sub

   Sheets("Encargado").Select
   Set buscar = Range("b2:b12").Find(What:=dato, LookIn:=xlFormulas, SearchOrder:=xlByRows)

   If Not buscar Is Nothing Then
      buscar.Activate
      ActiveCell.Offset(, -1).Copy Destination:=Ver.Cells(4, 2)
      Sheets("Ver").Select
   Else
      Sheets("Ver").Select
      MsgBox "Encargado no encontrado"
      Exit Sub
   End If
End Sub

In "Encargado" sheet and inside the range b2:b12 there are only numbers beetwen 101 and 111, and when I put the number 117 as an input (for example) I think it should get into the else part as it shouldn't have found any coincidence, but it gets into the if part, why? and I get an error saying "Error en el método activate de la clase Range" (As you noticed I am using Office in spanish, and programming as well with spanish variables). When I run line by line the error appears in the line "buscar.Activate". Does anyone know where is the error? In the case you want to see it, here is the file: https://www.dropbox.com/s/j1b39fqy971n7lf/Todo.xlsm Thanks.

A: You have not defined  the sheet in find function so its referring ver sheet. Use this code.
   Private Sub CommandButton1_Click()
   Dim buscar As Range

   'Application.ScreenUpdating = False

   dato = Range("b2").Value

   If dato = "" Then Exit Sub
    Set buscar = Sheets("Encargado").Range("b2:b12").Find(What:=dato, LookIn:=xlValues, SearchOrder:=xlByRows)
   If Not buscar Is Nothing Then
      'Encargado.Cells.Find(What:=Ver.Cells(2, 2), After:=Range("b2"), LookIn:=xlFormulas, SearchOrder:=xlByRows).Select
      'desplazamiento en fila, desplazamiento en columna, positivo: hacia abajo, hacia la derecha
      'buscar.Activate
      c = buscar.Row

     Sheets("Encargado").Range("a" & c).Copy
     Sheets("Ver").Range("b4").PasteSpecial

   Else
      Sheets("Ver").Select
      MsgBox "Encargado no encontrado"
      Exit Sub
   End If
   'Application.ScreenUpdating = True
End Sub

A: EDIT: As pointed out in the comments below, the Range object DOES have an .Activate method: http://msdn.microsoft.com/en-us/library/office/ff837085(v=office.15).aspx
buscar is a Range object, which does not have an Activate method. The following should get you where you're going, but out of curiosity -- have you looked into Excel's built-in =VLOOKUP functionality? It might save you from requiring VBA here...
Option Explicit
Private Sub CommandButton1_Click()
Dim TerritorioNum As Long, LastRow As Long
Dim TerritorioRange As Range, FoundRange As Range
Dim VerSheet As Worksheet, EncSheet As Worksheet

'set references up-front
Set VerSheet = ThisWorkbook.Worksheets("Ver")
Set EncSheet = ThisWorkbook.Worksheets("Encargado")
With EncSheet
    LastRow = .Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
    Set TerritorioRange = .Range(.Cells(1, 1), .Cells(LastRow, 2))
End With
TerritorioNum = VerSheet.Cells(2, 2).Value

'find the territory number
Set FoundRange = TerritorioRange.Find(TerritorioNum)
If FoundRange Is Nothing Then
    MsgBox ("Encargado no encontrado")
    Exit Sub
Else
    VerSheet.Cells(4, 2) = EncSheet.Cells(FoundRange.Row, FoundRange.Column - 1).Value
End If

End Sub


text:
Q: Rejection sampling confusion I have a confusion about the "intuitive explanation" of rejection sampling given at this link on (apologies, I know it's not always a good source) Rejection Sampling. The text in the introduction reads as follows (emphasis and additions mine)

Rejection sampling works as follows:

*

*Sample point on x-axis from proposal distribution p(x).

*Draw vertical line at this x-position, up to the maximum y-value of the proposal distribution, p(x).

*Sample uniformly along this line $\alpha$ from 0 to the maximum of the probability density function p(x). If sampled value is greater than the value of the desired distribution at this vertical line f(x), reject the x-value and return to step 1; else the x-value is a sample from the desired distribution.

My confusion is in the use of the word "maximum." The mathematical formulation of the rejection criterion is based upon comparing the uniform random variable $\alpha$ as follows:

*

*Draw $\alpha \sim U(0, M p(x))$ where $M$ is the constant ensuring $Mp(x) > f(x)$ envelopes the desired distribution.

*If $\alpha > f(x)$ reject.

However, the text written above seems to suggest drawing $\alpha \sim U(0, \textrm{max}(p(x))$ which greatly increases the spread of the samples, since we would now include values of $\alpha > p(x)$.
Is the article incorrect, or is it assuming that the proposal distribution is uniform? Or have I misinterpreted the text and the use of the word "maximum?"
Related to this, the application of my question is to the following:
I want to use rejection sampling to improve the sampling of a function. Right now I am generating samples from a proposal, p(x), with a mechanism that approximates the desired distribution, f(x), but in such a way that I don't actually know p(x).
Is there a sampling method that allows me to accept or reject these samples according to their value of f(x) without knowing the exact value of p(x) for each sample x?

A: The explanation is doubly confusing in that (1) the "maximum" is meant as $p(x)$ rather than as $\max_x p(x)$. And (2) this maximum should be $Mp(x)$ where $M$ is an upper bound on $f(x)/p(x)$ over all $x$'s. Generating a pair $(x,\alpha)$ this way produces a Uniform generation over the sub-graph of the function $Mp(\cdot)$. In the event the pair $(x,\alpha)$  also belongs to the sub-graph of the function $f(\cdot)$, it is then a Uniform generation over this sub-graph. Therefore, the marginal density of the accepted $x$ is $f(x)$, which validates the algorithm. (This is also the principle behind slice sampling.)
Here is an illustration taken from our book (pp.53-54):

To simulate beta $\mathcal{B}e(\alpha, \beta)$ random variables, we
can, however, construct a toy algorithm based on the Accept--Reject
method, using as the instrumental distribution the uniform ${\cal
  U}_{[0,1]}$ distribution when both $\alpha$ and $\beta$ are larger
than $1$. (The generic rbeta function does not impose this restriction.)
The upper bound $M$ is then the maximum of the beta density, obtained
for instance by optimize (or its alias
optimise):

 optimize(f=function(x){dbeta(x,2.7,6.3)},
         interval=c(0,1),max=T)$objective
 [1] 2.669744

Since the candidate density $g$ is equal to one, the proposed value
$Y$is accepted if $M \times U < f(Y)$, that is, if $M \times U$ is
under the beta density $f$ at that realization. Note that generating
$U \sim {\mathcal U}_{[0,1]}$ and multiplying $U$ by $M$ is equivalent to
generating $U \sim {\mathcal U}_{[0,M]}$. For $\alpha = 2.7$ and
$\beta = 6.3$, an alternative \R implementation of the Accept--Reject
algorithm is

   Nsim=2500
   a=2.7;b=6.3
   M=2.67
   u=runif(Nsim,max=M)    #uniform over (0,M)
   y=runif(Nsim)          #generation from g
   x=y[u<dbeta(y,a,b)]    #accepted subsample

and the left panel in the Figure below shows the results of generating
$2500$ pairs $(Y,U)$ from ${\mathcal U}_{[0,1]}\times{\mathcal
  U}_{[0,M]}$. The black dots $(Y,Ug(Y))$ that fall under the density
$f$ are those for which we accept $X=Y$, and we reject the grey dots
$(Y,Ug(Y))$ that fall outside. It is again clear from this graphical
representation that the black dots are uniformly distributed over the
area under the density $f$. Since the probability of acceptance of a
given simulation is  $1/M$, with $M=2.67$ we accept approximately
$1/2.67 = 37\%$ of the values.

Consider instead simulating $Y \sim \mathcal{B}e(2, 6)$ as a proposal distribution.
This choice of $g$ is acceptable since

 optimize(f=function(x){dbeta(x,2.7,6.3)/dbeta(x,2,6)},
 max=T,interval=c(0,1))$objective
 [1] 1.671808

This modification of the proposal thus leads to a smaller value of $M$ and a correspondingly higher acceptance rate of $58\%$ than with the uniform proposal.
The right panel of the Figure shows the outcome of the corresponding Accept--Reject algorithm and illustrates the gain in efficiency brought by simulating points in a smaller set.

When considering the second part of the question,given that the choice of $p(\cdot)$ is open, among those densities bounding $f(\cdot)$, computing $p(x)$ is not a primary issue when using Accept-Reject algorithms.

Is there a sampling method that allows me to accept or reject these
samples according to their value of f(x) without knowing the exact
value of p(x) for each sample x?

What matters is the ability to compute the ratio $f(x)/Mp(x)$ for any given $x$. This means that

*

*both densities $f$ and $p$ only need be known up to a normalising constant

*$p$ can be chosen towards eliminating the computation of intractable parts of $f$. That is, if $f(\cdot)=f_1(\cdot)f_2(\cdot)$ where $f_2(x)$ cannot be computed, choosing $p(\cdot)=p_1(\cdot)f_2(\cdot)$ eliminates the need to compute $f_2(x)$, providing $p(\cdot)$ can be simulated, i.e., is a generative model.

*if $f(x)$ can be written as$$f(x)=\int_\mathfrak Z \tilde f(x,z)\text dz$$ where the integral is intractable and $\tilde f(x,z)$ can be computed, using a proposal density $\tilde p(x,z)$ such that $\tilde f(x,z)/\tilde p(x,z)$ is bounded is sufficient for simulating $f$ even though $f(x)$ cannot be computed.


text:
Q: Error starting app on Heroku using Devise When pushing a new app to heroku, then running heroku rake db:migrate I get the following error:
heroku rake db:migrate
rake aborted!
Please install the postgresql adapter: `gem install activerecord-postgresql-adapter` (pg is not part of the bundle. Add it to Gemfile.)

Does anyone have any idea why it's asking for postgresql? In my gemfile the only db gem I'm using is sqlite.
This app is using Devise for authentication, that's the only gem out of the ordinary in the app's gemfile. On a sidenote, when I attempt to follow the advice, bundler throws:
Could not find gem 'activerecord-postgresql-adapter (>= 0)' in any of the gem sources listed in your Gemfile.

A: you can't use sqlite3 on Heroku, you have to use their Postgres or use your own external Db.
In your gemfile do
group :development do
 gem 'sqlite3'
end

group :production do
 gem 'pg'
end

to let you use sqlite3 locally and postgres on Heroku.


text:
Q: ToList method not available for TrackableCollection We are working with Trackable Entities on top of EF 4.0.
In order to delete an Entity with all its dependent entities I'm writing a generic DeleteDependentEntities to be called from the Delete method in the EntityManager. (We don't, or don't want to, rely on a CASCADE DELETE to be set on the relations in our database.) The DeleteDependentEntities scans recursevly all Children of the subjected entitySet.
In order to keep it generic, so that it can be used for all entities throughout the project I'm using dynamic types.
The method is as follows:
private void DeleteDependentEntities(dynamic entitySet, dynamic context)
{
  if (entitySet != null)
  {
    foreach (dynamic item in entitySet.ToList())
    {
      // 1. Scan object for children and delete children
      ProcessChildren(item, context);

      // 2. Delete this object
      context.DeleteObject(item);
    }
  }
}

It compiles OK, but at runtime I get the following error:
'SLS.AnimalIntakeMgmt.DataTypes.TrackableCollection' does not contain a definition for 'ToList'
Hence the type inference worked OK.  Problem with the ToList definition is weird since TrackableCollection is based on ObservableCollection which in its turn is based on Collection.
The ToList is necessary because otherwise the foreach loop fails because the collection is modified within the loop.
All suggestions are welcome!

A: The problem is that dynamics don't work with extension methods. The runtime only looks for methods defined on the dynamic object itself.
You need to call ToList as a static method:
foreach (dynamic item in Enumerable.ToList(entitySet))

But I really think you should use generics if possible at all.