text:
Q: StandardScaler with exported Keras model I just exported my keras model because I want to use it for my web application. For classification I'm using features from single audio files. The problem ist that with each prediction I only have one row, what makes the output of the StandardScaler 0. Is there any way to export the sklearn objekt that I can re use it in my webapp instead of using all the data from when I trained the model?
Best regards

A: I haven't used the webapp before, but I can save the trained scaler with joblib and then load it in the future.
from sklearn.preprocessing import StandardScaler
import joblib
from sklearn.datasets import load_breast_cancer

data = load_breast_cancer()

data = data.data

scaler = StandardScaler()

scaler = scaler.fit(data)

data_t = scaler.transform(data)
#saves the trained scaler
joblib.dump(scaler,r"scaler")

#Loads for transforming the new  data
scaler_2 = joblib.load(r"scaler")

data_t_2 = scaler.transform(data)


text:
Q: Loading XML file and deserializing data as Dictionary in C# I'm working on a personal localization project for strings where data is contained within XML files and deserialzed to a Dictionary.
Apart from the main XML file that holds stats, I hold the string data in separate files, loading in the specified language file in separately. I fetch the matching string data via the ID that is used as the key to display the string data in the correct language.
I'm a beginner to C# and serialization, and have already worked on a more simple version where the Dictionary was only an int key from an attribute and a string value. That works, and I'm trying to build off of that.
With this version, the value would be an object. I have tried wrapping the data in an additional element, but ideally I would like to avoid that to use less lines and make it easier for me to read and edit as the file gets larger.
XML File:
<DataStrings>
    <ItemString id="1">
        <Name>Item 1</Name>
        <ID>1</ID>
        <Description>Item 1's description</Description>
    </ItemString>

    <ItemString id="2">
        <Name>Berry</Name>
        <ID>2</ID>
        <Description>Item 2's description</Description>
    </ItemString>

    <ItemString id="3">
        <Name>Shotgun</Name>
        <ID>3</ID>
        <Description>Item 3's description</Description>
    </ItemString>
</DataStrings>

Applicable C# Code:
public IDictionary<int, Data> ItemStringData = new Dictionary<int, Data>();

public class ItemString {
    [XmlAttribute("id")]
    public int Key;

    // not sure what to put here
    public Data Value;
}

public class Data {
    [XmlElement("Name")]
    public string Name = null;

    [XmlElement("ID")]
    public int ID = 0;

    [XmlElement("Description")]
    public string Description;

}

public Dictionary<int, Data> LoadDictionary2(string path) {
    Dictionary<int, Data> dict = new Dictionary<int, Data> { };

    using (var reader = new StreamReader(path)) {
        XmlSerializer deserializer = new XmlSerializer(typeof(List<ItemString>), new XmlRootAttribute("DataStrings"));
        dict = ((List<ItemString>)deserializer.Deserialize(reader)).ToDictionary(x => x.Key, x => x.Value);
    }

    return dict;
}

After deserialization, the code successfully gets the id key for each item, but returns null for the value.
With this post I'm asking for advice on where to look next after a couple days of attempts. Is this even correct/efficient XML? Is this a valid way to store data? I'm more familiar with relating between MySQL databases, and querying with PHP.
Should I remove the ID attribute, and is it possible to build a Dictionary where the key is taken from the ID element and all of the data is contained within a class as the value?
More importantly, a push in the right direction would be amazing.

A: Your [XmlAttribute("id")] is in the wrong class - it's an attribute of Data:
public class DataStrings
{
    [XmlElement("ItemString")]
    public List<Data> Value;
}

public class Data
{
    [XmlAttribute("id")]
    public int id;

    [XmlElement("Name")]
    public string Name = null;

    [XmlElement("ID")]
    public int ID = 0;

    [XmlElement("Description")]
    public string Description;

}

public Dictionary<int, Data> Main(string path)
{
    var stringReader = new StringReader("<DataStrings><ItemString id=\"1\"><Name>Item 1</Name><ID>1</ID><Description>Item 1's description</Description></ItemString><ItemString id=\"2\"><Name>Berry</Name><ID>2</ID><Description>Item 2's description</Description></ItemString><ItemString id=\"3\"><Name>Shotgun</Name><ID>3</ID><Description>Item 3's description</Description></ItemString></DataStrings>");
    XmlSerializer deserializer = new XmlSerializer(typeof(DataStrings), new XmlRootAttribute("DataStrings"));
    var dict = ((DataStrings)deserializer.Deserialize(stringReader)).Value.ToDictionary(x => x.id, x => new Data() { ID = x.ID, Name = x.Name, Description = x.Description });
    return dict;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: O(N+M) time complexity I'm working through some practice problems where I'm given a target time complexity and space complexity. One of them gives a target time complexity of O(N+M). I'm having some trouble with the intuition of what an O(N+M) algorithm would look like. Does anyone have an example of an algorithm like this or can explain it clearly? Every example I try to think of seems like O(N*M) to me.

A: A simple example of algorithm that is O(m+n):
int sum(int[] nArr, int[] mArr) {
    int sum = 0;
    for(int i : nArr) {
        sum += i;
    }
    for(int i : mArr) {
        sum += i;
    }
    return sum;
}

To compute the sum, you need to go through all elements in nArr (size n) and all elements in mArr (size m), so the overall complexity is O(m+n)

A: Quick and simple example of an O(n + m) algorithm:
for (i = 0; i < n; i++)
{
  // do something but don't loop or invoke recursive functions
  // only constant O(c) complexity is allowed: a simple series of commands
}

for (i = 0; i < m; i++)
{
  // idem
}

Complexity is commutative when added (O(n + m) == O(m + n)) this means you may invert the two for() without affecting complexity. Obviously, on an algorithmic level the inverted one MAY not be equivalent to the straight one.
As an additional help, here is an example of O(n * m) algorithm:
for (i = 0; i < n; i++)
{
  for (j = 0; j < m; j++)
  {
    // do something but don't loop or invoke recursive functions
    // only constant O(c) complexity is allowed: a simple series of commands
  }
}

Again, you may invert inside with outside loop without affecting complexity (O(n * m) == O(m * n)). The same obvious considerations apply.
The limitation on what you may put into the for() bodies is because the big-o notation constraints the upper bound. If it were a lower bound (little-o notation) you may have put more complex stuff in, but it could never get less than that.

A: The intuition of this problem is that you have two unique variables n and m. Now imagine these two unique variables independently increasing, approaching infinity.
If this were an O(n) problem (i.e. BIG-O), the upward boundary of the complexity of this problem would be linear at least. You could say that O(n) = n^2. But an O(n) problem would never even get close to that n^2 limit as n (the input) approaches infinite.
Likewise, the behavior for m would be the same. O(m) can be m^2. But it is more accurate to say that O(m) = m. The complexities of these two problems are linear.

Now, if you just do O(n+m), is that really n^2? It shouldn't be. Even if n=m, the sum would be 2n or 2m. The complexity of this problem is still linear because the size of the output is still proportional to the inputs n and m. Therefore, the most precise answer to this problem would be O(n+m) = n+m.

A: So, in order to expand the other replies,  I will try to add a example of such problems to help you understand:

*

*Find a min/max in a N sized array, and then look for this value in an M sized array. Since you need to perform first min/max search, you cannot do  it at once.

For instance, summing up the elements of 2 vectors can be done in O(M+N), but it can be thought as O(N) (assuming N>M) or O(M) (if M>N).

A: All Above Answers illustrate how O(n+m) works but I would like to look at it from a different view by knowing what O(nm), what is the difference between O(n+m) and O(nm) the main difference is when multiplying an n number by m number it means that n will happen for m times or will try it for m times, for example, the below    code is O(n*m) because n will happen m times for n times
for(int i=0; i < n;i++){
  for(int j=0; j < m;j++){
  //some_code
  }
}

A: One instructive example which does something non-trivial is to take two sorted arrays of size M and N and output a new sorted array with all of these elements. This is the basis of merge-sort and will take O(M+N) comparisons.
You can find an example anywhere or do it yourself.


text:
Q: Custom class attribute that applies a different attribute to all methods I know I can create a custom class attribute like so:
[AttributeUsage(AttributeTargets.Class)]
class MyClassAttribute : Attribute {
    // Logic in here to apply MyMethodAttribute to all methods
    // in the class to which this is applied.
}

...and I can create a custom method attribute like so:
[AttributeUsage(AttributeTargets.Method)]
class MyMethodAttribute : Attribute { }

How can I edit the logic of MyClassAttribute such that it automatically applies MyMethodAttribute to all methods in the class that I apply it to? Is this even possible?

A: According to this documentation, it is impossible to trigger some other decoration logic as there is no access from the Attribute itself to the class (or method) it is applied to.

A: What about using partial methods and T4?
You'd run the template - it'd use reflection to generate partial method stubs for all methods in the class which has the attribute, and add the attribute on automatically.
Obviously it's not ideal (you have to mark your classes as partial, and you'd need one template per assembly), but it might work for you.


text:
Q: convert nested dictionary into pandas dataframe example dictionary:
sample_dict = {'doctor': {'docter_a': 26, 'docter_b': 40, 'docter_c': 42},
               'teacher': {'teacher_x': 21, 'teacher_y': 45, 'teacher_z': 33}}

output dataframe:
job     person     age
doctor |doctor_a | 26
doctor |doctor_b | 40
doctor |doctor_c | 42
teacher|teacher_x| 21
teacher|teacher_y| 45
teacher|teacher_z| 33

I have tried:
df = pd.dataFrame.from_dict(sample_dict)

=>
             doctor      teacher
doctor_a  |  26      |   Nah
doctor_b  |  40      |   Nah
doctor_c  |  42      |   Nah
teacher_x |  Nah     |   21
teacher_y |  Nah     |   45
teacher_z |  Nah     |   33

Could someone help me figure this out?

A: Use a nested list comprehension:
pd.DataFrame([[k1, k2, v]
              for k1,d in sample_dict.items()
              for k2,v in d.items()],
             columns=['job', 'person', 'age'])

Output:
       job     person  age
0   doctor   docter_a   26
1   doctor   docter_b   40
2   doctor   docter_c   42
3  teacher  teacher_x   21
4  teacher  teacher_y   45
5  teacher  teacher_z   33

A: You can construct a zip of length 3 elements, and feed them to pd.DataFrame after reshaping:
zip_list = [list(zip([key]*len(sample_dict['doctor']),
                 sample_dict[key],
                 sample_dict[key].values()))
            for key in sample_dict.keys()]

col_len = len(sample_dict['doctor']) # or use any other valid key
output = pd.DataFrame(np.ravel(zip_list).reshape(col_len**2, col_len))


text:
Q: How to set Animation Slide Down to card view when click on arrow down in ViewHolder? I tried to set slide down animation to card when the user click on the arrow down icon but it not work when I setAnimationListener(this). it error at "this" keyword.
Note I use recycler view and card in the fragment.
here my code below
class ListViewHolder extends RecyclerView.ViewHolder{
        TextView tvTitle, tvDescription;
        ImageView ivDropDown;
        LinearLayout ll_footer;
        Button btnClose;
        Animation slideDown;

        public ListViewHolder(View itemView) {
            super(itemView);
            tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
            tvDescription = (TextView) itemView.findViewById(R.id.tv_description);
            ivDropDown = (ImageView) itemView.findViewById(R.id.iv_arrow_down);
            ll_footer = (LinearLayout) itemView.findViewById(R.id.ll_footer);
            btnClose = (Button) itemView.findViewById(R.id.btn_close);

            btnClose.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
//                    callBack.onButtonCloseClick(getAdapterPosition());
                    ll_footer.setVisibility(View.GONE);
                }
            });

            ivDropDown.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    callBack.onImageClick(getAdapterPosition());
                    slideDown = AnimationUtils.loadAnimation(context, R.anim.slide_down);
                    ll_footer.setAnimation(slideDown);
                    slideDown.setAnimationListener();
                    ll_footer.setVisibility(View.VISIBLE);
                }
            });
        }
    }

A: You have not start animation.
to do like this:
class ListViewHolder extends RecyclerView.ViewHolder implements Animation.AnimationListener{
    TextView tvTitle, tvDescription;
    ImageView ivDropDown;
    LinearLayout ll_footer;
    Button btnClose;
    Animation slideDown;

    public ListViewHolder(View itemView) {
        super(itemView);
        tvTitle = (TextView) itemView.findViewById(R.id.tv_title);
        tvDescription = (TextView) itemView.findViewById(R.id.tv_description);
        ivDropDown = (ImageView) itemView.findViewById(R.id.iv_arrow_down);
        ll_footer = (LinearLayout) itemView.findViewById(R.id.ll_footer);
        btnClose = (Button) itemView.findViewById(R.id.btn_close);

        btnClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                    callBack.onButtonCloseClick(getAdapterPosition());
                ll_footer.setVisibility(View.GONE);
            }
        });

        ivDropDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callBack.onImageClick(getAdapterPosition());
                slideDown = AnimationUtils.loadAnimation(context, R.anim.slide_down);
                ll_footer.startAnimation(slideDown);
                slideDown.setAnimationListener(ListViewHolder.this);
                ll_footer.setVisibility(View.VISIBLE);
            }
        });
    }
    @Override
    public void onAnimationStart(Animation animation) {

    }

    @Override
    public void onAnimationEnd(Animation animation) {

    }

    @Override
    public void onAnimationRepeat(Animation animation) {

    }
}

A: First of all, create the following anim file named slide_down.xml :
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator">

    <translate
        android:duration="@android:integer/config_mediumAnimTime"
        android:fromYDelta="-100%"
        android:toYDelta="0" />
</set>

Thereafter, use the above anim file as follows :
ivDropDown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                callBack.onImageClick(getAdapterPosition());
                Animation slideDown = AnimationUtils.loadAnimation(mContext,
                R.anim.slide_down);
        slideDown.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                // show the footer
                ll_footer.setVisibility(View.VISIBLE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
                ll_footer.startAnimation(slideDown);
            }
        });

A:  Pass context from activity to adapter class using adapter constructor.

Then use the following lines and remove animation listener.
 slideDown = AnimationUtils.loadAnimation(context, R.anim.slide_down);
                        ll_footer.startAnimation(slideDown);


text:
Q: why not picking native windows cache? looking at https://docs.oracle.com/javase/8/docs/technotes/guides/security/jgss/tutorials/AcnOnly.html
LoginContext lc = null;
    try {
        lc = new LoginContext("JaasSample", new TextCallbackHandler());
    } catch (LoginException le) {
        System.err.println("Cannot create LoginContext. "
            + le.getMessage());
        System.exit(-1);
    } catch (SecurityException se) {
        System.err.println("Cannot create LoginContext. "
            + se.getMessage());
        System.exit(-1);
    }
    try {

      // attempt authentication
      lc.login();

  } catch (LoginException le) {

      System.err.println("Authentication failed: "
      System.err.println("  " + le.getMessage());
      System.exit(-1);

  }

  System.out.println("Authentication succeeded!");

}

my config file :-

   JaasSample {
    com.sun.security.auth.module.Krb5LoginModule required
    debug=true
    doNotPrompt=true
    useTicketCache=true
         ;
    };

why does it not use the cache of the windows user that has signed on?
Have I misunderstood?
thanks in advance?
JemRug


text:
Q: Is it possible to control elements in WSDL minOccurs maxOccurs? is it possible writing WCF, that will expose my properties with controllable maxOccurs?
<xs:element name="param" type="string" minOccurs="1" maxOccurs="10" />
What I have only found, it's control over complex types.
Thanx in advance.


text:
Q: Counting number of rows if certain conditions are met Im sure someone has a smart solution for this problem:
I have a dataframe like so:
A <- c("name1", "name2", "name3", "name4", "name5", "name6")
B <- c(10, 8, 7, 3, -1, -2)
C <- c(8, 3, -1, -10, -2, -2)
df <- data.frame(A, B, C)
df

      A  B   C
1 name1 10   8
2 name2  8   3
3 name3  7  -1
4 name4  3 -10
5 name5 -1  -2
6 name6 -2  -2

I want to obtain four values, by counting the rows if certain conditions are met:

*

*I want to count the number of rows in this dataframe where both B and C are negative integers (>0) -- for this example that would be "2"

*I want to count the number of rows in this dataframe where both B and C are positive integers (<0)-- for this example that would be "2"

*I want to count the number of rows in this dataframe where B is a negative integer (>0) and C is positive -- for this example that would be "0"

*I want to count the number of rows in this dataframe where B is a postive integer and C is negative) -- for this example that would be "2"

Im suspecting that this can be achieved with some sort of If/Else statement, combined with the "table(sign..." command?

A: Try this:
library(dplyr)

df_count <- df %>% summarise(con1 = sum(B < 0 & C < 0),
                             con2 = sum(B > 0 & C > 0),
                             con3 = sum(B < 0 & C > 0),
                             con4 = sum(B > 0 & C < 0))

df_count
con1 con2 con3 con4
   2    2    0    2

A: We can use count after creating a column with interaction on the sign
library(dplyr)
df %>%
   transmute(con = factor(interaction(sign(B), sign(C), sep=" "),
     levels = c('1 1', '1 -1', '-1 1', '-1 -1'))) %>%
   count(con, .drop = FALSE)
#    con n
#1   1 1 2
#2  1 -1 2
#3  -1 1 0
#4 -1 -1 2


text:
Q: c# this.sightCursor = new Cursor(GetType(), "Sight.Cur") gives Object reference not set to an instance of an object namespace Sample {
    public partial class Catcher: UserControl {
    Cursor sightCursor;
    bool running = false;
    CWindow parent;
    CWindow curWin = 0;
    Highlighter highlighter;
    public Catcher() {
        InitializeComponent(); * * this.sightCursor = new Cursor(GetType(), "Sight.Cur"); * *
        this.LostFocus += new EventHandler(Catcher_LostFocus);

        if (highlighter == null)
        highlighter = new Highlighter();
        ((CWindow) highlighter.Handle).Transparent = true;
    }

    * * this.sightCursor = new Cursor(GetType(), "Sight.Cur"); * * this is where i get error of Object reference not set to an instance of an object!

    Sight.Cur is available at my recources also!

    Looking forward of your helps..Thanks


text:
Q: .NET Core float variable don't print decimals I assign 2097151.3 to the float variable and the application prints only the integer part. Possible bug?
public static void Main(string[] args)
{
    float foo = 2097151.3F;

    Console.WriteLine(foo); // prints 2097151

    Console.ReadKey();
}

I'm running a .NET Core console application.

A: Nope. Floating point numbers have been around since the 1940s. A float is only really good for 7 significant figures.
The nearest float to 2097151.3 is 2097151.25, and WriteLine is clever enough to know that and so it truncates accordingly.
If you want precise decimal values then use a decimal type.


text:
Q: R - predict command error "undefined columns selected" I'm a newbie to R, and I'm having trouble with an R predict command.
I receive this error
 Error in `[.data.frame`(newdata, , as.character(object$formula[[2]])) :
  undefined columns selected

when I execute this command:
model.predict <- predict.boosting(model,newdata=test)

Here is my model:
model <- boosting(Y~x1+x2+x3+x4+x5+x6+x7, data=train)

And here is the structure of my test data:
    str(test)
'data.frame':   343 obs. of  7 variables:
 $ x1: Factor w/ 4 levels "Americas","Asia_Pac",..: 4 2 4 2 4 3 3 3 4 1 ...
 $ x2: Factor w/ 5 levels "Fifth","First",..: 3 3 2 2 4 2 4 4 1 1 ...
 $ x3: Factor w/ 3 levels "Best","Better",..: 2 3 1 1 3 2 2 1 3 3 ...
 $ x4: Factor w/ 2 levels "Female","Male": 1 1 2 1 1 2 1 2 2 2 ...
 $ x5: int  82 55 47 31 6 53 77 68 76 86 ...
 $ x6: num  22.8 14.6 25.5 38.3 7.9 32.8 4.6 34.2 36.7 21.7 ...
 $ x7: num  0.679 0.925 0.897 0.684 0.195 ...

And the structure of my training data:
$ RecordID: int  1 2 3 4 5 6 7 8 9 10 ...
 $ x1      : Factor w/ 4 levels "Americas","Asia_Pac",..: 1 2 2 3 1 1 1 2 2 4 ...
 $ x2      : Factor w/ 5 levels "Fifth","First",..: 5 5 3 2 5 5 5 4 3 2 ...
 $ x3      : Factor w/ 3 levels "Best","Better",..: 2 3 2 2 3 1 2 3 1 1 ...
 $ x4      : Factor w/ 2 levels "Female","Male": 1 2 2 2 1 1 2 2 1 1 ...
 $ x5      : int  1 67 75 51 84 33 21 80 48 5 ...
 $ x6      : num  21 13.8 30.3 11.9 1.7 13.2 33.9 17 3.4 19.5 ...
 $ x7      : num  0.35 0.85 0.73 0.39 0.47 0.13 0.2 0.12 0.64 0.11 ...
 $ Y       : Factor w/ 2 levels "Green","Yellow": 2 2 1 2 2 2 1 2 2 2 ..

I think there's a problem with the structure of the test data, but I can't find it, or I have a mis-understanding as to the structure of the "predict" command.  Note that if I run the predict command on the training data, it works.  Any suggestions as to where to look?
Thanks!

A: predict.boosting() expects to be given the actual labels for the test data, so it can calculate how well it did (as in the confusion matrix shown below).
library(adabag)

data(iris)

iris.adaboost <- boosting(Species~Sepal.Length+Sepal.Width+Petal.Length+
      Petal.Width, data=iris, boos=TRUE, mfinal=10)

# make a 'test' dataframe without the classes, as in the question
iris2 <- iris
iris2$Species <- NULL

# replicates the error
irispred=predict.boosting(iris.adaboost, newdata=iris2)
#Error in `[.data.frame`(newdata, , as.character(object$formula[[2]])) :
#  undefined columns selected

Here's working example, drawn largely from the help file just so there is a working example here (and to demonstrate the confusion matrix).
# first create subsets of iris data for training and testing
sub <- c(sample(1:50, 25), sample(51:100, 25), sample(101:150, 25))
iris3 <- iris[sub,]
iris4 <- iris[-sub,]

iris.adaboost <- boosting(Species ~ ., data=iris3, mfinal=10)

# works
iris.predboosting<- predict.boosting(iris.adaboost, newdata=iris4)

iris.predboosting$confusion
#               Observed Class
#Predicted Class setosa versicolor virginica
#     setosa         50          0         0
#     versicolor      0         50         0
#     virginica       0          0        50

A: when your y is factor, show this error, try as.vector(y)~.

A: The column names of the data that you use to predict should be exactly the same as the column names of training data.


text:
Q: What would be the best way to let Box2D handle collision at different (simulated) heights? I'm working on a 2D top-down game but we are also using a Z coordinate. This is to simulate the effect of 3D/height. Now the player can walk under a bridge and also over a bridge. The next thing I did was manage collision at these different heights. I got it working that the player collides with the bridge edge when he walks over it, but when he walks under it, he doesn't collide. But I'm not sure if I've done this correctly.
The way I'm currently doing it, is using different bits for different heights:
public static final short ENTITY_Z0_BIT = 1;
public static final short ENTITY_Z1_BIT = 2;
public static final short ENTITY_Z2_BIT = 4;
public static final short COLLISION_Z0_BIT = 8;
public static final short COLLISION_Z1_BIT = 16;
public static final short COLLISION_Z2_BIT = 32;

And then a collision body on Z 1 (or second floor) will have the following filter:
fixtureDef.filter.categoryBits = COLLISION_Z1_BIT;
fixtureDef.filter.maskBits = ENTITY_Z1_BIT;
fixtureDef.filter.groupIndex = (short) 0;

This will mean the wall on the second floor will only collide with an entity on the second floor, because I also change the entity's filter depending on if their Z coordinate increases/decreases. This means I have to add more bits if I need a higher simulated Z-axis and it also doesn't allow for dynamic z-axis handling as I will need to do a big switch-case or if-statements for every Z-axis and then set the filter accordingly.
My second option was setting the groupIndex to be the same as the collision/entity's z-axis + 1. If a collision body and an entity body both have groupIndex 1, they will ALWAYS collide. However if the entity moves up on the z-axis, it's groupIndex will be set to 2 and thus it won't collide anymore. This also seemed like a nice and more dynamic idea. But then anything that needs to collide with a wall or entity, automatically also collides with all the other bodies that need the same groupIndex for the same reason. This doesn't allow for a lot of flexibility.
Which of these 2 options is best? And if there's another better way to handle this, do let me know!


text:
Q: Check double booking feature with SharePoint online calendar In SharePoint online "Group Work Lists" feature is hidden. so i have activated referring below link and double booking functionality working properly.
https://www.codeproject.com/articles/588685/reservationplusofplusresourcesplusinplussharepoint
but the problem is that the "Group Work Lists" feature and also other group site template feature not available so it might happen that it can be removed in future so i don't want to use this feature for check double booking feature in calendar.
So is there any way to achieve "Check double booking" functionality using javascript/jquery or other ways?
Any help would be appreciated.


text:
Q: django redirect url containing id i want to add in my settings.py  a declaration like:
LOGIN_REDIRECT_URL='^private_profile/(?P<id>\d+)/$'
#or
LOGIN_REDIRECT_URL='/accounts/private_profile/id/'

so that when the user with the id 1, for example,is logging in, he will be redirected to
LOGIN_REDIRECT_URL='/accounts/private_profile/1/'

but both alternatives,
LOGIN_REDIRECT_URL='^private_profile/(?P<id>\d+)/$'
#or
LOGIN_REDIRECT_URL='/accounts/private_profile/id/'

are wrong, because in my browser i don't see the current user id, where am i wrong?
Thanks

A: When a user is logged, the request passed as the first parameter of your view has a user field. So in your view, you will know which user is logged:
def userProfile(request):
    print request.user

In My projets, I never specify the username in the urls because the User is already known in your code.

A: You could set your LOGIN_REDIRECT_URL to a view that checks for the id of the currently logged-in user. This view can then redirect the user to the correct location.
Login -> View checks current user id -> redirects to the correct page using user id

A: One trick to accomplish this would be defining a generic view for everybody and linking them to that, this view could then look like:
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required

@login_required
def after_login(request):
    return HttpResponseRedirect('/accounts/private_profile/%d/'%request.user.id)

But as said in my comment, this is only if you really want the user id in the url, which is most of the time not necessary at all. As you can see in my view, you can get the user id from the request context, provided django.contrib.auth.context_processors.auth is added to the TEMPLATE_CONTEXT_PROCESSORS setting in settings.py

A: I did it this way.
#========== Login View ==========#
def login(request):
   #==login stuff==#
   return HttpResponseRedirect('/accounts/private_profile/'+user.id+'/')

#========== PROJECT urls.py ==========#
urlpatterns = patterns('',
   (r'^accounts/', include('my_project.accounts.urls')),
   (r'^login/', login),
)

#========== ACCOUNTS APP urls.py ==========#
urlpatterns = patterns('',
   (r'^private_profile/(?P<id>\d+)/', private_profile),
)


text:
Q: How to make chating application in android? I want to create chating  app in which two different users able to do personal chating using app(like whats app), Here users registered on sql server.

A: Look into GCM(Google Cloud Messaging). Also, this question has been asked many times before so just use search.


text:
Q: TalkBack screen reading issues I'm trying to grasp how to code with screen readers in mind, and I'm having a number of issues. The first example is a single HTML element that I tried to display:

This is an element.

Talkback on Android will read it as "This is an element header 2," but I'd like to know how to make it so that it is just read back as "This is an element."
Another issue is in elements with numerous nested child elements; for example, I tested this:

This is text for the div.

 This is additional text.

I would like the screen reader to say "This is text for the div. This is additional text.", but it only says "This is text for the div." I was under the impression that aria-atomic would make it so that all of the contents of the region are read, so what might I be doing wrong? I tried to make the second sentence a title, but that didn't work, either (How would I make it so that both the contents of the div and the title attribute are read in a scenario such as this?).
Finally, while that problem persists, I was weirdly able to get both title text and the content text to be read together with:
this is additional text

...but only when I focus on that element individually. If I tried making that a child of a div with other text, a la:

This is a title and this is additional text

It will read off "This is a title and this is additional text," when I want "This is a title and this is additional text for the title." It basically skips the title attribute.
This is very confusing; I've read up on aria attributes and how certain screen readers and Talkback in particular work, but I'm having no luck. Any help would be greatly appreciated.

A: If you are putting a span under heading tags like  in your case, screen reader will read the heading level. If you don't want the heading to be read, then do not put the span inside heading tag.


text:
Q: How to transform an object in a printable object in C++ I would like to know how to print the value inside this object in C++:
#include <iostream>

void A::B(content::C* c) {
  cout << c << endl;
}

Currently the code above is only returning the memory address.
Thank you.

A: The variable c is declared as a pointer:
content::C* c
To print the contents of c, you have to do two things:

*

*Overload operator<< for ostream.

*Dereference the pointer.

The above will allow a statement like:
cout << *c << endl;

There are a plethora of examples on overloading operator<<.
Alternately, you can write an output function that outputs each member.
The C++ has no standard facilities for outputting members of a class or struct.


text:
Q: Media queries not taking effect on browser resize I'm using media queries to make a mobile version of a website for a client. When i resize the browser the media queries do not take effect, however they do take effect when the site is viewed on each device - i'm just curious as to why the media queries don't take effect when i resize the browser window itself i.e. Firefox.
Any input is much appreciated.
Code i'm using:
    @media only screen
    and (min-device-width : 320px)
    and (max-device-width : 720px) {
    #container {
        width: 100% !important;
        }
    }

A: change your code to -
@media only screen
and (min-width : 320px)
and (max-width : 720px) {
#container {
    width: 100% !important;
    }
}

alternately you can keep your previous code and check the responsive nature of your website in local computer by Mozilla Responsive Design View feature - shortcut 'Control+Shift+M'

A: If you are using attribute: max-device-width or min-device-width, it will work only on devices with that width and will ignore the manual browser resizing.
You should change the attribute to: max-width / min-width.
@media screen and (min-width: 1024px){
  /* some CSS here */
}

Check here:

In CSS media the difference between width and device-width can be a bit
muddled, so lets expound on that a bit. device-width refers to the
width of the device itself, in other words, the screen resolution of
the device.

http://www.javascriptkit.com/dhtmltutors/cssmediaqueries2.shtml


text:
Q: What do I need to manipulate to get my status bars in the correct position? Hi I'm a newb at html and css. Also using bootstrap4. I'm trying to get a couple status bars around my pip boy. I am trying to make them look like the first image, but I am having trouble getting them to look like that. What do I need to adjust in order to move the status bars closer to the pip boy? Margin, padding, or border?

html

                            special

                            perks

stylesheet
@font-face{
    font-family: Pipboy;
    src:url('../monofonto.ttf');
}

body{
    font-family:Pipboy, sans-serif;
    color:#14fe17;
    background-color: #292f26 !important;
}

body::after{
    height:100%;
    width: 100%;
    content:"";
    position: absolute;
    top: 0px;
    left:0px;
    background:repeating-linear-gradient(0deg, rgba(0,0,0,.5), rgba(0,0,0,.04) 1px, transparent 1px, transparent 2px);
    opacity: .3;
    z-index: 1000000;
    pointer-events:none;

}

.navbar{
    border-bottom:2px solid;
    margin:0px 10px;
}

.navbar.navbar-light::before, .navbar.navbar-light::after{
    height: 5px;
    width: 2px;
    content: "";
    position: absolute;
    display: block;
    z-index: 5000;
    background:#14fe17;;
    bottom: -7px;
}

.navbar::before {
    left:0px;
}

.navbar::after{
    right:0px;
}

ul > li.nav-item > a.nav-link, ul > li.navbar-item.active > a.nav-link {
    color:#14fe17 !important;
    font-size: 32px;
    line-height: 22px;
    padding-bottom: 0px;
}

.navbar-item.active::before{
    content: "";
    position: absolute;
    background: #f00;
    width: 100%;
    height: 26px;
    top: 14px;
    background: #272b23;
    border-left: 2px solid;
    border-right: 2px solid;
    border-top: 2px solid;
    left: 0px;

}

.navbar-light .navbar-nav > li.navbar-item.active > .nav-link{
    text-align: center;
    width: 100%;
    margin: auto;
    font-size: 32px;
    line-height: 22px;
    padding-bottom: 0px;
    z-index: 50;
    position: relative;
    background: #262b23
}

.navbar-nav{
    width:100%;
}

.navbar-light ul.navbar-nav > li {
    display: block;
    position: relative;
    width: 10%;
}

.center-image{
    position:absolute;
    margin-left: 400px;
}

.center-image img{

    margin: auto;
    display: block;
    position: relative;
    max-height: 300px;
    margin-top: 100px;
    filter:grayscale(1)sepia(100%)hue-rotate(55deg)saturate(7)brightness(1)contrast(2);
}

.pip-footer{
    position: fixed;
    bottom: 0;
    width: calc(100% - 20px);
    margin: 0px;
}

.navbar.navbar-light .navbar-nav{
    margin: 0px 200px;
}

.navbar.navbar-light .navbar-nav > li {
    padding: 0px 20px;
}

.nav.nav-tabs{
    margin:20px;
    border-bottom:none;
}

.nav.nav-tabs > .nav-item > .nav-link:hover{
    border:1px solid transparent;
}

.nav.nav-tabs >li>a{

    font-size: 26px !important;
    background: transparent !important;
    border: 1px solid transparent !important;
    padding: 5px 10px;
}

.nav.nav-tabs > li:nth-child(2) >a {
    opacity: .5;
}

.nav.nav-tabs > li:nth-child(3) >a {
    opacity: .2;
}

.level-progress{
    width: 100%;
    height: 10px;
    border: 2px solid;
    display: inline-block;
    width: 70%;
}

.level-progress-indicator{

    height: 6px;
    background: #14fe16;
    position: relative;
    width: 70%;

}

.navbar.navbar-light.pip-footer{
    border:none;
}

.navbar.pip-footer .col-3, .navbar.pip-footer .col-6{
    background: rgba(16, 255, 0, 0.15);
}

.navbar.pip-footer .col-6{
    margin:0px 5px ;
    flex: 0 0 48% ;
}

.stat-bar {
    width: 60px;
    margin: auto;

}

#status P{
    max-width: 400px;
    margin: auto;
}

.stat-bars > .row {
    margin-bottom: 125px;
}

A: You could change your col-6 to a lower number, then center the columns within the row by adding justify-content-center class to the row.
https://getbootstrap.com/docs/4.0/layout/grid/#variable-width-content


text:
Q: PHP 5.3 to PHP7 - Undefined class constant 'self::MYCONST' I have a project running on PHP 5.3.21 that I am trying to migrate to PHP 7.0.
The project uses a lot the structure as in the example below:
<?php
class foo {
    protected $_const = self::MYCONST;
}

class boo extends foo {
    const MYCONST = "test";

    public function __construct() {
        echo $this->_const.PHP_EOL;
    }
}
new boo();

The expected result is printing "test", and it works perfectly on 5.3, but on 7.0 I get

PHP Fatal error:  Uncaught Error: Undefined class constant
  'self::MYCONST'

Any help will be highly appreciated

A: Try to transfer the constants to the parent classes in your project


text:
Q: C# Selenium Xpath I am trying to select a an element from a DOM but I am struggling with. Basically i am trying to select a title attribute that contains some text. Below is a section of the DOM I am interegating:-

So I am trying to select the 'img' element with a 'title' attribute that contains the text 'AndyShort'. I have tried this but it doesnt work:-
//div[@id='map']/div[1]/div[2]/div[3]/img[contains(text(),'AndyShort')]

Also,
//div[@id='map']/div[1]/div[2]/div[3]/img[@title contains(text(),'AndyShort')]

Can anybody help?

A: You should check Title attribute
//img[contains(@title, 'AndyShort')]


text:
Q: Multi-class classification for large database (matlab) Can you suggest any implementation (matlab) of Multi-class classification algorithm for large database, I tried libsvm it's good except for large database and for the liblinear I can't use it for the multi classification

A: If you want to use liblinear for multi class classification, you can use one vs all technique. For more information Look at this.
But if you have large database then use of SVM is not recommended. As Run time complexity of SVM is O(N * N * m)
N = number of samples in data
m = number of features in data
So, alternatively You can use Neural Network. You can start with nntool available in MATLAB.


text:
Q: Eclipse Leshan server and client with secure keys fails with RequestTimeoutException The LeshanStandalone.java and LeshanClientExample.java that come with the Leshan source code are not setup with secure client connections.
So I borrowed some code from SecurityTest.java and SecureIntegrationTestHelper.java to setup the server and client.
My modified LeshanStandalone code:
public class LeshanStandalone {

    private static final Logger LOG = LoggerFactory.getLogger(LeshanStandalone.class);

    private Server server;
    private LeshanServer lwServer;

    public void start() throws NonUniqueSecurityInfoException {

        // Build LWM2M server
        LeshanServerBuilder builder = new LeshanServerBuilder();
        builder.setLocalAddress(new InetSocketAddress(InetAddress.getLoopbackAddress(), 5683));
        builder.setLocalAddressSecure(new InetSocketAddress(InetAddress.getLoopbackAddress(), 5684));

        // Get public and private server key
        PrivateKey privateKey = null;
        PublicKey publicKey = null;

        try {
            // Get point values
            byte[] publicX = DatatypeConverter
                    .parseHexBinary("fcc28728c123b155be410fc1c0651da374fc6ebe7f96606e90d927d188894a73");
            byte[] publicY = DatatypeConverter
                    .parseHexBinary("d2ffaa73957d76984633fc1cc54d0b763ca0559a9dff9706e9f4557dacc3f52a");
            byte[] privateS = DatatypeConverter
                    .parseHexBinary("1dae121ba406802ef07c193c1ee4df91115aabd79c1ed7f4c0ef7ef6a5449400");

            // Get Elliptic Curve Parameter spec for secp256r1
            AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
            algoParameters.init(new ECGenParameterSpec("secp256r1"));
            ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

            // Create key specs
            KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)),
                    parameterSpec);
            KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec);

            // Get keys
            publicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec);
            privateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec);

            builder.setSecurityRegistry(new SecurityRegistryImpl(privateKey, publicKey));
        } catch (InvalidKeySpecException | NoSuchAlgorithmException | InvalidParameterSpecException e) {
            LOG.warn("Unable to load RPK.", e);
        }

        lwServer = builder.build();

        lwServer.getSecurityRegistry().add(SecurityInfo.newPreSharedKeyInfo("lwm2mClient", "testclient", DatatypeConverter.parseHexBinary("73656372657450534b")));
        lwServer.start();

        // Now prepare and start jetty
        String webPort = System.getenv("PORT");
        if (webPort == null || webPort.isEmpty()) {
            webPort = System.getProperty("PORT");
        }
        if (webPort == null || webPort.isEmpty()) {
            webPort = "8080";
        }
        server = new Server(Integer.valueOf(webPort));
        WebAppContext root = new WebAppContext();
        root.setContextPath("/");
        root.setResourceBase(this.getClass().getClassLoader().getResource("webapp").toExternalForm());
        root.setParentLoaderPriority(true);
        server.setHandler(root);

        // Create Servlet
        EventServlet eventServlet = new EventServlet(lwServer);
        ServletHolder eventServletHolder = new ServletHolder(eventServlet);
        root.addServlet(eventServletHolder, "/event/*");

        ServletHolder clientServletHolder = new ServletHolder(new ClientServlet(lwServer));
        root.addServlet(clientServletHolder, "/api/clients/*");

        ServletHolder securityServletHolder = new ServletHolder(new SecurityServlet(lwServer.getSecurityRegistry()));
        root.addServlet(securityServletHolder, "/api/security/*");

        ServletHolder objectSpecServletHolder = new ServletHolder(new ObjectSpecServlet());
        root.addServlet(objectSpecServletHolder, "/api/objectspecs/*");

        // Start jetty
        try {
            server.start();
        } catch (Exception e) {
            LOG.error("jetty error", e);
        }
    }

    public void stop() {
        try {
            lwServer.destroy();
            server.stop();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws NonUniqueSecurityInfoException {
        new LeshanStandalone().start();
    }
}

my modified LeshanClientExample.java:
public class LeshanClientExample {
    private String registrationID;

    public static void main(final String[] args) throws Exception {
        if (args.length != 4 && args.length != 2) {
            System.out
                    .println("Usage:\njava -jar target/leshan-client-example-*-SNAPSHOT-jar-with-dependencies.jar [ClientIP] [ClientPort] ServerIP ServerPort");
        } else {
            if (args.length == 4)
                new LeshanClientExample(args[0], Integer.parseInt(args[1]), args[2], Integer.parseInt(args[3]));
            else
                new LeshanClientExample("0", 0, args[0], Integer.parseInt(args[1]));
        }
    }

    public LeshanClientExample(final String localHostName, final int localPort, final String serverHostName,
                               final int serverPort) throws Exception {

        // Initialize object list
        ObjectsInitializer initializer = new ObjectsInitializer();
        initializer.setClassForObject(3, Device.class);
        List<ObjectEnabler> enablers = initializer.createMandatory();

        // Create client
        final InetSocketAddress clientAddress = new InetSocketAddress(localHostName, localPort);
        final InetSocketAddress serverAddress = new InetSocketAddress(serverHostName, serverPort);

        CoapServer serverLocal = new CoapServer();

        // Get point values
        byte[] publicX = DatatypeConverter
                .parseHexBinary("fcc28728c123b155be410fc1c0651da374fc6ebe7f96606e90d927d188894a73");
        byte[] publicY = DatatypeConverter
                .parseHexBinary("d2ffaa73957d76984633fc1cc54d0b763ca0559a9dff9706e9f4557dacc3f52a");
        byte[] privateS = DatatypeConverter
                .parseHexBinary("1dae121ba406802ef07c193c1ee4df91115aabd79c1ed7f4c0ef7ef6a5449400");

        // Get Elliptic Curve Parameter spec for secp256r1
        AlgorithmParameters algoParameters = AlgorithmParameters.getInstance("EC");
        algoParameters.init(new ECGenParameterSpec("secp256r1"));
        ECParameterSpec parameterSpec = algoParameters.getParameterSpec(ECParameterSpec.class);

        // Create key specs
        KeySpec publicKeySpec = new ECPublicKeySpec(new ECPoint(new BigInteger(publicX), new BigInteger(publicY)),
                parameterSpec);
        KeySpec privateKeySpec = new ECPrivateKeySpec(new BigInteger(privateS), parameterSpec);

        // Get keys
        PublicKey serverPublicKey = KeyFactory.getInstance("EC").generatePublic(publicKeySpec);
        PrivateKey serverPrivateKey = KeyFactory.getInstance("EC").generatePrivate(privateKeySpec);
        DTLSConnector dtlsConnector = new DTLSConnector(serverAddress);
        dtlsConnector.getConfig().setPreferredCipherSuite(CipherSuite.TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8);
        dtlsConnector.getConfig().setPskStore(new StaticPskStore("testclient", DatatypeConverter.parseHexBinary("73656372657450534b")));
        dtlsConnector.getConfig().setPrivateKey(serverPrivateKey, serverPublicKey);
        dtlsConnector.getConfig().setRequireClientAuth(true);

        serverLocal.addEndpoint(new CoAPEndpoint(dtlsConnector, NetworkConfig.getStandard()));

        final LeshanClient client = new LeshanClient(clientAddress, serverAddress, serverLocal, new ArrayList<LwM2mObjectEnabler>(
                enablers));

        // Start the client
        client.start();

        // Register to the server provided

        RegisterResponse response = client.send(new RegisterRequest("lwm2mClient"));

        // Report registration response.
        System.out.println("Device Registration (Success? " + response.getCode() + ")");
        if (response.getCode() == ResponseCode.CREATED) {
            System.out.println("\tDevice: Registered Client Location '" + response.getRegistrationID() + "'");
            registrationID = response.getRegistrationID();
        } else {
            // TODO Should we have a error message on response ?
            // System.err.println("\tDevice Registration Error: " + response.getErrorMessage());
            System.err.println("\tDevice Registration Error: " + response.getCode());
            System.err
                    .println("If you're having issues connecting to the LWM2M endpoint, try using the DTLS port instead");
        }

        // Deregister on shutdown and stop client.
        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                if (registrationID != null) {
                    System.out.println("\tDevice: Deregistering Client '" + registrationID + "'");
                    client.send(new DeregisterRequest(registrationID));
                    client.stop();
                }
            }
        });
    }

    public static class Device extends BaseInstanceEnabler {

        public Device() {
            // notify new date each 5 second
            Timer timer = new Timer();
            timer.schedule(new TimerTask() {
                @Override
                public void run() {
                    fireResourceChange(13);
                }
            }, 5000, 5000);
        }

        @Override
        public ValueResponse read(int resourceid) {
            System.out.println("Read on resource " + resourceid);
            switch (resourceid) {
                case 0:
                    return new ValueResponse(ResponseCode.CONTENT, new LwM2mResource(resourceid,
                            Value.newStringValue(getManufacturer())));
                case 1:
                    return new ValueResponse(ResponseCode.CONTENT, new LwM2mResource(resourceid,
                            Value.newStringValue(getModelNumber())));
                case 2:
                    return new ValueResponse(ResponseCode.CONTENT, new LwM2mResource(resourceid,
                            Value.newStringValue(getSerialNumber())));
                case 3:
                    return new ValueResponse(ResponseCode.CONTENT, new LwM2mResource(resourceid,
                            Value.newStringValue(getFirmwareVersion())));
                case 9:
                    return new ValueResponse(ResponseCode.CONTENT, new LwM2mResource(resourceid,
                            Value.newIntegerValue(getBatteryLevel())));
                case 10:
                    return new ValueResponse(ResponseCode.CONTENT, new LwM2mResource(resourceid,
                            Value.newIntegerValue(getMemoryFree())));
                case 13:
                    return new ValueResponse(ResponseCode.CONTENT, new LwM2mResource(resourceid,
                            Value.newDateValue(getCurrentTime())));
                case 14:
                    return new ValueResponse(ResponseCode.CONTENT, new LwM2mResource(resourceid,
                            Value.newStringValue(getUtcOffset())));
                case 15:
                    return new ValueResponse(ResponseCode.CONTENT, new LwM2mResource(resourceid,
                            Value.newStringValue(getTimezone())));
                case 16:
                    return new ValueResponse(ResponseCode.CONTENT, new LwM2mResource(resourceid,
                            Value.newStringValue(getSupportedBinding())));
                default:
                    return super.read(resourceid);
            }
        }

        @Override
        public LwM2mResponse execute(int resourceid, byte[] params) {
            System.out.println("Execute on resource " + resourceid + " params " + params);
            return new LwM2mResponse(ResponseCode.CHANGED);
        }

        @Override
        public LwM2mResponse write(int resourceid, LwM2mResource value) {
            System.out.println("Write on resource " + resourceid + " value " + value);
            switch (resourceid) {
                case 13:
                    return new LwM2mResponse(ResponseCode.NOT_FOUND);
                case 14:
                    setUtcOffset((String) value.getValue().value);
                    fireResourceChange(resourceid);
                    return new LwM2mResponse(ResponseCode.CHANGED);
                case 15:
                    setTimezone((String) value.getValue().value);
                    fireResourceChange(resourceid);
                    return new LwM2mResponse(ResponseCode.CHANGED);
                default:
                    return super.write(resourceid, value);
            }
        }

        private String getManufacturer() {
            return "Leshan Example Device";
        }

        private String getModelNumber() {
            return "Model 500";
        }

        private String getSerialNumber() {
            return "LT-500-000-0001";
        }

        private String getFirmwareVersion() {
            return "1.0.0";
        }

        private int getBatteryLevel() {
            final Random rand = new Random();
            return rand.nextInt(100);
        }

        private int getMemoryFree() {
            final Random rand = new Random();
            return rand.nextInt(50) + 114;
        }

        private Date getCurrentTime() {
            return new Date();
        }

        private String utcOffset = new SimpleDateFormat("X").format(Calendar.getInstance().getTime());
        ;

        private String getUtcOffset() {
            return utcOffset;
        }

        private void setUtcOffset(String t) {
            utcOffset = t;
        }

        private String timeZone = TimeZone.getDefault().getID();

        private String getTimezone() {
            return timeZone;
        }

        private void setTimezone(String t) {
            timeZone = t;
        }

        private String getSupportedBinding() {
            return "U";
        }
    }
}

The server starts ok, but the client starts on 5684 with a RequestTimeoutException, and the server prints:
May 19, 2015 2:47:04 PM org.eclipse.californium.scandium.dtls.Record fromByteArray
WARNING: Received illegal record content type: 68
May 19, 2015 2:47:07 PM org.eclipse.californium.scandium.dtls.Record fromByteArray
WARNING: Received illegal record content type: 68

What have i done wrong or missing?


text: Q: Xamarin.Android app with MvvmCross and Pixate I am currently experimenting with Pixate, trying to add to our existing app that is built with Xamarin.Android and uses MvvmCross.  Without Pixate, the app works correctly.  As soon as I make the init call for Pixate, Mvvmcross will throw null exceptions in MvxSpinner method calls, and the app doesn't seem to bind to the list view or spinner.  I am wondering if there is anyone that has a working Xamarin Android application that uses both Mvvmcross and Pixate, it seems to me there's a conflict going on between the two libraries.  Just wanted to confirm and see if anyone else experience similar issues.  Thanks!


text:
Q: Reading bytes into Go buffer with a fixed stride size I'd like to read and process 1024 bytes at a time in my file given by filename. I don't understand how to construct the outer loop correctly, especially to accommodate the final stride in which the buffer will contain fewer than 1024 bytes
What I have tried:
fs, _ := os.Open(filename)
defer fs.Close()
n := 1024 // 1kb
buff := make([]byte, n)
for {
    buff = make([]byte, n) // is this initialized correctly?
    n1, err := fs.Read(buff)
    if err != nil {
        if err == io.EOF {
            break
        }
        fmt.Println(err)
        break
    }
    fmt.Println("read n1 bytes...", n1)
    fmt.Println(buff)
}

I have seen the following resources:

*

*Reading specific number of bytes from a buffered reader in golang

*Read arbitrary amount of bytes into buffer Golang

*How to read a binary file in Go

*Working with raw bytes from a network in go

*https://gobyexample.com/reading-files

*Writing into fixed size Buffers in Golang with offsets

*https://rwinslow.com/posts/use-flatbuffers-in-golang/

*reading file line by line in go

*How do I read in a large flat file in Golang

*https://golang.org/pkg/io/#ReadFull

A:
Reading bytes into Go buffer with a fixed stride size
read and process 1024 bytes at a time in my file given by filename.
accommodate the final stride in which the buffer will contain fewer
  than 1024 bytes.

For number of bytes read guarantees, use ioutil.ReadFull. For efficient stream reads, use bufio.Reader. For efficiency, allocate the read buffer once and reuse it.
For example,
package main

import (
    "bufio"
    "fmt"
    "io"
    "io/ioutil"
    "os"
)

func main() {
    stride := 1024
    filename := testname(stride)

    f, err := os.Open(filename)
    if err != nil {
        fmt.Fprintln(os.Stderr, err)
        return
    }
    defer f.Close()

    r := bufio.NewReader(f)
    buf := make([]byte, 0, stride)
    for {
        n, err := io.ReadFull(r, buf[:cap(buf)])
        buf = buf[:n]
        if err != nil {
            if err == io.EOF {
                break
            }
            if err != io.ErrUnexpectedEOF {
                fmt.Fprintln(os.Stderr, err)
                break
            }
        }

        fmt.Println("read n bytes...", n)
        // process buf
    }
}

func testname(stride int) string {
    f, err := ioutil.TempFile("", "test.stride.")
    if err != nil {
        panic(err)
    }
    defer f.Close()
    _, err = f.Write(make([]byte, 2*stride+stride/2))
    if err != nil {
        panic(err)
    }
    return f.Name()
}

Playground: https://play.golang.org/p/iYOY-z7hkoz
Output:
read n bytes... 1024
read n bytes... 1024
read n bytes... 512


text:
Q: Understanding the Ruby mixin's proxy class mechanism I am refering to the follwing article, paragaph "Pitfall #1": http://definingterms.com/2013/03/23/pitfalls-of-ruby-mixins/
I've got the following setup, a slightly changed form of the one used in the article:
module EmailReporter
    def send_report
        #Sending a report ...
        puts self.class
    end
end

class Person
end

class Employee < Person
    include EmailReporter
end

As I understand, when I include EmailReporter in Employee, its methods are not just pasted into it, but a anonymous proxy class is created and put into the inheritance chain above Employee and under Person.
When I call Employee.new.send_report, I am not in the scope of Employee, but in the scope of the proxy class. Thus, I would not have access to constants or class variables of Employee, but I would have access to instance variables.
Questions:

*

*If I run Employee.new.send_report, the output is "Employee", but not something like "Employee__proxy_class". Why is that? Shouldn't "self" refer to the proxy class?

*The article suggest the proxy class delegates method calls to the Module EmailReport. But of course you cannot just call instance methods on it. So whom does the proxy class delegate its calls to?
Thanks to everyone trying to answer my question!

A: I think your fundamental problem is in understanding the value of self. Often it's helpful to just add code that tells you what self is at different points of your code. Let's begin with a very simple example:
class Dad
  def hi
    puts "self in Dad#hi = #{self}"
  end
end

class Son < Dad
end

son = Son.new
  #=> #<Son:0x007fc1f2966b88>
son.methods.include?(:hi)
  #=> true
son.hi
  # self in Dad#hi = #<Son:0x007fc1f2966b88>

Just because:
son.method(:hi).owner
  #=> Dad

does not mean self is changed when hi is invoked on self. Now let's include a mixin:
module Helper
  def hi
    puts "self in Helper#hi = #{self}"
  end
end

Son.include Helper

son.hi
  # self in Helper#hi = #<Son:0x007fc1f29551d0>
son.method(:hi).owner
  #=> Helper

I think you understand why Helper#hi was invoked here rather than Dad#hi.
Does this answer your first question? I don't understand the second question, but perhaps you can answer it yourself now that you've been enlightened on self. If not, please clarify #2 (with an edit to your question).


text:
Q: Matching two columns in Apps Script / JavaScript with a specific condition I'm working on matching a pair from a list of names in Apps Script but there's a condition attached to it which I'm trying to figure out.

Names1
Names2

Glen
Adam

John
Matthew

Mitch
Damien

Daryl
Jason

Steve
Shane

Ricky
Stuart

Here's the Google sheets link explaining the input and the expected output - https://docs.google.com/spreadsheets/d/1nwu5j2ae_NQAmNQ5WlC-etd12lYMr4FDNKt3iAIjq4w/edit?usp=sharing
Checkout inline comments in cells A2 and D1
In the above example, Glen from Names1 column is mapped to Adam in Names2 column. I wish to write a randomization matching code where Glen gets mapped with every other person from Names1 and Names2 column without any repeating matches. This is what I have tried so far -
Method 1:
Use a simple randomize() function but repeating matching occurs at a higher frequency
Method 2:
Using a custom shuffle function
function shuffleArray(range) {
     var i,j,temp;
     for (i=range.length-1; i>0; i--) {
         j = Math.floor(Math.random()*(i+1));
         temp = range[i];
         array[i] = array[j];
         array[j] = temp;
     }
     return range;
}

Unfortunately, this method also shows repeated matching but at a very less rate and it does not do an exhaustive matching with every other person in both the lists.
Any help would be really appreciated. Thanks!

A: You could store what you already get in an array and everytime you get a pair check first if the array does not already contain the pair you found. If you want every possible pair, without duplicates you can do something like this:
const found = [];
for(let i=0; i<range.length; i++){
  for(let j=i+1; j<range.length; j++){
    const str = `${range[i]}_${range[j]}`;
    if(!found.includes(str)){
      found.push(str);
    }
  }
}

A: Solution1
function solution1() {

  const sheet = SpreadsheetApp.getActiveSpreadsheet()
                              .getSheetByName(`Solution1`)

  const personsList = sheet.getRange(`A3:A`)
                           .getValues()
                           .filter(String)
                           .flat()

  const teamsGenerated = sheet.getRange('C3:3')
                              .getValues()
                              .flat()
                              .filter(String)
                              .length

  let newTeam
  if (teamsGenerated) {

    const previousTeams = sheet.getRange(3, 3, personsList.length, teamsGenerated)
                               .getValues()

    newTeam = randomize(personsList)
    while (previousTeams.some((i, index) => i.includes(newTeam[index]))) {
      newTeam = randomize(personsList)
    }

    sheet.getRange(3, 3+teamsGenerated, newTeam.length)
         .setValues(newTeam.map(i => [i]))

  } else {

    newTeam = randomize(personsList)
    sheet.getRange(3, 3+teamsGenerated, newTeam.length)
         .setValues(newTeam.map(i => [i]))

  }

}

function randomize(array) {

  for (let i = array.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [array[i], array[j]] = [array[j], array[i]];
  }

  return array

}

Taking all names from the first column, we see if there are already teams generated. If there are teams found, generate a new team where no player is in the same position as previous teams until found; then insert in next available column. If there are no teams found, insert a randomized team.

A:
Glen gets mapped with every other person from Names1 and Names2 column without any repeating matches

It is unclear why you want to do this in Apps Script, because a plain vanilla spreadsheet formula should suffice. You can map each name to every other name in a random order like this:
=transpose( { A3; sort( filter( A$3:A, len(A$3:A), A$3:A <> A3 ), randarray( counta( filter( A$3:A, len(A$3:A), A$3:A <> A3 ) ) ), true ) } )
See the new Solution1 sheet in your sample spreadsheet. To get another iteration, click the checkbox in cell D2.

The expected output is just one iteration. Next time when I run the code, I expect to see a different set of pairing for each of the individual without repetition. Team 1, Team 2

That sounds like a different question, but you can divide the names in A3:A into the number of teams given in B3 with this formula in cell C3:
=arrayformula(
  query(
    query(
      iferror(
        if(
          { 1, 1, 0 },
          floor( mod( sequence(counta(A2:A)) - { 1, 1 }, { 9^9, B3 } ), { B3, 1 } ),
          transpose( split( regexreplace( query( transpose( query(
            transpose( sort( A3:A, if( len(A3:A), randbetween( sign(row(A3:A)), 9^9 ), iferror(1/0) ), true ) & char(9) ),
            "", 9^9 ) ), "", 9^9 ), "\s+$", "" ), char(9) & " ", false, true ) )
        )
      ),
      "select max(Col3) where Col3 <> '' group by Col1 pivot Col2", 0
    ),
    "offset 1", 0
  )
)

The formula will create a table that lists teams, one team per column, with the names divided randomly into teams, with no names repeating.
See the new Solution2 sheet in your sample spreadsheet. To get random division into teams, click the checkbox in cell B5.


text:
Q: Edit a cell value with a Form (Appscript in Gsheet) Good morning,
I am building a form to handle a database in appscript.
I got some script from a similar past project so I might lack references but I can't find any ... (sorry)
The functions I already coded are:

*

*Create a line in the database

*Search a line in the database

*Select and open a form with the prefilled data of the line

The function I am trying to code is :

*

*Save the edited field in the original column

I am having troubles making this work, I always end up with nothing, no error message, just nothing !
Data looks like that :

ID
Field 1
Field 2
Field 3
Field 4

01
01-1
02-1
03-1
04-1

02
01-2
02-2
03-2
04-2

03
01-3
02-3
03-3
04-3

04
01-4
02-4
03-4
04-4

What I want to see if I EDIT line ID 03 :

ID
Field 1
Field 2
Field 3
Field 4

01
01-1
02-1
03-1
04-1

02
01-2
02-2
03-2
04-2

03
[EDIT 01-3]
[EDIT 02-3]
[EDIT 03-3]
[EDIT 04-3]

04
01-4
02-4
03-4
04-4

And here is my code (simplified version for lisibility):
In the HTML Form used for edition
<!DOCTYPE html>

      <button id="edit" onclick="Edit();Fill()">Edit</button>

    <form id="myForm" onsubmit="handleFormSubmit2(this)">

        Field 1 :
        <textarea type="text" id="Field1Edit" name="Field1Edit"></textarea>

        Field 2:
        <textarea type="text" id="Field2Edit" name="Field2Edit"></textarea>

        Field 3:
        <textarea type="text" id="Field3Edit" name="Field3Edit"></textarea>

        Field 4 :
        <textarea type="text" id="Field4Edit" name="Field4Edit"></textarea>

      <button id="Submit" onclick="EditVal()">Submit</button>

    </form>

And this is the script for "ProcessForm2" :
/* Process Form and replace data in the Sheet */
function processForm2(formObject) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Tracker");

  var mylist = [formObject.Field1,formObject.Field2,formObject.Field3,formObject.Field4];
  var cell = 0; /* Start of the range of modified cells */

  // Add data after the opening ones in the corresponding row
  for (var i=0; i<mylist.length; i++){
    if ((mylist[i]).length > 0){sheet.getRange(formObject.num,cell).setValue(mylist[i])}
    cell++;
  }

}

When I submitted the form I just got my fields to reset and nothing happened
*In my opinion, the issue is located in EditVal() or the order it is trigger.
I tried to trigger it that way too, not working*
    <form id="myForm" class="form" onsubmit="EditVal(); handleFormSubmit2(this)">

I'd appreciate some help,
Thank you in advance !

A: It might be easier

if you add a field to the database that is called has_been_edited and is true or false, then you can just right to that field and test for it to be true. Hope this can help I am not familiar with appscript.

A: Hello,
Thank you @TheMaster for the answer,
Indeed, I forgot
<input type="hidden" id="num" name="num">

In my form.
Thank you @Emel and @Wayne too for your help !
Here is the modified code :
<!DOCTYPE html>

      <button id="edit" onclick="Edit();Fill()">Edit</button>

    <form id="myForm" onsubmit="handleFormSubmit2(this)">

        Field 1 :
        <textarea type="text" id="Field1Edit" name="Field1Edit"></textarea>

        Field 2:
        <textarea type="text" id="Field2Edit" name="Field2Edit"></textarea>

        Field 3:
        <textarea type="text" id="Field3Edit" name="Field3Edit"></textarea>

        Field 4 :
        <textarea type="text" id="Field4Edit" name="Field4Edit"></textarea>

      <input type="hidden" id="num" name="num">

      <button id="Submit" onclick="alert('Your modification(s) have been taken into account !');">Submit</button>

    </form>

And
/* Process Form and replace data in the Sheet */
function processForm2(formObject) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Tracker");

  var mylist = [formObject.Field1,formObject.Field2,formObject.Field3,formObject.Field4];
  var cell = 0; /* Start of the range of modified cells */

  // Add data after the opening ones in the corresponding row
  for (var i=0; i<mylist.length; i++){
    if ((mylist[i]).length > 0){sheet.getRange(formObject.num,cell).setValue(mylist[i])}
    cell++;
  }

}


text:
Q: Azure logic app Update Currency Exchange Rates parameter helps I need to develop the Logic apps to update Currency Exchange Rate.
I do have the Api looks like that
https://api.int.org/rest/default/V1/currency/exchange-rate/?sourceCurrency=USD&destinationCurrency=EUR
The destination currency is dynamic; it would INR,EUR or any other currency.
I want to pass the destination currencies using the parameters.
I need help. How do I need to pass the parameters?
enter image description here

A: All you need to do is add the parameter value in your parameters which enables you to add whenever it is required to build the flow.

Below is how the URI looks when reading from the parameters
https://api.int.org/rest/default/V1/currency/exchange-rate/?sourceCurrency=USD&destinationCurrency=@{parameters('destinationCurrency')}


text:
Q: Rails: passing validations in rake populate rails I have created a rake populate file to build dummy data.
@corp_page = CorporatePage.create(title: 'Home', static_descriptor: 'Home')
    @panel_count = CorporatePanel::PANEL_TYPE.count
    if @corp_page.title == 'Home'
         ----
    else
      puts "Corp Page not saved"
      puts @corp_page.inspect
    end

On inspect it appears my validations are preventing the instance being made. Why?
Freddys-MacBook-Pro:gll_corporate McGroarty$ rake db:populate
 not saved
#<ActiveModel::Errors:0x007fdb2f5162f8 @base=#<CorporatePage id: nil, title: nil, static_descriptor: nil, workflow_state: "draft", created_at: nil, updated_at: nil>, @messages={:title=>["can't be blank"]}>

The values are exactly as validated for. Why isn't this working?
CorpPage model
# == Schema Information
#
# Table name: corporate_pages
#
#  id                :integer          not null, primary key
#  title             :string(255)
#  static_descriptor :string(255)
#  workflow_state    :string(255)      default("draft")
#  created_at        :datetime
#  updated_at        :datetime
#

class CorporatePage < ActiveRecord::Base

    HOME_PAGE='Home'
    PAGE_TYPES=[HOME_PAGE]

    has_many :corporate_panels

    validates_presence_of :title
  validates :static_descriptor, inclusion: PAGE_TYPES

Rails 4
Thanks

A: Rails prevents mass assignment of variables by default
With rails 4, as far as I know, you can add this line to your application's Gemfile:
gem 'protected_attributes'

execute
bundle install

from the command line
and in your model put
attr_accessible :title, :static_descriptor

this way you're whitelisting the attributes you allow to be mass assigned.
Actually it used to be a default functionality but has been deprecated, I'm still learnng the new 'right way' :)
I would have commented as my answer is definitely missing a lot but I'm still not allowed to. (50 reputation to comment)


text:
Q: Difference between torque and speed in dc motor? I have knowledge about the definitions about both speed as well as of the torque. But I am unable to think dc motors in terms of speed and torque. When the armature of a dc motor rotates , we call it torque because of rotational movement about the fixed axis. So where is speed?

A: Torque is how hard you push, and speed is how fast it goes.
In a electric motor, torque is proportional to current, regardless of the applied voltage.
Think of a motor as the coils that cause the torque in series with a voltage source.  The coils are always the same, and the torque produced by the magnetic interactions inside the motor are always proportional to the current thru these coils.  Here is a useful first order simplified model of a motor:

L1 and R1 represent the part of the motor that produces torque proportional to current.  V1 is the motor acting as a generator.  When the motor is spinning due to applied voltage, then V1 opposes that voltage.  The voltage applied across the torque-producing part of the motor is therefore V+ - V1.  This means the faster the motor goes in the direction you are trying to spin it, the less voltage is avaiable to drive the motor, therefore less current is drawn, and less torque developed.  In steady state, the motor goes fast enough so that V1 cancels out just enough applied voltage to leave the exact amount applied to L1 and R1 to produce the torque to spin it at the speed it is going at.
For example, let's say you have a small DC motor that is not mechanically connected to anything (unloaded).  Let's say the motor is rated for 10 V.  When you first apply 10 V, the motor is not moving, so V1 is 0, and all of that 10 V is applied across L1-R1.  This causes current of 2 A thru the motor, which causes torque, which makes the motor speed up.  As it speeds up, V1 increases.  After a few seconds the motor speed stabalizes and stops increasing.  You now measure only 200 mA with the same 10 V applied, and the motor is running at 80 Hz (4800 RPM).
Since the current is now 1/10 what it was originally when the motor was not spinning, called the stall current, you know that 1/10 the original voltage is applied across L1-R1, which is 1 V.  That means the motor is internally generating 9 V.  From that you can compute the generator constant, which is (9 V)/(80 Hz) = 113 mV/Hz.  You also now know that 1 V across L1-R1 is what is needed to just counter friction and other losses in the motor at 80 Hz.
If you were to externally spin the motor at 80 Hz you would measure a open-circuit voltage of 9 V.  You would need to spin it at 89 Hz to get 10 V out.  If you applied the 10 V while spinning it at 89 Hz, no current would flow.  If you then disconnected the shaft from whatever was driving it, the motor would start slowing down.  This is because is it has some friction.  As it slows down, the V1 voltage goes down, so some voltage is applied across L1-R1, which causes current, which produces torque to keep the motor going.  Initially that current is too small to produce enough torque to keep the motor going at the existing speed, so the motor slows down more.  That reduces V1, which increases the voltage on L1-R1, which increases the current, which increases the torque.  Eventually it will reach equillibrium at 80 Hz and 200 mA, just like before.  If the motor were to go slower, V1 would drop, the voltage on L1-R1 would increase, current would increase, more torque would be generated, and the motor would speed up.  The reverse happens if the motor were to go faster.

A:
When the armature of a dc motor rotates , we call it torque because of
  rotational movement about the fixed axis. So where is speed?

We don't call it torque, we call it speed aka rpm or rotational speed.
The force that it takes to spin at a certain speed we call torque and usually, for a dc motor high speed means low torque and high torque means low speed. Look at this formula for the mechanical power output of a motor: -
Power out = \$2\pi n T\$
Where n is speed in revolutions per second or, if you wish \$2\pi n\$ is radians of rotation per second. and T is torque.
For a constant power out n.T must be constant.


text:
Q: Arduino - Cannot get ECG readings from heart, but I do when I poke at the leads I have a minor issue with my ECG.  When I poke at the leads, I get a reading.  But when I hold the leads or place it near my heart, I don't get anything.  I'm pretty sure this is hardware related, but I don't want to completely rule out a potential software problem.  I used this YouTube video as a guide: https://www.youtube.com/watch?v=NDjRg-KgIXY, with their circuit show below.

My breadboard almost looks exactly the same as that, but with a couple of changes.  Instead of connecting the ECG to the computer via a audio cable, I used Bluetooth to transfer it to my phone.  Here is my schematic diagram.

Here is my breadboard diagram.

In my breadboard, I used three LM358 op-amps.  Here is my Arduino code (if you need it):
const int  signal = 7;    // Pin connected to the filtered signal from the circuit
unsigned long currentBeatTime;
unsigned long previousBeatTime;

unsigned long frequency;

// Internal variables
unsigned long period = 0;
int input = 0;
int lastinput = 0;

void setup() {
pinMode(signal, INPUT);
Serial.begin(9600);

previousBeatTime = millis();
}

void loop() {
delay(100);
input = digitalRead(signal);

if ((input != lastinput) && (input == HIGH)) {
    // If the pin state has just changed from low to high (edge detector)
    currentBeatTime = millis();

    period = currentBeatTime - previousBeatTime; // Compute the time between the previous beat and the one that has just been detected
    previousBeatTime = currentBeatTime; // Define the new time reference for the next period computing
}

lastinput = input; // Save the current pin state for comparison at the next loop iteration

// Detect if there is no beat after more than 2 seconds
if ( (millis() - previousBeatTime) > 2000 )
{
    //Serial.println("dead");
}
else
{
    if (period <= 0)
    {
        frequency = 0;
    }
    else
    {
        frequency = 60000/period; // Compute the heart rate in beats per minute (bpm) with the period in milliseconds
    }

    Serial.println(frequency);
}
}

Any help regarding this issue is highly appreciated.  Thank you!

A: You actually have a major issue.  You're triggering off noise created by dorking with your leads, and not on anything related to the ecg.  This is going to be very difficult to debug without an oscilloscope.  What are you using for electrodes?  Also, a real circuit diagram for the analog portion would be of huge help.
I suggest your input stage should be a modest gain, maybe 10, with an instrumentation amp, then a high pass filter, then a big gain with an op amp and a low pass filter.
The leads don't belong near your heart.  Hold one lead in each hand, and ground your ankle to the same ground you use for vref on the instrumentation amp.
UPDATE:
1) The circuit in the video is not perfectly suitable to amplify biopotentials. You want a DIFFERENTIAL AMPLIFIER, and this amp is single-ended. Interestingly enough, even if this were never intended to be used for biopotentials (there's no suggestion in the vid that it is), its still sort of a textbook example of students using textbook examples and expecting them to work.  They're in the right direction, but there's practical aspects of the circuit that will have a ton of problems.  The 7 MegaOhm resistors will prove to big noise sources if you try to crank up the gain, and also those big resistors will cause large offset voltages to to input bias currents that will saturate gain stages beefy enough to measure ecg signals, which are about .1-5mV in amplitude (so you'd like a gain of about 500 or so).
2) Even if the circuit were OK to measure biopotentials, it wasn't implemented right in this case.
a) Although the op-amps you used are fine to power with a single power supply, you should have a positive and a negative power supply for the purposes you're using them for here.  You can alter the circuit to use a single supply, but that's more work than you want to take on.
b) You can't swap out resistor and capacitor values willy nilly and expect them to work.  As luck would have it, the combo you use on the high pass filter stage seems OK, but you haven't provided enough info for me to know about the low pass stage.
To do this right, you should have a modest gain differential stage that won't saturate for an input offset of about 200mV.  An instrumentation amp (like your INA128) with a gain of 10 would work if you can supply +/- power.  If you need to work with one power supply, then you need an instrumentation amp like the AD623, who's inputs can go below the negative rail, with Vref set at about 2.5V.  Then you need a high pass filter to get rid of the amplified offset.  After that, a stage with a gain of about 50-100 and a low pass cutoff of about 50Hz.  After that, you need some sort of comparator stage to use as a heartbeat detector, but perhaps that's getting a bit too far ahead.
(As an aside, the more modern approach is probably to just have the modest gain first stage and a low-pass filter, then sample it at 24 bit resolution, and do everything after that digitally).
So, bottom line is the circuit you're using won't work, and there's no great way to fix it.  If you're going to try this without an oscilloscope to debug, you're going to need to start with an absolutely bulletproof design, and implement it correctly.
I suggest looking at http://www.eng.utah.edu/~jnguyen/ecg/instructions.html (with the schematic at http://www.eng.utah.edu/~jnguyen/ecg/bigsch.gif) for a differential amplifier that works for this purpose.


text:
Q: The Hilbert-Schmidt Theorem for Compact, Self-adjoint operators Suppose $T$ is a compact, self-adjoint operator on a Hilbert space $\mathcal{H}$. Then there exists an orthonormal set $\{e_n\}_{n=1}^{\infty}$ of eigenvalues of $T$ such that every $x \in \mathcal{H}$ has a unique decomposition of the form $$ x = \sum_{n=1}^{\infty} c_n e_n + y, $$ where $c_n \in \mathbb{C}$ and $y \in \ker(T)$.
The proof I know of the above theorem boils down to showing that $\mathcal{H} = L \oplus \ker(T)$, where $$L = \overline{\text{span}\{e_n\}_{n=1}^{\infty}}.$$
I'm confused about the structure of $L$. How do we know that an element of $L$ (say $z$) looks like $$z = \sum_{n=1}^{\infty} c_n e_n?$$ I thought that, in general, the closure of the span of an infinite set did not coincide with the set of all infinite sums of elements from that set?


text:
Q: How to create XML using PHP and MYSQL with conditional nesting I am attempting to make a TV Guide by using a database to create the XML file via MYSQL and PHP. I have had good success so far and have managed to output the various channels for each day.
The problem is when I try to bring the various programmes in. Within the database, each programme is assigned a day and channel it will be shown on. However, the XML being generated is placing every programme on every channel for every day.
Here is what I have so far:
$xml = new DOMDocument("1.0", "UTF-8");
$xml->formatOutput = TRUE;

$day_query = "SELECT day_name FROM day;";

$dq_result = mysql_query($day_query) or die(mysql_error());

$tvguide = $xml->createElement("guide");
$tvguide = $xml->appendChild($tvguide);

    if($dq_result)
    while($dayrow = mysql_fetch_row($dq_result)){
        $day = $xml->createElement("day");
        $day->setAttribute("name", $dayrow[0]);
        $day = $tvguide->appendChild($day);

        $channel_query = "SELECT channel_ID, channel_Name FROM channel ORDER BY channel_Name ASC;";

        $cq_result = mysql_query($channel_query) or die(mysql_error());

        if($cq_result)
            while($channelrow = mysql_fetch_row($cq_result)){

            $channel = $xml->createElement("channel");
            $channel->setAttribute("id", $channelrow[0]);
            $channel = $day->appendChild($channel);

            $channel_name = $xml->createElement("channel_name");
            $channelNameText = $xml->createTextnode($channelrow[1]);
            $channel_name->appendChild($channelNameText);
            $channel_name = $channel->appendChild($channel_name);

            $show_query = "SELECT programme_ID, programme_Name, start_Time, duration, description, day_Name, channel_Name FROM programme ORDER BY start_Time ASC;";

            $sq_result = mysql_query($show_query) or die(mysql_error());

            if($sq_result)
                while($showrow = mysql_fetch_row($sq_result)){

            $show = $xml->createElement("show");
            $show = $channel->appendChild($show);

            $show_name = $xml->createElement('show_name');
            $show_name->setAttribute("id", $showrow[0]);
            $showNameText = $xml->createTextnode($showrow[1]);
            $show_name->appendChild($showNameText);
            $show->appendChild($show_name);

            }

        }
}

Basically, I want to know how I can nest all the shows whose day_Name is equal to Monday, for example, within the 'Monday' XML tag. Thank you.

A: OK, to answer your question quickly, it be as easy as changing:

$show_query = "SELECT programme_ID, programme_Name, start_Time, duration, description, day_Name, channel_Name FROM programme ORDER BY start_Time ASC;";

Into

$show_query = "SELECT programme_ID, programme_Name, start_Time, duration, description, day_Name, channel_Name FROM programme WHERE day_Name='$dayrow[0]' AND channel_Name='$channelNameText' ORDER BY start_Time ASC;";

However, there are a couple more things to change:

*

*You shouldn't use the mysql_ interface, use either mysqli or PDO_mysql.

*You are doing inside the while a query (SELECT channel_ID, channel_Name FROM channel ORDER BY channel_Name ASC;) which is constant. You probably should make it only once, before the while, and cache its results.


text:
Q: create multiple pdf by id with TCPDF codeigniter good evening ! I need your help, I am trying to generate several PDFs with the TCPDF, I have been able to create a PDF one by one by passing the ID of the database to the function, but what I need is for it to automatically create several PDFs for each ID that it brings from the database, how can I achieve this?
Controller:
public function reportpdf($id){
    ob_start();

        $allowance= $this->allowance_m->get_allowance_byid($id);
        $this->load->library('tcpdf');
        $pdf = new
        TCPDF('P','mm','A4',true,'UTF-8',false);
        $pdf->AddPage();

        $pdf->setXY(12,40);
        $txt_pembuka = 'Allowance Report';
        //$pdf->SetFontSize(16);
        $pdf->SetFont('times', 'B', 16, '', 'false');
        $pdf->MultiCell(0, 5, $txt_pembuka, 0, 'C', 0, 2, '', '', true);

        $pdf->setXY(20,$pdf->getY()+7);
        $pdf->SetFont('times', '', 12, '', 'false');
        $pdf->cell(35,5,"Nama");
        $pdf->cell(0,5,":   ".$allowance->tarjeta);

        $pdf->setXY(20,$pdf->getY()+7);
        $pdf->cell(35,5,"Periode");
        $periode = strtotime($allowance->monto);
        $formatperiode = date('F Y',$periode);
        $pdf->cell(0,5,":   ".$formatperiode);

        $pdf->setXY(20,$pdf->getY()+7);
        $pdf->cell(35,5,"Uang Makan");
        $pdf->cell(0,5,":   Rp.".$allowance->nombre);
        $pdf->Output();

    ob_end_flush();
    }

Model:
public function get_allowance_byid($id)
    {

         $db6 = $this->load->database('db6', TRUE);
        $sql = "SELECT * FROM registros WHERE tarjeta='".$id."'";
        return $db6->query($sql)->row();
    }

A: If you want to create "several PDFs for each ID" it is recommended to first save the created PDF files in a local folder on your server before making them available to your user instead of prompting the created PDF directly in the browser as in your example. It is not practical to send multiple PDFs at once to the browser.
Add a path and a filename to the Output Method to save the PDF, preferably with an ID so you can find it again:
$pdf->Output('allowance_report_'.$id.'.pdf');

Documentation: https://tcpdf.org/docs/srcdoc/TCPDF/classes-TCPDF/#method_Output
In your case, you can either create multiple PDFs inside the method reportpdf() or make a new method for each file.
If you choose to do it inside your current method you can do something like:
public function reportpdf($id){

    $allowance= $this->allowance_m->get_allowance_byid($id);
    $this->load->library('tcpdf');

    //CREATE YOUR FIRST PDF....
    $pdf = new
    TCPDF('P','mm','A4',true,'UTF-8',false);
    $pdf->AddPage();

    ... ETC ...

    // SAVE THE FIRST PDF BY PROVIDING A PATH AND A FILENAME
    $pdf->Output('folder/allowance_report_'.$id.'.pdf');

    //CREATE YOUR SECOND PDF....
    $pdf = new
    TCPDF('P','mm','A4',true,'UTF-8',false);
    $pdf->AddPage();

    ... ETC ...

    // SAVE THE SECOND PDF BY PROVIDING A PATH AND A FILENAME
    $pdf->Output('folder/another_report_'.$id.'.pdf');

}

If you then want to send the PDFs to the browser I suggest you create a zip file containing all the created PDFs and prompt it through the browser.


text:
Q: Given positive $a, b, c$, prove that $(a^2 + b^2 + c^2)^3 \ge (a^3 + b^3 + c^3)(ab + bc + ca)(a + b + c)$.
Given positive $a, b, c$, prove that $$\large (a^2 + b^2 + c^2)^3 \ge (a^3 + b^3 + c^3)(ab + bc + ca)(a + b + c)$$

As a starting point,
$$(a^2 + b^2 + c^2)^3 \ge (a^3 + b^3 + c^3)(ab + bc + ca)(a + b + c)$$
$$\iff \frac{a^2 + b^2 + c^2}{ab + bc + ca} \ge \frac{(a^3 + b^3 + c^3)(a + b + c)}{(a^2 + b^2 + c^2)^2}$$
$$\iff \frac{(a - b)^2 + (b - c)^2 + (c - a)^2}{2(ab + bc + ca)} \ge \frac{ab(a - b)^2 + bc(b - c)^2 + ca(c - a)^2}{(a^2 + b^2 + c^2)^2} \tag 1$$
$$\iff \sum_{cyc}(a - b)^2\left[\frac{1}{2(ab + bc + ca)} - \frac{ab}{(a^2 + b^2 + c^2)^2}\right] \ge 0$$
$$\iff \frac{1}{2} \cdot \sum_{cyc}\frac{[a^4 + b^4 + c^4 + 2(ca)^2 + 2(bc)^2 - 2a^2bc - 2b^2ca](a - b)^2}{(ab + bc + ca)(a^2 + b^2 + c^2)^2} \ge 0$$
$$\iff \frac{\displaystyle (a^4 + b^4 + c^4) \cdot \sum_{cyc}(a - b)^2 + 2\sum_{cyc}ca(ca - b^2)[(a - b)^2 + (b - c)^2]}{(ab + bc + ca)(a^2 + b^2 + c^2)^2} \ge 0$$
Please note for $(1)$ that $$(a^2 + b^2 + c^2) - (ab + bc + ca) = \frac{(a - b)^2 + (b - c)^2 + (c - a)^2}{2}$$ and $$(a^3 + b^3 + c^3)(a + b + c) - (a^2 + b^2 + c^2)^2 = ab(a - b)^2 + bc(b - c)^2 + ca(c - a)^2$$
Moreover, evaluating $\displaystyle \sum_{cyc}ca(ca - b^2)[(a - b)^2 + (b - c)^2]$, we have that $$\sum_{cyc}ca(ca - b^2)[(a - b)^2 + (b - c)^2] = \sum_{cyc}ca(ca - b^2)(c^2 + a^2 + 2b^2 - 2bc - 2ab)$$
$$ = \sum_{cyc}[(ca)^2 - b^2ca](c^2 + a^2) + 2bca \cdot \sum_{cyc}(ca - b^2)(b - c - a)$$
$$ = \sum_{cyc}b^2[(ab)^2 - c^2ab + (bc)^2 - a^2bc] - 2bca \cdot \sum_{cyc}b[(ab - c^2) + (bc - a^2) - (ca - b^2)]$$
I'm going to stop here. There was an attempt, one that failed tremendously.

A: Your SOS  works!
Indeed, by your work we obtain:
$$(a^2+b^2+c^2)^3-(a^3+b^3+c^3)(ab+ac+bc)(a+b+c)=$$
$$=(a^2+b^2+c^2)^2(ab+ac+bc)\left(\frac{a^2+b^2+c^2}{ab+ac+bc}-\frac{(a^3+b^3+c^3)(a+b+c)}{(a^2+b^2+c^2)^2}\right)=$$
$$=\frac{1}{2}\sum_{cyc}(a-b)^2((a^2+b^2+c^2)^2-2ab(ab+ac+bc))\geq$$
$$\geq\frac{1}{2}\sum_{cyc}(a-b)^2((a^2+b^2+c^2)(ab+ac+bc)-2ab(ab+ac+bc))=$$
$$=\frac{1}{2}(ab+ac+bc)\sum_{cyc}(a-b)^2((a-b)^2+c^2)\geq0.$$
Also, we can use $uvw$, which gives a solution immediately.
Indeed, let $a+b+c=3u$, $ab+ac+bc=3v^2$ and $abc=w^3$.
Thus, $a^2+b^2+c^2$, $ab+ac+bc$ and $a+b+c$ dot't depend on $w^3$ and since $$a^3+b^3+c^3=27u^3-27uv^2+3w^3,$$ it's enough to prove our inequality for a maximal value of $w^3$, which happens for equality case of two variables.
Since, our inequality is homogeneous, it's enough to assume $b=c=1$, which gives
$$(a-1)^2(a^4-2a+4)\geq0$$ and we are done!


text:
Q: What are the risks or drawbacks of using an external editor in an EDMS So I have an EDMS that uses OCR for extraction, indexing , classifying documents etc...
But actually I have developed my own PDF editor that handles native and scanned PDFs for text modification (through OCR for scanned pdfs)
But before starting I didn't really think about why using an external paid program such as Adobe Nitro Wondershare or Foxit would be a bad idea
Now I have to justify why I had to create mine I know it sounds a little ridiculous as question like people have to think in my place
But my question is just : are there any security or other risks concerned with editing documents from an EDMS out of the system??
For example I thought about the fact that downloading the documents everytime we have to edit is a long process and also that downloading them means every user that can edit will have the permission to download documents in the system and that wouldn't be good
I also thought that using an external editor can change the layout of the document and since some extractions are based on templates, those tools can move key elements from their bounding boxes and they won't be found by the extraction template again
Please let me know what you think
Thanks


text:
Q: Missing a step into opening kafka to outside world I have a setup a local kafka node that I want to open to the open world.
I have seen this question which seems very similar. I have opened that port using the advertised listeners to localhost:9092 and I opened that port the node, but when I'm trying to produce a message using kafkajs I get the following error :
{"level":"ERROR","timestamp":"2021-06-01T13:49:35.225Z","logger":"kafkajs","message":"[Connection] Connection error: connect EHOSTUNREACH 13.36.134.166:9092","broker":"13.36.134.166:9092","clientId":"my-app","stack":"Error: connect EHOSTUNREACH 13.36.134.166:9092\n    at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1054:14)"}
Am I missing a big step here ? Is using localhost to designate the advertised port ?
Many thanks ! Kev.