text:
Q: React.js - How do I uniquely identify a field within a dynamically generated component? I am currently creating a form that has an unknown number of sensor fields within it. I've gotten the front end working beautifully. However, now I want to grab the user info out of those dynamically generated component fields and I can't figure out how. Here is where I'm generating the components:
{this.state.sensors.map((item, i) => (
  <UpdateSensorInfo
    key={i}
    sensorName={item.sensorName}
    sensorLowerLimit={item.sensorLowerLimit}
    sensorUpperLimit={item.sensorUpperLimit}
  />
))}

And here is the actual component itself:
import React, { Component } from "react";
import "./updateSensorInfo.css";

class UpdateSensorInfo extends Component {
  render() {
    return (

            Sensor Name:
            <input
              type="text"
              name="text"
              placeholder=""
              className="sensorTextField"
              defaultValue={this.props.sensorName}
              required
            />

            Sensor Upper Limit:
            <input
              type="number"
              name="text"
              placeholder=""
              className="sensorTextField"
              defaultValue={this.props.sensorUpperLimit}
              required
            />

            Sensor Lower Limit:
            <input
              type="number"
              name="text"
              placeholder=""
              className="sensorTextField"
              defaultValue={this.props.sensorLowerLimit}
              required
            />

    );
  }
}

export default UpdateSensorInfo;

I would like to uniquely identify each text field within each generated component. How can I do this?

A: For anyone who has a similar situation, I have found a solution that works. There is a way to use the key that is created for each of the components within each component. use the following as an id or name for the input element:
id={`${this._reactInternalFiber.key}-additionalNameHere`}

This uses the key and will allow you to loop over the inputs within the components.


text:
Q: Exactly fitting an ellipsoid in $\mathbb{R}^n$ I'm trying to understand the constraints on exactly fitting an ellipse/ellipsoid to a small set of points as the number of dimensions increases. The ellipse/ellipsoid is always centred at the origin.
I conjecture that in $\mathbb{R}^n$, any $n$ points can have an infinite number of ellipsoids centred at the origin fitted through them so long as the $n$ points satisfy some constraint to avoid colinearity/coplanarity, which would lead to degenerate solutions (circles/spheres/spheroids) or no solution at all. I'm not clear on the precise nature of this constraint as $n$ increases.
Suppose we identify and satisfy these constraints so that special cases are excluded. Can this infinite number of ellipsoids be reduced to a unique ellipsoid by adding 1 more point, subject to additional constraints? What are those additional constraints? And is 1 more point always enough?
For example, if you have three points (plus origin) in $\mathbb{R}^2$, you can select the two points that make the widest angle with respect to the origin, and draw a line between them. The remaining point can only be fitted to an ellipse through the other two points if it lies "outside" the line with respect to the origin. I imagine that some similar constraint should exist in $\mathbb{R}^n$ - what is this constraint?

A: This is a partial answer.

Can this infinite number of ellipsoids be reduced to a unique ellipsoid by adding 1 more point, subject to additional constraints?

An general ellipsoid (as well as hyperboloids and other quadrics) can be described by a quadratic form. You can think of this as a symmetric $r\times r$ matrix, with $r=n+1$. It has $\frac{r(r+1)}2$ different entries. But you actually have one less degree of freedom due to homogenity. The centering at the origin eats another $n$ degrees of freedom, since you can achieve all other quadrics using translation in $n$ dimensions. So you have
$$\frac{r(r+1)}2-r = \frac{r(r-1)}2 = \frac{n(n+1)}2$$
real degrees of freedom. Each defining point contributes one real degree of freedom: it can be freely moved in $n$ dimensions, but even for a given quadric, it can still move insie the cuadric, i.e. a $(n-1)$-dimensional manifold, without changing its definition.
So in 2D, you have 3 defining points, in 3D you have 6, and so on. So no, $n+1$ points won't be enough to uniquely describe a quadric.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change TextView Value When Click On Screen I want to make a simple counter. When i click on the screen, the value of the textvalue will increase.
So my activity.
public class MyTasbih extends Activity implements View.OnClickListener {

//Button btn;
TextView t;
int i=0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //btn=(Button)findViewById(R.id.button);
    t=(TextView)findViewById(R.id.t);

    //btn.setOnClickListener(this);
    t.setOnClickListener(this);

    updateCounter();

}

public void onClick(View view) {
    i++;
    updateCounter();

}

private void updateCounter() {

    t.setText(i);
}
}

but its crash. I'm newbie, please help.

A: please try this and check
private void updateCounter() {

    t.setText(String.valueOf(i));
}

A: I don't have eclipse handy to check this but should update not be:
private void updateCounter() {
    t.setText(Integer.toString(i));
}

A: public class MyTasbih extends Activity implements View.OnClickListener {

//Button btn;
TextView t;
int i=0;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main6);

    //btn=(Button)findViewById(R.id.button);
    t=(TextView)findViewById(R.id.t);

    //btn.setOnClickListener(this);
    t.setOnClickListener(this);

    updateCounter();

}

public void onClick(View view) {
    i++;
    updateCounter();

}

private void updateCounter() {

    t.setText(String.valueOf(i));
}
}


text:
Q: Which versions of ubuntu are compatible with INTEL Core i5 6th generation ASUS A556U laptop I had ubuntu 14.04 on my lap but it did not support my trackpad. I am very new to OS and compatibility issues. Please help me out

A: This was a kernel bug which was fixed in Ubuntu 15.10, so 15.10 and later should be OK


text:
Q: Problem in converting tick data into OHLC in real time This post is a continuation of previous post. I reproduce the code as follows:
import time, requests
import pandas as pd

ticks = []
while True:
    r = requests.get('https://api1.binance.com/api/v3/ticker/price?symbol=ETHUSDT')
    resp_dict = r.json()
    # time.time()
    ticks.append({'time' : time.time(), 'price' : resp_dict["price"]})
    df = pd.DataFrame(ticks)
    df["time"] = pd.to_datetime(df["time"], unit="s")
    df["price"] = df["price"].astype(float)
    df = df.set_index("time")
    ohlc = pd.DataFrame(df["price"].resample("5s").ohlc())
    # print(df)
    print(ohlc)

I want to get the latest ohlc by resampling the realtime data. However, I got a variable ohlc. Examples of output are as follows:
                        open     high      low    close
time
2022-06-14 03:49:35  1164.92  1165.16  1164.76  1164.91
2022-06-14 03:49:40  1164.86  1165.46  1164.86  1165.17
                        open     high      low    close
time
2022-06-14 03:49:35  1164.92  1165.16  1164.76  1164.91
2022-06-14 03:49:40  1164.86  1165.46  1164.86  1164.89
                        open     high      low    close
time
2022-06-14 03:49:35  1164.92  1165.16  1164.76  1164.91
2022-06-14 03:49:40  1164.86  1165.46  1164.86  1165.16

You can see that in the close price column, the close price is changing. The reason for this is doing the resampling while in the realtime the period is still within the resampling timestep.
May I know how can I deal with this problem? Thank you.


text:
Q: How to use character vector in formula in R I have this formula for Rpackage DESEeq which takes ~Strain as formula.
I have type.formula <- "Strain" and want to replace the Strain in formula with type.formula and be able to run the code below. How can I do this?
So instead of this code below:
dds <- DESeqDataSetFromMatrix(countData = count.mat , colData = cond, design = ~Strain)

I want to run it like this:
dds <- DESeqDataSetFromMatrix(countData = count.mat , colData = cond, design = ~eval(type.formula))


text:
Q: Error saving model in sklearn2pmml using VotingClassifier I'm new to programming and I'm having a little trouble saving a model in pmml. I have a database and I need to make a selection of attributes, then use the majority vote and finally save in pmml. Even the majority vote part works, but when I save the model on the last line using sklearn2pmml it gives an error.
from pandas import read_csv
from sklearn.tree import DecisionTreeClassifier
from sklearn.model_selection import train_test_split
from mlxtend.classifier import EnsembleVoteClassifier
from sklearn.metrics import accuracy_score
from sklearn2pmml import make_pmml_pipeline
from sklearn2pmml import sklearn2pmml
from sklearn.compose import ColumnTransformer, make_column_transformer
from sklearn.pipeline import Pipeline
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn2pmml.pipeline import PMMLPipeline
from sklearn.ensemble import VotingClassifier
import joblib

url = 'D:/treinamento.CSV'
df = read_csv(url, header=None)
data = df.values

url_test = 'D:/TESTE.CSV'
df_test = read_csv(url_test, header=None)
data_test = df_test.values

X = data[:, :-1]
y = data_test[:, -1]

X_train = data[:, :-1]
X_test = data_test[:, :-1]
y_train = data[:, -1]
y_test = y
#features selection
features1 = [2, 5, 7]
features2 = [0, 1, 4, 5, 7]
features3 = [0, 1, 4, 5, 6]
features4 = [1, 4]
numeric_transformer = Pipeline(steps=[('scaler', StandardScaler())])
preprocessor1 = ColumnTransformer(transformers=[('numerical', numeric_transformer, features1)])
preprocessor2 = ColumnTransformer(transformers=[('numerical', numeric_transformer, features2)])
preprocessor3 = ColumnTransformer(transformers=[('numerical', numeric_transformer, features3)])
preprocessor4 = ColumnTransformer(transformers=[('numerical', numeric_transformer, features4)])

pipe1 = PMMLPipeline(steps=[('preprocessor', preprocessor1),('classifier', DecisionTreeClassifier(min_samples_split = 2))])
pipe2 = PMMLPipeline(steps=[('preprocessor', preprocessor2),('classifier', DecisionTreeClassifier(min_samples_split = 2))])
pipe3 = PMMLPipeline(steps=[('preprocessor', preprocessor3),('classifier', DecisionTreeClassifier(min_samples_split = 2))])
pipe4 = PMMLPipeline(steps=[('preprocessor', preprocessor4),('classifier', DecisionTreeClassifier(min_samples_split = 2))])

eclf = VotingClassifier(estimators=[('pipe1', PMMLPipeline(steps=[('preprocessor', preprocessor1),('classifier', DecisionTreeClassifier(min_samples_split = 2))])),
                                    ('pipe2', PMMLPipeline(steps=[('preprocessor', preprocessor2),('classifier', DecisionTreeClassifier(min_samples_split = 2))])),
                                    ('pipe3', PMMLPipeline(steps=[('preprocessor', preprocessor3),('classifier', DecisionTreeClassifier(min_samples_split = 2))])),
                                    ('pipe4', PMMLPipeline(steps=[('preprocessor', preprocessor4),('classifier', DecisionTreeClassifier(min_samples_split = 2))]))], voting='hard', weights=[1,1,1,1])

eclf.fit(X_train, y_train)
yhat = eclf.predict(X_test)
accuracy = accuracy_score(y_test, yhat)
print('Accuracy: %.3f' % (accuracy * 100))

sklearn2pmml(eclf, "D:/Mestrado/ARTIGO DRC/dados_pos_revisao/cross validation - dados reavaliados/4 revisao/5 FOLDS/1 FOLD/eclf.pmml", with_repr = True)

Code error
65 sklearn2pmml(eclf, "D:/mest/eclf.pmml", with_repr = True)

~\anaconda3\lib\site-packages\sklearn2pmml\__init__.py in sklearn2pmml(pipeline, pmml, user_classpath, with_repr, debug, java_encoding)
    222                 print("{0}: {1}".format(java_version[0], java_version[1]))
    223         if not isinstance(pipeline, PMMLPipeline):
--> 224                 raise TypeError("The pipeline object is not an instance of " + PMMLPipeline.__name__ + ". Use the 'sklearn2pmml.make_pmml_pipeline(obj)' utility function to translate a regular Scikit-Learn estimator or pipeline to a PMML pipeline")
    225         estimator = pipeline._final_estimator
    226         cmd = ["java", "-cp", os.pathsep.join(_classpath(user_classpath)), "org.jpmml.sklearn.Main"]

TypeError: The pipeline object is not an instance of PMMLPipeline. Use the 'sklearn2pmml.make_pmml_pipeline(obj)' utility function to translate a regular Scikit-Learn estimator or pipeline to a PMML pipeline

A:
The pipeline object is not an instance of PMMLPipeline

Did you read the SkLearn2PMML error message or not? Probably not, because it clearly states what's the issue!
You're using the PMMLPipeline class in completely wrong places. It should be used only as the topmost wrapper to the VotingClassifier estimator.
Please reorganize your code like this:
pipeline = PMMLPipeline([
  ("classifier", VotingClassifier([
    ("pipe1", Pipeline(...)),
    ("pipe2", Pipeline(...)),
    ("pipe3", Pipeline(...))
  ]))
])
sklearn2pmml(pipeline, "pipeline.pmml")


text:
Q: If no solution for x from some system of equations exists, then does that imply that x (at least within domain of that system) does itself not exist?? Suppose you're solving an inconsistent system. Since none of the variables can have compatible combination of values, then the answer is No Solution, ⦰.  What is the correct translation relating the tuple to this answer? In the common 3- case of $x,y,z$, is it $⟨x,y,z⟩=⦰$ or instead $[x,y,z]∈\{\}$ or are the two expressions equivalent or are neither strictly correct?
Supposing instead that one or more if not all the variables do exist, for simplicity suppo4se that $x,y$ is dependent on $z$; for $z:=f(x,y)$ then would it be apt to think of $z$ as $=0±.. 0±..$, where 0 is analogous to nullset with existence (since addition-subtraction is the lowest order of operations, it should never affect the subsequent expression, unlike as possible with e.g. 1 for multiplicative identity)?


text:
Q: Are my debug statements correct? Is the class being used correctly? I am not currently getting errors but also am getting no output I am tasked to write a program that accesses an outside text file that contains basketball player names and scores. I have always had issues reading and writing from txt files regardless of language. Once the txt file is read from, the program is supposed to output the average scores for all players as well as the player name of the highest scorer. I am getting several errors thrown from my code which won't run. Are my debug statements correct? Is the class being used correctly? Here is what I have:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace BasketBallScore
{
public partial class BasketballStats : Form
{

    private string score;

    public BasketballStats()
    {
        InitializeComponent();
    }

    public class BasketballController
    {
        public class Entry
        {
            public int Value { get; set; }
            public string Name { get; set; }
        }
        BasketballController(string filename)
        {
            this.filename = filename;
        }
        private string filename;
        private List<Entry> data = new List<Entry>();
        public List<Entry> Data
        {
            get
            {
                // Clear data
                data.Clear();
                // Iterate through lines
                foreach (string line in System.IO.File.ReadLines(filename))
                {
                    // Split by space
                    List<string> parts = line.Trim().Split(' ').ToList();
                    if (parts.Count() < 2)
                        continue;
                    // Number is last space separated string
                    int number = int.Parse(parts.Last());
                    // Remove number
                    parts.RemoveAt(parts.Count() - 1);
                    // Name is any previous word joined by space
                    string name = string.Join(" ", parts).Trim();

                    // Add number and name to data
                    data.Add(new Entry() { Name = name, Value = number });
                }
                // Sort from greater value to smaller
                data.Sort(Comparer<Entry>.Create(
                    (l, r) => r.Value.CompareTo(l.Value)));
                return data;
            }
            set
            {
                using (var writer = new System.IO.StreamWriter(filename))
                {
                    foreach (var entry in value)
                    {
                        writer.WriteLine(string.Format("{0} {1}", entry.Name, entry.Value));
                    }
                }
                data = value;
            }
        }
        public double Average
        {
            get
            {
                // Read file if data is empty, otherwise reuse its value
                var src = (data.Count() == 0) ? Data : data;
                if (src.Count() == 0)
                    return 0.0;
                // Return average
                return src.Average(x => x.Value);
            }
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void BtnCreateFile_Click(object sender, EventArgs e)
    {
        score = "basketBallScore.txt";
        if (File.Exists(score))
        {
            Console.WriteLine("FileName: {0}", score);
            Console.WriteLine("Attributes: {0}",
                File.GetAttributes(score));
            Console.WriteLine("Created: {0}",
                File.GetCreationTime(score));
            Console.WriteLine("Last Accessed: {0}",
                File.GetLastAccessTime(score));

            DirectoryInfo dir = new DirectoryInfo(".");
            Console.WriteLine("Current Directory: \n{0} \n",
                Directory.GetCurrentDirectory());
            Console.WriteLine("File Name".PadRight(52) +
                "Size".PadRight(10) + "Creation Time");
            foreach (FileInfo fil in dir.GetFiles("*.*"))
            {
                string name = fil.Name;
                long size = fil.Length;
                DateTime creationTime = fil.CreationTime;
                Console.WriteLine("{0} {1,12:NO} {2, 20:g} ", name.PadRight(45),
                    size, creationTime);
            }
        }

        else
        {
            Console.WriteLine("{0} not found - using current" +
                "directory:", score);
        }
        Console.ReadKey();
    }

    private void CalcAverage_Click(object sender, EventArgs e)
    {
        var c = new BasketballController("basketBallScore.txt");
        Debug.WriteLine(string.Format("Average {0}", c.Average));
        Debug.WriteLine(string.Format("First {0} {1}", c.Data.First().Name, c.Data.First().Value));
        Debug.WriteLine(string.Format("Last {0} {1}", c.Data.Last().Name, c.Data.Last().Value));
    }
}

}
This is what the text file contains:
Lebron James        31
Steph Curry         12
Kyrie Irving        37
Kevin Durant        9
Paul George         35
Klay Thompson       8
J.R.Smith           12
Zaza Pachulia       4
Tristan Thompson    10
Draymond Green      2

The program will access the file but will not give any output beyond the verification of the the data file. This is an updated version of a previous program. This was what I had previously:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace TextFiles
{
public partial class BasketBallStats : Form
{
    List<int> marks = new List<int>();

public BasketBallStats()
{
    InitializeComponent();
}

// Form load event handler used to construct
// object of the Streamwriter class, sending the
// new filename as an argument. Enclosed in
// try...catch block.
public class BasketballController
{
    public class Entry
    {
        public int Value { get; set; }
        public string Name { get; set; }
    }
    BasketballController(string filename)
    {
        this.filename = filename;
    }
    private string filename;
    private List<Entry> data = new List<Entry>();
    public List<Entry> Data
    {
        get
        {
            // Clear data
            data.Clear();
            // Iterate through lines
            foreach (string line in System.IO.File.ReadLines(filename))
            {
                // Split by space
                List<string> parts = line.Trim().Split(' ').ToList();
                if (parts.Count() < 2)
                    continue;
                // Number is last space separated string
                int number = int.Parse(parts.Last());
                // Remove number
                parts.RemoveAt(parts.Count() - 1);
                // Name is any previous word joined by space
                string name = string.Join(" ", parts).Trim();

                // Add number and name to data
                data.Add(new Entry() { Name = name, Value = number });
            }
            // Sort from greater value to smaller
            data.Sort(Comparer<Entry>.Create(
                (l, r) => r.Value.CompareTo(l.Value)));
            return data;
        }
        set
        {
            using (var writer = new System.IO.StreamWriter(filename))
            {
                foreach (var entry in value)
                {
                    writer.WriteLine(string.Format("{0} {1}", entry.Name, entry.Value));
                }
            }
            data = value;
        }
    }
    public double Average
    {
        get
        {
            // Read file if data is empty, otherwise reuse its value
            var src = (data.Count() == 0) ? Data : data;
            if (src.Count() == 0)
                return 0.0;
            // Return average
            return src.Average(x => x.Value);
        }
    }
}

private string score;

public List<int> Marks { get => Marks1; set => Marks1 = value; }
public List<int> Marks1 { get => marks; set => marks = value; }

private void BasketBallStats_Load(object sender, EventArgs e)
{

}

private void BtnCreateFile_Click(object sender, EventArgs e)
{
    score = "basketBallScore.txt";
    if (File.Exists(score))
    {
        Console.WriteLine("FileName: {0}", score);
        Console.WriteLine("Attributes: {0}",
            File.GetAttributes(score));
        Console.WriteLine("Created: {0}",
            File.GetCreationTime(score));
        Console.WriteLine("Last Accessed: {0}",
            File.GetLastAccessTime(score));

        DirectoryInfo dir = new DirectoryInfo(".");
        Console.WriteLine("Current Directory: \n{0} \n",
            Directory.GetCurrentDirectory());
        Console.WriteLine("File Name".PadRight(52) +
            "Size".PadRight(10) + "Creation Time");
        foreach (FileInfo fil in dir.GetFiles("*.*"))
        {
            string name = fil.Name;
            long size = fil.Length;
            DateTime creationTime = fil.CreationTime;
            Console.WriteLine("{0} {1,12:NO} {2, 20:g} ", name.PadRight(45),
                size, creationTime);
        }
    }

    else
    {
        Console.WriteLine("{0} not found - using current" +
            "directory:", score);
    }
    Console.ReadKey();
}

private void BtnWriteFile_Click(object sender, EventArgs e)
{
    try
    {
        var WriteToFile = new System.IO.StreamWriter("basketBallScore.txt"); //create textfile in default directory
        WriteToFile.Write(listView1.Text + ", " + listView1.Text + ", " + listView1.Text + ", " + listView1.Text);
        WriteToFile.Close();
        Marks.Add(Convert.ToInt32(listView1.Text)); //add to list
    }

    catch (System.IO.DirectoryNotFoundException)
    {
        lblMessage.Text = "File did not close properly: ";    //add error message
    }
}

private void ManipulateFile_Click(object sender, EventArgs e)
{
    int[] hoursArray = new int[30];
    StreamReader fileSR = new StreamReader("basketBallScore.txt");
    int counter = 0;
    string line = "";
    line = fileSR.ReadLine();
    while (line != null)
    {
        hoursArray[counter] = int.Parse(line);
        counter = counter + 1;
        line = fileSR.ReadLine();
    }
    fileSR.Close();

    int total = 0;
    double average = 0;
    for (int index = 0; index < hoursArray.Length; index++)
    {
        total = total + hoursArray[index];
    }
    average = (double)total / hoursArray.Length;

    int high = hoursArray[0];
    for (int index = 1; index < hoursArray.Length; index++)
    {
        if (hoursArray[index] > high)
        {
            high = hoursArray[index];
        }
    }
    Console.WriteLine("Highest number is: " + high);
    Console.WriteLine("The average is: " + average);
    Console.ReadLine();
}

private void BasketBallStats_Load_1(object sender, EventArgs e)
{

}

private void CalcAverage_Click(object sender, EventArgs e)
{
    int totalmarks = 0;
    foreach (int m in Marks)
        totalmarks += m;

    MessageBox.Show("Average Is: " + totalmarks / Marks.Count);
}

private void Button1_Click(object sender, EventArgs e)
{
    var c = new BasketballController("basketBallScore.txt");
    Debug.WriteLine(string.Format("Average {0}", c.Average));
    Debug.WriteLine(string.Format("First {0} {1}", c.Data.First().Name, c.Data.First().Value));
    Debug.WriteLine(string.Format("Last {0} {1}", c.Data.Last().Name, c.Data.Last().Value));
    }
  }
}

A: I was able to code a program that does exactly what I needed it to do. Here is what I have:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;

namespace BasketballScores
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void BtnOutputData_Click(object sender, EventArgs e)
    {
        try
        {
            string path = "basketBallScore.txt";
            var c = new BasketballPlayer(path);
            ListView1.Items.Add(string.Format("\r\nAverage {0}", c.Average));
            ListView1.Items.Add(string.Format("\r\nFirst {0} {1}", c.Data.First().Name, c.Data.First().Value));
            ListView1.Items.Add(string.Format("\r\nLast {0} {1}", c.Data.Last().Name, c.Data.Last().Value));
            using (StreamWriter sw = File.AppendText(path))
            {
                foreach (ListViewItem item in ListView1.Items)
                {
                    sw.WriteLine(item.Text);
                    for (int i = 1; i < item.SubItems.Count; i++)
                    {
                        sw.WriteLine(item.SubItems[i].Text);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            lblMessage.Text = ex.Message;
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {

    }

    private void ListView1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
  }
}

This is a class I have with the code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasketballScores
{
class BasketballPlayer
{
    public class Entry
    {
        public int Value { get; set; }
        public string Name { get; set; }
    }
public BasketballPlayer(string filename)
    {
        this.filename = filename;
    }
    private string filename;
    private List<Entry> data = new List<Entry>();
    public List<Entry> Data
    {
        get
        {
            // Clear data
            data.Clear();
            // Iterate through lines
            foreach (string line in System.IO.File.ReadLines(filename))
            {
                // Split by space
                List<string> parts = line.Trim().Split(' ').ToList();
                if (parts.Count() < 2)
                    continue;
                // Number is last space separated string
                int number = int.Parse(parts.Last());
                // Remove number
                parts.RemoveAt(parts.Count() - 1);
                // Name is any previous word joined by space
                string name = string.Join(" ", parts).Trim();

                // Add number and name to data
                data.Add(new Entry() { Name = name, Value = number });
            }
            // Sort from greater value to smaller
            data.Sort(Comparer<Entry>.Create(
                (l, r) => r.Value.CompareTo(l.Value)));
            return data;
        }
        set
        {
            using (var writer = new System.IO.StreamWriter(filename))
            {
                foreach (var entry in value)
                {
                    writer.WriteLine(string.Format("{0} {1}", entry.Name, entry.Value));
                }
            }
            data = value;
        }
    }
    public double Average
    {
        get
        {
            // Read file if data is empty, otherwise reuse its value
            var src = (data.Count() == 0) ? Data : data;
            if (src.Count() == 0)
                return 0.0;
            // Return average
            return src.Average(x => x.Value);
        }
    }
  }
}


text:
Q: Listening to Events in the calendar from more than one person using EWS API Simply I would like to receive a notification every time someone added a new appointment or made any changes on what he/she has.
The only way I know how to do it , is by using
service.SubscribeToStreamingNotifications
but the problem here that it only listens to the account that the service is bound to like in this way
var service = new ExchangeService(ExchangeVersion.Exchange2010_SP2)
{
    Credentials = new WebCredentials(userName, password)
};

service.SubscribeToStreamingNotifications(new FolderId[]
{
    WellKnownFolderName.Calendar
}, EventType.FreeBusyChanged, EventType.Deleted);

I have solved this problem by creating a list of services each service is bounded to different user and the application should listen to each of them.
The problem with this way is that I need to have the password of each account I wont to listen to its events, which is not possible in real world.
so is there any way to deal with that ?

A: I have solved this problem, by creating a list of services, all the services are a clone of the main ExchangeService, with the same credentials for the admin account, but they are impersonated to the other accounts.
NOTE: You need to setup the server so it allows impersonation.
private void ImpersonateUsers(ICollection<string> userSmtps)
        {
            if (userSmtps != null)
                if (userSmtps.Count > 0)
                {
                    foreach (var userSmtp in userSmtps)
                    {
                        if (_services.ContainsKey(userSmtp)) continue;
                        var newService = new ExchangeService(ExchangeVersion.Exchange2010_SP2);

                        try
                        {
                            var serviceCred = ((System.Net.NetworkCredential)(((WebCredentials)(_services.First().Value.Credentials)).Credentials));
                            newService.Credentials = new WebCredentials(serviceCred.UserName, serviceCred.Password, serviceCred.Domain);
                            newService.AutodiscoverUrl(serviceCred.UserName + "@" + serviceCred.Domain, RedirectionUrlValidationCallback);
                            newService.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, userSmtp);
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex.Message);
                        }
                        _services.Add(userSmtp, newService);
                    }
                }
        }

Where userSmtps is a list of the email addresses I want to impersonate and _services is the dictionary of services where the first member is the main service.

A: you will have to create a service instance per user. There is no way to subscribe to other users folder.
But instead of StreamingNotifications you can use Pull and Push-Subscriptions too.
Something like this:
List<FolderId> folders = new List<FolderId>();
folders.Add(new FolderId(WellKnownFolderName.Calendar));
PullSubscription subscription = = service.SubscribeToPullNotifications(folders, 1440, watermark, EventType.Created, EventType.Deleted, EventType.Modified, EventType.Moved, EventType.NewMail);

Some time later....
GetEventsResults currentevents = m_subscription .GetEvents();


text:
Q: Drawing a graph from a function I have a complex mathematical C++ function. I want a translated and easy to read graph out of it. Is there any software which can analyze special mathematical functions and draw an easy to read graph?  Assume it's an encryption algorithm code.
I have tried a lot of software like Understand, WizGraph, etc. Is there something I should search for to find this type of software?

A: Print the (x, y) values on cout, one pair (or tuple) of values per line, separated by commas.  Run the gen program from command interpreter, redirect to textfile data.csv.
Load the comma-separated values text file in Excel or other spreadsheet program.  Select the relevant data.  Graph it.


text:
Q: ADC 10-bit false results I'm using atmega32 µc with the internal 10-bit ADC. I connected my potentiometer to the ADC 1 and I'm using 5 V Voltage Reference.
using the following code, I did the ADC-config
void ADC_init(void)
{

    //Turn on the ADC
    ADCSRA |= 1<<ADEN;   // Turn On ADC (Enable ADC)

    //ADMUX  |= 1<<ADLAR ;  // Config shifting to the left (10-bit), otherwise it is right adjusted

    ADMUX  |= 1<<REFS0 ;  // Config VRef (external Vref in this case)
    ADMUX  |= 1<<MUX1 ;  // ADC-Channel 1

//  ADCSRA |= 1<<ADIE;   // Enable ADC Interrupt
    ADCSRA |= 3<<ADPS0;  // Assign ADC-prescaler 128

    ADCSRA |= 1<<ADSC;   //start the the measure conversion
}

Then in Main function I am calling the following function each 1000ms and send the data to the USART interface
void ADC_measure(void)
{
    _delay_ms(50);

    // if the ADC right adjusted
    theLow = ADCL;  // ADC Value Low
    _delay_ms(50);

    ADC_TenBit = ADCH<<8 | theLow  ;  // because of lift adjustment of ADC

    _delay_ms(50);

    sprintf( ADCBuffer, "The ADCValue is : %d \n", ADC_TenBit );

    _delay_ms(50);

    usart_pstr(ADCBuffer);

    _delay_ms(50);
    //start the the measure conversion
    ADCSRA |= 1<<ADSC;
}

The problem is : when I open the terminal , I see only the ADC Value = 255 or 248
increasing or decreasing the potentiometer value doesn't change the ADC value.
what can I do now?

A: You have incorrect multiplexer setting. To select channel 1, it should be
ADMUX  |= 1<<MUX0 ;  // ADC-Channel 1

Edit: Another thing is incorrect clock prescaler. To get \$f_{clk}/128\$:
ADCSRA |= 7<<ADPS0;  // Assign ADC-prescaler 128

A: Try:
ADC_TenBit = (uint16_t)ADCH<<8 | theLow;

And you did declare ADC_TenBit uint16_t, right?


text:
Q: Dynamics AX 2009 Developer Install I am trying to set my new laptop up with a developer installation of MS Dynamics AX 2009.
I start by installing MS SQL Server  2008 R2, this goes in fine, I create a new database in here.
I then launch the AX 2009 setup, I firstly install the Application Files, go through this, all is OK.
I then re-launch the AX 2009 setup, installing the AOS, I login using a specific username / password setup for the AOS.
I then re-launch the AX 2009 setup and install the Client and Debugger.
When I go to launch the AOS in Services the service gets 'stuck on "Starting" and after 5/10/15 minutes waiting and refreshing nothing happens?
Do I need to install the Database files in the AX 2009 setup as well?
Many thanks...

A: Yes you need to have an AX 2009 database.  Either install it via the AX 2009 installer or deploy the contoso example database from Microsoft.  Easier to install from the installer.
The first start of the AOS can take some time, but if you don't have a database, I can't imagine how it would work.
Go to (Administrative Tools>Microsoft Dynamics AX 2009 Server Configuration) and click the database tab of your instance, and what does it have?  Does that database exist or is anything selected?
You should check the windows event viewer under "applications" to see issues during service startup.
/This isn't really code btw...


text:
Q: Resources for learning formal math notation Does anyone know of some resources that provide a good introduction to common notation used in formal math? For example, I honestly don't know how to interpret $f: \mathbb{Z} \rightarrow \mathbb{Z}$. I feel like the most difficult time I have with math is not understanding the notation. Thanks!

A: The Wikipedia page List of mathematical symbols explains the meaning of some basic symbols, with examples of usage. Then there is the category Mathematical notation...
Generally speaking: if the text  you are reading uses notation which it does not explain, this means the author assumes the  readers are familiar  with the notation already. If you are not familiar with it, chances are that you lack the background necessary for reading the book -- which will also manifest itself in ways unrelated to notation.


text:
Q: Slider with bullets I have made a slider of three photos. I have two buttons (next and prev), this part works fine. I want to use 3 bullets for selecting the images too, but I am having some problems making the bullet buttons work with the slider. I can't find the way to do this.
Can anyone help me with this code? I'm a real beginner with JavaScript.
Thanks.

/**
 * Navegación por botones
 */
var navegar = function () {
 var elemento = document.getElementById('slider').getElementsByTagName('li');
 var pos = 0;
 for (var i=0; i<elemento.length; i++) {
  if (elemento[i].className == "activa") {
   elemento[i].className = "noactiva";
   pos = i;
  }
 }
 /** Pulsar Anterior **/
 if (this.id == "ant" && pos > 0) {
  elemento[pos-1].className = "activa";
 } else if (this.id == "ant") {
  elemento[elemento.length-1].className = "activa";
 }

 /** Pulsar Siguiente **/
 if (this.id == "seg" && pos < elemento.length-1) {
  elemento[pos+1].className = "activa";
 } else if (this.id == "seg") {
  elemento[0].className = "activa";
 }
 return false;
};

var desplazar = function () {
 var nav = document.querySelectorAll(".nav");
 for (var i=0; i<nav.length; i++) {
  nav[i].onclick = navegar;
 }
};

window.onload = function (){
 new desplazar();
};
body.slide { background-color:#9c9c9c  }

#slider {display: block; margin: 0 auto;padding: 0;position: relative;width: 50%;min-height: 22.5em; max-height: 22.5em;list-style: none; overflow: hidden;}

#slider li {position: absolute; background: white; float: left; margin: 0 15px 30px; padding: 10px 10px 35px; box-shadow: 0 4px 6px rgba(0,0,0,.3);}

#slider li img { width: 100%;}

#slider .activa { z-index: 1; opacity: 1;}

#slider .noactiva { z-index: 0; opacity: 0;}

.nav { display: inline-block; margin-top: 1.5em; text-decoration: none;}

.botons { text-align: center;}

.button { position: absolute; top: 50%; }

#linknum ul{list-style:none; display:block; text-align:center; }

#linknum ul li{display:inline; margin-right: 3%;}
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta charset="UTF-8">
<title>PracticaFinal</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />

Home

Slide

Carta

Galeria d'imatges amb Slide

  <button id="ant" class="nav" >Anterior</button>
  <button id="seg" class="nav" >Següent</button>

  <input id="button-1" type="radio" name="radio-set" class="activa" checked="checked">

  <input id="button-2" type="radio" name="radio-set" class="noactiva">

  <input id="button-3" type="radio" name="radio-set" class="noactiva">

A: I think you will find your applications easier to think about if you separate the application state from the representation. By "application state", we mean the data in the application that changes over time. In this example, the application state has a single property: the currently active slide index.
In order for our code to know the current application state, it must use the DOM to figure out the index of the slide that is currently active. We can move the state to our code-level by creating a global variable to hold the active slide index:
var activeIndex = 0;

And while we are creating global variables, let's cache some references to the DOM elements we will be continually using so that we do not have to keep fetching and re-fetching them:
var $bullets = document.querySelectorAll('input[name="radio-set"]');
var $slides = document.getElementById('slider').getElementsByTagName('li');

Next, let's update our navegar function to use our activeIndex variable:
var navegar = function () {
    activeIndex += this.id === 'seg' ? 1 : -1;

    if (activeIndex >= $slides.length) {
        activeIndex = 0;
    }
    else if (activeIndex < 0) {
        activeIndex = $slides.length - 1;
    }

    render(); // TODO: We will define this later.
}

We will now define our render function whose job it will to update the page with the current application state:
var render = function () {
    for (var i = 0; i < $slides.length; i++) {
        $bullets[i].className = i === activeIndex ? 'activa' : 'noactiva';
        $slides[i].className = i === activeIndex ? 'activa' : 'noactiva';
    }
};

We are now ready to address your original question and to bind the radio buttons to our slider navigation. All we need do is attach an onchange handler to each bullet that will update the ativeIndex and then call render. We can do this by adding something like the following to the desplazar function:
for (var i = 0; i < $bullets.length; i++) {
    (function (index) {
        $bullets[index].onchange = function () {
            activeIndex = index;
            render();
        };
    })(i);
}

The (function (index) { /*...*/ })(i); bit might look a little odd. If you are curious about it, a discussion can be found here.
Additionally, I have created a fiddle for your reference.


text:
Q: Proving a property of rank of a matrix Let be $m,b\in\Bbb{N}$ and $A=(a_{ij})\in\Bbb{R}^{m \times n} $ It applies that $\sum_{j=1}^{n} a_{ij}= 0, \forall i\in \{ 1,\cdots,m\}$ Show that $Rank(A) < n$.
\
I guess it's a crucial point that the $rank(A) < n$ and it's not $rank(A) = n$
Actually I have difficulties to understand this part $\sum_{j=1}^{n} a_{ij}= 0, \forall\in \{ 1,\cdots,m\}$.
Do we accumulate the elements $ a_{i1}+ \cdots a_{in}$? So is it the sum of every elements in the matrix? But it makes no sense to me. Thank you for your helps in advance.

A: Each and every column of the matrix sums to $0$. Hence, the $n$-dimensional vector of all $1$'s is mapped to the null vector. This gives a non-trivial nullspace, hence rank is $<n$.


text:
Q: Choose to use the default sim when placing calls from iOS app We have a dialer app that makes phone calls. Basically, it just sends the dial string to the native dialer and the native dialer makes the call.
When an iPhone has a dual sim, you set which one is used as the default. When you make a call with the native dialer, it uses that default sim.
However, when you make calls from our app, it uses the first sim, regardless of which is set as default. The only way to have it call from the second sim, is if you deactivate sim1.
We are not trying to choose the sim from within our app, simply to use the one that is set as primary on the iPhone.
Native Dialer
Primary set as Sim 1 - Calls using Sim 1
Primary set as Sim 2 - Calls using Sim 2
Our app
Primary set as Sim 1 - Calls using Sim 1
Primary set as Sim 2 - Calls using Sim 1
Primary set as Sim 2 (but with Sim 1 deactivated) - Calls using Sim 2
Thanks in advance.

A: Unfortunately you can't select the sim to call yet.
In the future maybe Apple add that but as you said all calls will directed to the physical sim unless it's deactivated.


text:
Q: DSL support for Clover Maven Plugin Support Currently I am using Clover Maven Plugin to check code coverage.
I configured Jenkins to Clover plugin manually and was able to see the code coverage metrics. I used the below link for configuration.
https://wiki.jenkins.io/display/JENKINS/Clover+Plugin
Now, I am trying to use dsl file to create the Jenkins task, and it seems dsl supports CloverPHP plugin alone.
Is there any other alternative way to configure the Clover Plugin via dsl.

A: Tried with below code and it worked
configure { project ->
    project / 'publishers' << 'hudson.plugins.clover.CloverPublisher' {
        cloverReportDir 'target/site/clover'
        cloverReportFileName 'clover.xml'
        healthyTarget {
            methodCoverage 70
            conditionalCoverage 80
            statementCoverage 80
        }
    }
}


text:
Q: Perl one-liner: deleting a line with pattern matching I am trying to delete bunch of lines in a file if they match with a particular pattern  which is variable.
I am trying to delete a line which matches with abc12, abc13, etc.
I tried writing a C-shell script, and this is the code:
    **!/bin/csh
    foreach $x (12 13 14 15 16 17)
    perl -ni -e 'print unless /abc$x/' filename
    end**

This doesn't work, but when I use the one-liner without a variable (abc12), it works.
I am not sure if there is something wrong with the pattern matching or if there is something else I am missing.

A: Yes, it's the fact you're using single quotes. It means that $x is being interpreted literally.
Of course, you're also doing it very inefficiently, because you're processing each file multiple times.
If you're looking to remove lines abc12 to abc17 you can do this all in one go:
perl -n -i.bak -e 'print unless m/abc1[234567]/' filename

A: Try this
perl -n -i.bak -e 'print unless m/abc1[2-7]/' filename

using the range [2-7] only removes the need to type [234567] which has the effect of saving you three keystrokes.
man 1 bash: Pattern Matching
[...] Matches any one of the enclosed characters. A pair of characters separated by a hyphen denotes a range expression; any character that sorts between those two characters, inclusive, using the current locale's collating sequence and character set, is matched. If the first character following the [ is a ! or a ^ then any character not enclosed is matched.
A - may be matched by including it as the first or last character in the set. A ] may be matched by including it as the first character in the set.


text:
Q: docker swarm manager on windows through a tailscale network so I want my windows machine to be a manger node in my docker swarm.  all the compute power will be on linux swarm nodes.
another complication, I am using tailscale for the network.  I cant seem to configure docker to use the tailscale network for listen-addr and advertise-addr.
it seems to work ok if I dont try to force it to use tailscale.
any ides?
I have tried looking for a config json file to add a tailscale dns entry. but cant find it on windows


text:
Q: How to use multiple css files for react pages? Im building a react application which has two pages(two react components) so far. My main issue here is that for each component i want there to be an external css file for it, but once there are two css files one files over writes the code in the other. For example, I have a homepage class which has some html code and is being routed to by the App.js file. I want to style my homepage component with a css file called home_style, this works fine if there is only one css file. Once i create another css file for that for my other component, it overwrites the code for the first css file(home_style) and ends up being applied for both my components. I had the idea of having all the code in one css file and set ids for each html component to be able to reference it properly, but i want to know if there is a better way to accomplish this.

A: Importing different css files into your js file doesn't mean it will only affect this js file only. In React, A css file is global, so you need to encapsulate your css with a parent :
// component1.js
const Component1 = () => {
  return (

      This is the component 1

  )
}

// component2.js
const Component2 = () => {
  return (

      This is the component 2

  )
}

Here I use the same class red in my two components. So in my css, if I want these same classes to do different things, i'll need to encapsulate it (as you said) :
//component1.css
.component1 .red {
  color: red;
}

// component2.css
.component2 .red {
  background-color: red;
}

Importing my css files or just writing this in a global css file will work, but if you are looking for some other solution, you can ahve a look at Styled components or JSS (These are just examples, there is multiple solutions to manage css in React, like simply using SCSS for easier encapsulation).


text:
Q: No me funciona el conteo del for en javascript Quisiera hacer un bucle repetitivo para llenar un array y que es este sea comparado si es un numero o no pero el ciclo for no me contea los ciclos y se corta al primer dato numerico
Aca abajo dejo el codigo es javascript
let piloto1 = [];
let piloto2 = [];

for(var i=0; i < 10; i++)
{
  if (i < 1)
    {
    piloto1[0] = prompt("ingrese el nombre del piloto 1");
    }
  else if (i < 9 )
    {
      var tiempo;
      var tiempoP;
      if (isNaN(tiempo))
      {
        do {
          tiempo = Number(prompt("ingrese el tiempo de la carrera " + i));
        } while (isNaN(tiempo));
      }
      if (isNaN(tiempoP))
      {
        do {
          tiempoP = Number(prompt("ingrese el tiempo penalizado de la carrera " + i));
        } while (isNaN(tiempoP));
        piloto1[i] = tiempo + tiempoP;
      }
    }
}

console.log(piloto1);

A: Te recomiendo que las declaraciones de las variables tiempo se encuentren fuera del for y justo antes de finalizar el for, les asignes valores de null. Ya que en cada ciclo se repiten los valores de la pasada anterior y como estos son valores numéricos, el if los ignora.
var tiempo;
var tiempoP;

for() {
...
tiempo = null;
tiempoP =null;
}

A: isNaN siempre es falso, por que siempre lo declaras antes de darle un valor es decir la crearlo es tipo numerico pero no tiene dato por lo tanto su primer valor es empty eso se repite 9 veces, lo ideal es que ese if este dentro del DoWhile


text:
Q: WPF: Change the user control programatically I am new to WPF, I  wanted to display a window with multiple user controls.
example.xaml
<DockPanel>

<Border x:Name ="TopRegion" DockPanel.Dock = "top">
    <local:userControl1/>
 </Border>

<Border x:Name ="leftRegion" DockPanel.Dock = "left">
    <local:userControl2/>
 </Border>

</DockPanel>

The usercontrol1 and usercontrol2 are other views in the same  project. I.e usercontrol1.xaml and usercontrol2.xaml.
Problem is that i need to change the usercontrol of  leftRegion from usercontrol2 to usercontrol3 during run time i.e programatically.
How to achieve this in example.xaml.cs program.

A: You already named the Border leftRegion, so you could use this Border to set a new child like
leftRegion.Child = new userControl3();

programatically in code behind.
This means you are replacing the instance of userControl2 of the Border with a new instance of userControl3.

A: While this is a legitimate request, it crosses with the logic of XAML and data binding, so I would suggest an alternative way that will have the same effect for end-user but is more in the spirit of XAML.
The solution is simple - just have both controls in your XAML and switch their Visibility based on whether you need one or another control to be displayed.


text:
Q: how to get not duplicated results in mysql I am trying to get results from mysql by not letting a specific field gets repeated more than 5 times.
For example, lets say that I have a table like this :
-------------
Name        City
person1     Nashville
person2     Nashville
person3     Nashville
person4     Nashville
person5     Nashville
person6     Nashville
person7     New York
-------------

What I want it to return is this :
-------------
Name        City
person1     Nashville
person2     Nashville
person3     Nashville
person4     Nashville
person5     Nashville
person7     New York
-------------

where the city field cannot be repeated more than five times! if it was repeated more than fix times, only return the first five results.
This question could be impossible (that is what I am guessing) but if there is a solution or anyway to work around what I am trying to achieve, please tell me! I can use PHP.

A: How about something like this which uses variables to check the current row to the previous row, if they are the same then the row number will increase if they are not the row number will reset:
select name, city
from
(
  select name,
    city,
    @row:=(case when @prev=city then @row else 0 end) + 1 as rownum,
    @prev:=city pcity
  from yourtable
  order by city, name
) src
where rownum <= 5

See SQL Fiddle with Demo
The result is:
|    NAME |      CITY |
-----------------------
| person1 | Nashville |
| person2 | Nashville |
| person3 | Nashville |
| person4 | Nashville |
| person5 | Nashville |
| person7 |  New York |

A:     SELECT x.*
      FROM my_table x
      JOIN my_table y
        ON y.name <= x.name
       AND y.city = x.city
     GROUP
        BY x.city
         , x.name
    HAVING COUNT(*) <= 5;

A: Are you allowed to perform more than one MySql command? If so, you can try doing two separate calls --
SELECT name, city FROM table WHERE city = 'Nashville' ORDER BY name LIMIT 5;
SELECT name, city FROM table WHERE city <> 'Nashville' ORDER BY name;

Someone may need to check on this but the general idea stands. The only problem with this is your end result would not have the table ordered by name. Rather, it'd have the people with the city has 'Nashville' first, and then everyone else.


text:
Q: FBAudienceNetwork interstitial ads displayed upside down when orientation is landscape right On landscape left it is fine but when I rotate the device as landscape right, advertisements mostly displayed upside down (behaves like device orientation is landscape left).
I tried both 4.25.0 and 4.26.0 FBAudienceNetwork SDK versions.
And devices: iPhone 5 (iOS 10.3.3), iPod touch 5 (iOS 9.3.5)
I also tried the sample project on https://github.com/fbsamples/audience-network and it behaves same.
When I search about the issue I faced, could not see any other people complains about it.
Is there such problem or am I doing something wrong?


text:
Q: How to change character limit in split sms javascript? I am using split-sms
it splits segment by 2 when character is over 160 and unicode character is over 70. But I want to change this behavior.
I want to do 153 character limits and 67 characters limit in unicode.
Can anyone give me a hint where to change?

A: Looks like uou need to modify the code provided by split-sms.js
in
module.exports.split = function (message, options) {
...
if (isGsm) {
    splitResult = gsmSplitter.split(message, options);
    singleBytes = 153;
    multiBytes = 146;
    charBytes = 1;
  } else {
    splitResult = unicodeSplitter.split(message, options);
    singleBytes = 134;
    multiBytes = 128;
    charBytes = 2;
  }
....
}


text:
Q: Get SharePoint List with Python I am trying to find any way possible to get a SharePoint list in Python. I was able to connect to SharePoint and get the XML data using Rest API via this video: https://www.youtube.com/watch?v=dvFbVPDQYyk... but not sure how to get the list data into python. The ultimate goal will be to get the SharePoint data and import into SSMS daily.
Here is what I have so far..
import requests
from requests_ntlm import HttpNtlmAuth
url='URL would go here'
username='username would go here'
password='password would go here'
r=requests.get(url, auth=HttpNtlmAuth(username,password),verify=False)

I believe these would be the next steps. I really only need help getting the data from SharePoint in Excel/CSV format preferably and should be fine from there. But any recommendations would be helpful..
#PARSE XML VIA REST API
#PRINT INTO DATAFRAME AND CONVERT INTO CSV
#IMPORT INTO SQL SERVER
#EMAIL RESULTS

A: from shareplum import Site
from requests_ntlm import HttpNtlmAuth

server_url = "https://sharepoint.xxx.com/"
site_url = server_url + "sites/org/"

auth = HttpNtlmAuth('xxx\\user', 'pwd')
site = Site(site_url, auth=auth, verify_ssl=False)
sp_list = site.List('list name in my share point')
data = sp_list.GetListItems('All Items', rowlimit=200)

A: this can be done using SharePlum and Pandas
following is the working code snippet
import pandas as pd     # importing pandas to write SharePoint list in excel or csv
from shareplum import Site
from requests_ntlm import HttpNtlmAuth

cred = HttpNtlmAuth(#userid_here, #password_here)
site = Site('#sharePoint_url_here', auth=cred)

sp_list = site.List('#SharePoint_list name here') # this creates SharePlum object
data = sp_list.GetListItems('All Items') # this will retrieve all items from list

# this creates pandas data frame you can perform any operation you like do within
# pandas capabilities

data_df = pd.DataFrame(data[0:])
data_df.to_excel("data.xlsx")

please rate if this helps.
Thank you in advance!

A: I know this doesn't directly answer your question (and you probably have an answer by now) but I would give the SharePlum library a try. It should hopefully simplify the process you have for interacting with SharePoint.
Also, I am not sure if you have a requirement to export the data into a csv but, you can connect directly to SQL Server and insert your data more directly.
I would have just added this into the comments but don't have a high enough reputation yet.

A: I can help with most of these issues
import requests
import xml.etree.ElementTree as ET
import csv

from requests_ntlm import HttpNtlmAuth

response = requests.get("your_url", auth=HttpNtlmAuth('xxxx\\username','password'))
tree =  ET.ElementTree(ET.fromstring(response.content))
tree.write('file_name_xml.xml')
root = tree.getroot()

#Create csv file
csv_file = open('file_name_csv.csv', 'w', newline = '', encoding='ansi')
csvwriter = csv.writer(csv_file)

col_names = ['Col_1', 'Col_2', 'Col_3', 'Col_n']
csvwriter.writerow(col_names)

field_tag = ['dado_1', 'dado_2', 'dado_3', 'dado_n']

#schema XML microsoft
ns0 = "http://www.w3.org/2005/Atom"
ns1 = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"
ns2 = "http://schemas.microsoft.com/ado/2007/08/dataservices"

for member in root:
    if member.tag == '{' + ns0 + '}entry':
        for element in member:
            if element.tag == '{' + ns0 + '}content':
                data_line = []

                for field in element[0]:
                    for count in range(0, len(field_tag)):
                        if field.tag == '{' + ns2 + '}' + field_tag[count]:
                            data_line.append(field.text)

                csvwriter.writerow(data_line)

csv_file.close()


text:
Q: WPF Selecting the Control that should play Storyboard Animation from Code Behind I have created a MainMenu and two Animations: ZoomIn & ZoomOut.
The MainMenu will be filled with Canvas, each containing icons. What I am trying to do, is on clicking a button, that the current visible panel disapear with ZoomOut and clicked Panel appear with ZoomIn.
So far I have managed to call the Animation from Code Behind using this:
Dim ZoomOut As Storyboard = DirectCast(FindResource("storyZoomOut"), Storyboard)
    ZoomOut.Begin()

But now I want the particular control to animate. Also is it possible to animate two diferent controsl at the same time? like Canvas1 ZoomOut and Canvas2 ZoomIn at the same time?
<Storyboard x:Key="storyZoomOut">
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Opacity)" Storyboard.TargetName="pnlCompras">
            <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="0.8"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="0.6"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="0.4"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.4" Value="0.2"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.5" Value="0.0"/>
        </DoubleAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleX)" Storyboard.TargetName="pnlCompras">
            <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="1.04"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="1.09"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="1.15"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.4" Value="1.3"/>
        </DoubleAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[0].(ScaleTransform.ScaleY)" Storyboard.TargetName="pnlCompras">
            <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="1.04"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.2" Value="1.09"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.3" Value="1.15"/>
            <EasingDoubleKeyFrame KeyTime="0:0:0.4" Value="1.3"/>
        </DoubleAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.X)" Storyboard.TargetName="pnlCompras">
            <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="0"/>
        </DoubleAnimationUsingKeyFrames>
        <DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.RenderTransform).(TransformGroup.Children)[3].(TranslateTransform.Y)" Storyboard.TargetName="pnlCompras">
            <EasingDoubleKeyFrame KeyTime="0:0:0.1" Value="0"/>
        </DoubleAnimationUsingKeyFrames>
    </Storyboard>

thanks all for your help!

A: You could remove the Storyboard.TargetName="pnlCompras" setting from all the animations in your Storyboards and then run a Storyboard on any control by Storyboard.Begin(FrameworkElement).
Dim ZoomOut As Storyboard = DirectCast(FindResource("storyZoomOut"), Storyboard)
ZoomOut.Begin(someControl)

A: You can also use these lines in your event
Dim ZoomOut As Storyboard = DirectCast(FindResource("storyZoomOut"), Storyboard)
ZoomOut.Begin( --Control-- )

or
Test with this other line
DirectCast(FindResource("storyZoomOut"), Animation.Storyboard).Begin()


text:
Q: Load High quality image to imageview I want to load a 15Mb image file into an imageview.. I tried loading it using piccasa and some other ways, But all return out of memory exception.
The code I used is
       Picasso.with(getActivity()).load(R.drawable.highqual).into(imageView);

Is there any way to make it possible in android

A: try this:
call this function decodeSampledBitmapFromFile(String filePath,int reqWidth, int reqHeight)
which reqHeight and reqWidth is your ImageView dimension. also note that if it takes long time and send you ANR run it on a separate thread then set it to your ImageView.
the code is from doc that I changed it to read image file.
public static int calculateInSampleSize(
            BitmapFactory.Options options, int reqWidth, int reqHeight) {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize = 1;

    if (height > reqHeight || width > reqWidth) {

        final int halfHeight = height / 2;
        final int halfWidth = width / 2;

        // Calculate the largest inSampleSize value that is a power of 2 and keeps both
        // height and width larger than the requested height and width.
        while ((halfHeight / inSampleSize) > reqHeight
                && (halfWidth / inSampleSize) > reqWidth) {
            inSampleSize *= 2;
        }
    }

    return inSampleSize;
    }

    public static Bitmap decodeSampledBitmapFromFile(String filePath,int reqWidth, int reqHeight) {

        // First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(filePath, options);
    }

Reference:
Loading Large Bitmaps Efficiently


text:
Q: "Valet parking " or "parking valet" Which one is the correct form?

"parking valet" or  "valet parking"

"Valet parking" is commonly used, but it seems that "parking valet" is also correct!
What's the grammatical explanation of these two correct forms of the phrase?

A: The "parking valet" is the person who parks your car.
The "valet parking" is the facility that is offered.
If those phrases are part of an advertisement, they effectively mean the same thing, respectively

We have a valet who will park your car.
  We offer a car parking service.

Both your phrases consist of two nouns, and in each case the second word is the actual noun, while the first word is a noun adjunct. This is a noun used like an adjective.


text:
Q: Unix permission to load a csv file into MySQL I am having problems trying to load my .csv file into MySQL on my Centos box.  My file is called 'OD_Orders.csv' is located in my home directory called /home/kam/KamSQLData
The error I get when I tried to load up the file into MySQL is:
mysql> LOAD DATA LOCAL INFILE '/home/kam/KamSQLData/OD_Orders.csv' INTO TABLE orders FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n';
ERROR 13 (HY000): File '/home/kam/KamSQLData/OD_Orders.csv' not found (Errcode: 13)
I did some reading and the usual culprit is Unix permissions are off or wrong.  I than proceed to create a group (called KamSQLData) so the userid of 'mysql' and 'kam' can share the group on /home/kam/KamSQLData:
KamSQLData:x:512:mysql,kam
I then proceed to set /home/kam/KamSQLData as the group of 'KamSQLData', thinking both kam and mysql will have access to it.

-rwxr-xrwx.  1 root KamSQLData     2322 Feb 15 14:03 OD_Orders_2019-01-28.csv
-rwxr-xrwx.  1 root KamSQLData     5282 Feb 15 14:03 OD_Orders_2019-01-25.csv
-rwxr-xrwx.  1 root KamSQLData     4428 Feb 15 14:03 OD_Orders_2019-01-24.csv
-rwxr-xrwx.  1 root KamSQLData     9784 Feb 15 14:03 OD_Orders_2019-01-23.csv
-rwxr-xrwx.  1 root KamSQLData     3795 Feb 15 14:03 OD_Orders_2019-01-22.csv
-rwxr-xrwx.  1 root KamSQLData    11004 Feb 15 14:03 OD_Orders_2019-01-18.csv
-rwxr-xrwx.  1 root KamSQLData     3528 Feb 15 14:03 OD_Orders_2019-01-17.csv
-rwxr-xrwx.  1 root KamSQLData     5655 Feb 15 14:03 OD_Orders_2019-01-16.csv
-rwxr-xrwx.  1 root KamSQLData     2959 Feb 15 14:03 OD_Orders_2019-01-15.csv
-rwxr-xrwx.  1 kam  KamSQLData 27084955 Feb 15 14:21 OD_Orders.csv
drwx------. 12 kam  kam            4096 Feb 15 14:21 ..
drwxr-srwx.  2 root KamSQLData    20480 Feb 15 14:36 .

Than i went ahead and set the following to my directory:
sudo chmod -R 2775 /home/kam/KamSQLData/

A: I ended taking the suggestion of Haxiel, where is never a good idea to make changes to the home directory (since everyone creation account(s) starts there). I placed my source data folder on /tmp and it already had the proper permission on that folder already (though I did run chmod -R 2775 to make sure). I was able to Load my .csv file(s) from that directory without modifying anything on SELinux or the home directory permission.


text:
Q: No F & P values for main effects in R I'm running repeated-measures ANOVAs using aov in R, and all variables are within-subjects.
But R is not showing main effects. Several people have looked at my code, and no one knows why. It looks like:
test1 = aov(y ~ (a*b+c) + Error(Subject/a*b+c), mydata))

But when I run summary(test1), I only get one P value:
             Df Sum Sq Mean Sq F value Pr(>F)
a:b           4 431859  107965   2.637  0.185

For main effects a, b, c I am only getting Df Sum Sq Mean Sq.
I also tried switching to "afex", and doing this:
test1 <- aov_ez("Subject", "y", mydata, within = c("a", "b", "c"))

But then the summary does not allow me to do a complex interaction, like a*b+c. Not all variables interact in my model. I need two to interact, but I have to control for the main effect of the other.


text:
Q: Saving more than one array in sequence in CSV file I am using this function to generate CSV file
function array_to_csv($input, $delimeter=',', $linebreak="\n", $enclosure='"') {
  if (!is_array($input))
    die("Please provide an array of data.");

 // $keys = array_keys($input);
  $values = array_values($input);

  foreach ($values as $k => $v) {
    // Not refactored
    $values[$k] = $enclosure.str_replace($enclosure, $enclosure.$enclosure, $v).$enclosure;
  }

  //print implode($delimeter, $keys);
  //print $linebreak;
  //print implode($delimeter, $values);

 $write = implode($delimeter, $values);
 $file='abc.csv';
$fp = fopen($file, "w");
fwrite($fp, $write);
  fclose($fp);

}

In php I call this function as:
array_to_csv($title, $delimeter=',', $linebreak="\n", $enclosure='"');

$title is my array I am passing to the function. Till this point, everything is okay, file is successfully saved.
Now I want to writing CSV file using same function while calling more than 1 function such that:

1: first element of array1 is written in file
  2: first element of array2 is written in file
  3: first element of array3 is written in file

How can I accomplish this task? Have any one idea about it?


text:
Q: Работа с DLL, способы вызова функций У меня очень "новичковый" вопрос (никогда в жизни не работал с DLL) и состоит он в следующем:
У меня есть 3 файла f1.c f2.c f3.c. В каждом из них вот по таким функциям:
// f1.c
int f1()
{
    return 2;
}

// f2.c
int f2()
{
    return 4;
}

// f3.c
int f3()
{
    return 10;
}

потом я получил три отдельных объектных файла, с помощью команды (использую mingw по windows):
gcc -c f1.c f2.c f3.c

и далее я создаю DDL-ку, командой:
gcc f1.o f2.o f3.o -o test1.dll -shared

получился файл test1.dll
С помощью DLL Export Viewer я открыл и посмотрел свой DLL файл:

Как я теперь могу динамически или статически (вот это я еще плохо понял) обращаться к этой библиотеки, для вызова функций f1(), f2() ( а если бы в функции были бы параметры входные? ) например из своего C++ приложения? Что я вообще могу делать с этим файлом?
Извиняюсь за немного глупый вопрос
A: Случайно удалил свой ответ, что смог восстановил. Давно уже не работал, там все очень просто, разбираться не сложно, примерно так:

*

*если динамически, загружаете dll, получаете ссылку на функцию по имени (напр. "f1"), используете функцию по ссылке;

*если статически, подключаете библиотеку к проекту, объявляете внешнюю функцию и сразу можно вызывать в программе.

В обоих случаях надо знать прототип функции. Более подробно см.:

*

*http://www.firststeps.ru/mfc/winapi/r.php?22

*http://www.firststeps.ru/mfc/winapi/r.php?41

Надо еще разобраться с методами вызова функций:  http://ru.wikipedia.org/wiki/Соглашение_вызова
A: Все сводится к вызовам LoadLibrary, FreeLibrary и GetProcAddress. Посмотрите здесь на пример: использование dll.


text:
Q: Изменение класса div по клику на radio кнопку Как убрать черный квадрат по клику на радио кнопку через display:none?
Подскажите пожалуйста.

.block {
color: #fff;
background: #000;
height: 100px;
width: 100px;
}
<input id="myid" class="myclass" type="radio" name="myname"/>

A: Можно и на css это реализовать, только эти элементы должны иметь одного родителя

.block {
  color: #fff;
  background: #000;
  height: 100px;
  width: 100px;
}

.block {
  margin-top: 5px;
  color: white;
}

#myid:checked~.block {
  display: none;
}

  <input id="myid" class="myclass" type="radio" name="myname" />

    block-1

    block-2

A: Или так через jQuery:

$('#myid').on('change', function() { $('.block').hide(); });
.block {
color: #fff;
background: #000;
height: 100px;
width: 100px;
}

<input id="myid" class="myclass" type="radio" name="myname"/>

A: <input id="myid" class="myclass" type="radio" name="myname"
  onclick="document.querySelector('.block').style.display='none';"/>

или
.block-hide {
  display:none;
}

<input id="myid" class="myclass" type="radio" name="myname"
  onclick="document.querySelector('.block').classList.add('block-hide');"/>


text:
Q: Android excessive SurfaceFlinger login for simple Cordova app I have a very basic Cordova app rendering a small react site (the most basic one, created with create-react-app). This features a react svg logo spinning around in a slow animation.
When running this app and checking the logs with adb logat, I constantly get the following sequence:
D/SurfaceFlinger(  279): FPS : 60.19
W/SurfaceFlinger(  279): Fail to Open /sys/devices/platform/gpusysfs/fps

I don't really think this problem is related to my app specifically, but it still bugs me. Anything to do about it?
I'm running on a Samsung GT-I9505 with Android 5.0.1.

A: The problem is affecting all Samsung GT-I95XX.
D/SurfaceFlinger: FPS : 15.99
W/SurfaceFlinger: Fail to Open /sys/devices/platform/gpusysfs/fps
    TIMA: QCOM_send_command--int8_t QCOM_send_command(TIMA_handle_t, void*, uint32_t, void*, uint32_t, uint32_t)
    rsp_len = 1008 rcvd_data_len = 1040, self_calculate_len=1040

I think it's linked to a security issue which caused a buffer Overflow.
Google (laginimaineb) said it's fixed now, but the service "SurfaceFlinger" is still trying to access it, in a infinite loop.
And it eats a lot of battery too...


text:
Q: How to do Jenkins with Selenium and Internet Explorer Maybe because most build servers are linux and so irrelevant or most people use slaves, but I'm finding not much information for this problem.
I have a jenkins server on Windows Server 2012. I'm trying to run Selenium tests on it(for a Vaadin app if it matters). It's great under Chrome and Firefox, but for IE it doesn't seem to want to do anything. This works fine on the desktop. Some investigation found the selenium site saying the Selenium IE WebDriver doesn't work under services. Fine so I tried to run it from the command line(java -jar jenkins.war), but when I start jenkins it doesn't have any of my existing jobs.
So I have one multipart question: (1) What's the best way to do selenium tests for IE on jenkins? and (2) if it's to start jenkins from the command line, what's the best way to do that?

A: *

*stop the jenkies slav service

*Open a browser on the slave machine and go to the Jenkins master server url (http://yourjenkinsmaster:8080).
Go to Manage Jenkins > Manage Nodes, Click on the slave machine.
3.run in cmd the line in option: run frome slave commandline For example:
javaws http://{yourjenkinsmaster}:8080/computer/{slav name}/slave-agent.jnlp

new jenkies run whith GUI and ie run ok
to run it all day :
save this line in bat file in startup folder


text:
Q: Use a variable before its declaration I am writing a Python script and I have a problem of variable declaration, here is a part of my script :
if chromosome :
    if chromosome.group(1) != '1' :
        output.close()
        print str(base)+" bases found in chromosome "+chr_name
        chr_name = chromosome.group(1)
    output = open(current_dir+"/"+name+"3/"+name+".chr"+chromosome.group(1)+".wig", "w")
    output.write("fixedStep chrom=chr"+chromosome.group(1)+" start=1 step=1\n")

As you can see, I close my output before to create it in the code, but in the facts, this would never happens because you cannot enter the condition before to create the file.
I can make something dirty, opening a tmp file before my condition, but that's not very elegant. So I was wondering if there is another solution to make Python happy ?
EDIT :
if chromosome :
    if chromosome.group(1) != '1' :
        print str(base)+" bases found in chromosome "+chr_name
        chr_name = chromosome.group(1)
    with open(current_dir+"/"+name+"3/"+name+".chr"+chromosome.group(1)+".wig") as output:
        output.write("fixedStep chrom=chr"+chromosome.group(1)+" start=1 step=1\n")

EDIT2:
Here is an idea of the algorithm, maybe it could help understand the problem better :
for line in input do :
     chromosome = re.search(something)
     if chromosome :
          if chromosome != '1' :
              ouput.close()
          output = open(file+chromosome)
          output.write(title)
     elif somethingElse :
          output.write(somethingElse)
     endif
endfor

I want to create different files (file1, file2, file3...). Before to create file2, I have to close file1; before to create file3, I have to close file2; etc...  but for the first one (file1), I don't have to close anything !

A: You can use with statement, like this
with open(current_dir+"/"+name+"3/"+name+".chr"+chromosome.group(1)+".wig", 'w') as output:
    output.write("fixedStep chrom=chr"+chromosome.group(1)+" start=1 step=1\n")

You don't have to worry about closing the file explicitly.

A: Are you trying to do something like this:
if chromosome :
    if chromosome.group(1) != '1' :
        print str(base)+" bases found in chromosome "+chr_name
        chr_name = chromosome.group(1)
    else:
        output = open(current_dir+"/"+name+"3/"+name+".chr"+chromosome.group(1)+".wig", 'w')
        output.write("fixedStep chrom=chr"+chromosome.group(1)+" start=1 step=1\n")
        output.close()

        output = open("The next file")
        output.write("whatever")
        output.close()

or with improved file handling and str.format instead of adding strings:
if chromosome :
    if chromosome.group(1) != '1' :
        print str(base)+" bases found in chromosome "+chr_name
        chr_name = chromosome.group(1)
    else:
        with open({}/{}3/{}.chr{}.wig.format(current_dir,name,name,chromosome.group(1), 'w') as output:
            output.write("fixedStep chrom=chr"+chromosome.group(1)+" start=1 step=1\n")
        with open("The next file") as output:
            output.write("whatever")

A: This looks like a candidate for itertools.groupby:
pattern = re.compile(...)
for chromasome, lines in itertools.groupby(input, key=pattern.search):
    with open(filebase + chromosome, 'w') as f:
        for line in lines:
            ...

A: I'm not entirely sure what you're asking for, but I think you could easily solve this with a another nested if statement.
EDIT: too early this morning, forgot this is Python need to have something in the object
output = None
    for line in input do :
         chromosome = re.search(something)
         if chromosome :
              if chromosome != '1' :
                  if output != None :
                       output.close()
              output = open(file+chromosome)
              output.write(title)
         elif somethingElse :
              output.write(somethingElse)


text:
Q: How can I design my Spring program so that when a user logs in I can tell if they are a Staff member, student or faculty member? A little more detail. Like I said I'm building this University Management System and it will have user authentication. It will also user authorization for some parts of the web layer, for example only a Student will be able to access the Student web portal to add/drop classes and only a Faculty will be able to use the faculty portal to grade students and see their list of course.
Here is the problem: When someone logs in (This is all using Spring Security and Spring MVC btw) I need to be able to tell if this a student, faculty or staff ideally from the login info itself. And querying each table until I find a match seems like TERRIBLE design. Each Entity inherits from a common abstract class Person but the interface that they share is very basic, they have getters and setters for the ID, first name, last name ect. I could store the Authorization role in the abstract class and that would tell me if this Person instance is a Staff, Student or Faculty and then check the role to figure what specific subclass I am using but that seems contrived as well. Is there a intuitive and common sense way to approach this problem?

A: I think you could create an enum field in the entity class called userType, and then create a filter class that determine the access to the functions located in the api layer, based on the userType of the user. You can get the userType efficiently by requesting it from the DB and store it in a data structure (like HashMap) on the server after the user logged in.


text:
Q: ASP.NET Page with ReportViewer Gives the Error below I am having this error when I opening page with Reportviewer, and ideas
Server Error in '/' Application.
Index was outside the bounds of the array.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.IndexOutOfRangeException: Index was outside the bounds of the array.
Source Error:
An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.
Stack Trace:
[IndexOutOfRangeException: Index was outside the bounds of the array.]
   AjaxControlToolkit.MaskedEditExtender.set_CultureName(String value) +708
   AjaxControlToolkit.MaskedEditExtender.OnPreRender(EventArgs e) +326
   System.Web.UI.Control.PreRenderRecursiveInternal() +88
   System.Web.UI.Control.PreRenderRecursiveInternal() +160
   System.Web.UI.Control.PreRenderRecursiveInternal() +160
   System.Web.UI.Control.PreRenderRecursiveInternal() +160
   System.Web.UI.Control.PreRenderRecursiveInternal() +160
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +985


text:
Q: Workflow with Git and remote server I'm looking to improve our workflow using Git and our development servers.
We have it set up so in addition to our production and staging server, each dev generally runs their own local VM. We also keep our code in a GitLab repository.
Amongst the devs, there are two main ways we get our code on to the server:
- Push to GitLab, then pull from the local server
- Run a daemon on the local VM, then push directly to it
As you can imagine, this means we have to make many frequent commits as we are working on things. We try to work on a different branch for each feature, but it's still a bit cumbersome. I'd like us to start rebasing each branch or feature to a single commit so the log looks nice (no need to keep the intermediate steps).
However, as I understand it, once you've pushed to a remote server (like GitLab), rebasing because very difficult and impractical.
Is there a workflow where we can easily put files on our server via our repo, yet retain a means to rebase without creating lots of headaches?
Thanks.

A: You can use the "Squash commits" functionality when creating a Merge-Request. Squashing commits from a Merge Request means to compact all the commits in this request into only one commit.

If you don't want to use the GitLab interface for that:
# If you want to merge my-feature-branch to master
git checkout master
git merge --squash my-feature-branch


text:
Q: SLURM leaves nextflow jobs job pending in node I am running a nextflow script on my HPC which is run by SLURM. My job consists of processing thousands of small files. So heavy I/O but very little computational effort per job ~ 5min per job. When I submit my job Next-Flow will spawn jobs and they will be processed but they sit largely idle for most of the time. I spoke to the admin and they said once I am assigned resources I have them for the full time I requested. I am confused why I should be in pending status at all.
Any help is much appreciated
my submission script
#!/bin/bash

#SBATCH --ntasks-per-node=1
#SBATCH --nodes=1
#SBATCH --partition=general
#SBATCH --mem=500MB
#SBATCH -t 02-00:00:00
#SBATCH --mail-type=BEGIN,REQUEUE,FAIL,END
#SBATCH --mail-user= me@email.com

work_dir=/pine/scr/
image_set=$1
export NXF_CLUSTER_SEED=$(shuf -i 0-16777216 -n 1)

srun $work_dir/nextflow -c $work_dir/nextflow.config run $work_dir/image_processing.nf --folder $image_set -with-mpi
sacct -j $SLURM_JOB_ID --format='JobID,user,elapsed, cputime, totalCPU,MaxRSS,MaxVMSize, ncpus,NTasks,ExitCode'

my nextflow.config file
process.container = '/pine/scr/m/j/mjrich/longleaf.sif'
singularity.enabled = true
singularity.autoMounts = true

process {
  executor='slurm'
  memory='500MB'
  pollInterval = '10 min'
  dumpInterval = '10 min'
  exitReadTimeout = '10 min'
  killBatchSize = 50
}

my directives on the offending process
    publishDir "$projectDir/processed_images/$folder", mode: 'move', overwrite: true, pattern: 'image-*.jpeg'
    publishDir "$projectDir/processed_images/$folder/failed", mode: 'move', overwrite: true, pattern: 'failed-*.jpeg'
    errorStrategy 'ignore'
    maxForks 5
    memory '500 MB'
    time '10m'
    cpus 1

A: I think your pollInterval of 10 minutes might be too high for the anticipated job duration. From the Nextflow Scope executor, docs:

pollInterval - Determines how often a poll occurs to check for a
process termination.

Perhaps try changing this to:
pollInterval = '30 sec'


text:
Q: VTK 7 - why object gets destroyed? I am trying to load raw image data using vtkImageImport and display 2D texture:
    char* data = (char*)imgData->data(); // size is 786432

    vtkSmartPointer<vtkImageImport> importer = vtkSmartPointer<vtkImageImport>::New();
    importer->SetWholeExtent(0, 511, 0, 511, 0, 0);
    importer->SetDataExtentToWholeExtent();
    importer->SetDataScalarTypeToUnsignedChar();
    importer->SetImportVoidPointer(data);
    importer->SetNumberOfScalarComponents(3);
    importer->Update();
    double bounds[6];
    vtkImageData* vtk_image_data = importer->GetOutput(); // this is null
    vtk_image_data->GetBounds(bounds);

When I call importer->Update() then destructor of vtkDataSet is invoked, and importer->GetOutput() returns null... Any ideas why that happens?

A: I compiled and ran your code on MSVC 2010 with VTK 6.2.0. I did not get any  null vtk_image_data. check out some macro pre-processors it might help.

A: Finally, I have found cause of the problem. In general, we are porting VTK to use with Google Chrome's Portable Native Client (PNaCl) and I had to create project vtkCommonCore from scratch and set all settings to work with PPAPI\PNACL. I was missing special build rule for vtkInformationDataObjectKey.cxx which has to be set manually in .vcxproj:
<ClCompile Include="vtkInformationDataObjectKey.cxx">
      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">vtkCommonDataModel_ENABLED;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">vtkCommonDataModel_ENABLED;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='MinSizeRel|Win32'">vtkCommonDataModel_ENABLED;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='RelWithDebInfo|Win32'">vtkCommonDataModel_ENABLED;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <PreprocessorDefinitions Condition="'$(Configuration)|$(Platform)'=='Debug|PPAPI'">vtkCommonDataModel_ENABLED;%(PreprocessorDefinitions)</PreprocessorDefinitions>
      <!-- adding above rule for Debug|PPAPI solved the problem -->
</ClCompile>


text:
Q: What does 'GET OR SET ACCESSOR EXPECTED' mean? using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

public partial class RepeaterEx2 : System.Web.UI.Page {
    SqlConnection cn = null;
    SqlDataAdapter da = null;
    DataSet ds = null;
    String strSqlQuery = String.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        cn = new SqlConnection();
        cn.ConnectionString = "Server=(local);Data base=TestDb;Uid=sa;Password=123";
        if (!Page.IsPostBack)
        {
        }

    }
    void BindEmpData
    {
        SqlDataAdapter da=new SqlDataAdapter( "select e.ENO,e.ENAME,e.JOB,e.SAL,d.DNAME form EMPLOYEE e,DEPARTMENT d where e.DNO=d.DNO",cn);

        da.Fill(ds,"EMPLOYEE");//here showing set or get accessorexpected error at "da"
        Repeater1.DataSource=ds.Table["EMPLOYEE"];
        Repeater1.DataBind();

    }
}

I'm getting this error:

A get or set accessor expected

How do I resolve this error?

A: Parentheses is required to differentiate a method from a property that requires the get/set syntax

A: You need parentheses after the function name here:
void BindEmpData()
{
    ...
}

Also, you'll want to make sure you initialize the DataSet correctly:
void BindEmpData()
{
    SqlDataAdapter da = new SqlDataAdapter("select e.ENO,e.ENAME,e.JOB,e.SAL,d.DNAME form EMPLOYEE e,DEPARTMENT d where e.DNO=d.DNO",cn);
    DataSet ds = new DataSet();
    da.Fill(ds,"EMPLOYEE");
    Repeater1.DataSource = ds.Table["EMPLOYEE"];
    Repeater1.DataBind();
}

And at this point you can remove the ds and da class members, since they are no longer being used (they've been replaced by function variables).


text:
Q: Where is wrong in this reasoning about relativity? Consider two people A and B in 1-dimensional space. If in A's frame, he observes that B is $1$ light-year apart and moving at a constant speed of $c/2$ to the right, A would think if he sends a light signal, it would take $2$ light years in his frame for the signal to get to B. Because in A's frame, the relative speed of the light signal to B is $c/2$, and it takes $\frac{c}{c/2} = 2$ years to get to B.
But, if A thinks B is stationary and himself is moving to the left at constant velocity $c/2$, then if he sends a light signal to B it will cost 1 year in A's frame for B to receive it. ($t = \frac{c}{c} = 1$)
Where is wrong in this reasoning?

A:
If in A's frame, he observes that B is $1$ light-year apart and moving
  at a constant speed of $c/2$ to the right, A would think if he sends a
  light signal, it would take $\frac{3}{2}$ light years in his frame for
  the signal to get to B.

No, he wouldn't think that. It would take light $2$ years (not light-years unless you are setting $c=1$) and not $1.5$ years. Let's do this explicitly just to be sure. The trajectory of the light would be $x(t)=ct$ and the trajectory of B would be $x(t)=c \cdot 1 \text{year}+\frac{c}{2}t$ where $t$ is in years. So, they would meet when $ct=c \cdot 1 \text{year}+ct/2$ which gives us $t=2$ years.

But, if A thinks B is stationary and himself is moving to the left at
  constant velocity $c/2$, then if he sends a light signal to B it will
  cost 1 year in A's frame for B to receive it.

This is "not even wrong" to use the famous phrase. Because it doesn't convey any meaning. Here, you are doing something very confusing which sounds alright in English but isn't alright in physics. You are saying that while imagining that $A$ is moving to the left and $B$ is at rest, $A$ is calculating something in $A$'s frame. This is not possible to do. If you are imagining $A$ to be moving and $B$ to be at rest then, by definition, you are working in $B$'s frame (don't get me wrong, $A$ is totally allowed to use $B$'s frame but he just can't use both the frames together).
However, what you can ask is having used $B$'s frame consistently, what would $A$ predict about observations in his own frame using the principles of relativity? This is a legitimate thing to do and it should match with what someone using $A$'s frame would observe.
Notice that while using $B$'s frame, you'd have to make sure you are taking the relativity of simultaneity seriously because the problem is set up using a language which uses the concept of simultaneity in $A$'s frame (namely, when $B$ is such and such distance apart, $A$ does such and such. This fact that these two things are happening at the same time would only be true in $A$'s frame, not in $B$'s). On top of that, you'd obviously need to take care of length contractions and time dilations too. But this should be straightforward once you realize that you cannot both imagine yourself to be moving and use your own frame of reference. You can imagine yourself to be moving but then you have to use someone else's frame of reference (and then go on to predict what it would all have been looked like in your frame of reference).


text:
Q: online resources for spatial analysis I am wondering about some good online resources for learning how to implement spatial statistical techniques, like Moran's I and Geary's C, or even K Nearest Neighbors...any help is appreciated. Thanks!

A: Spatial Regression Models, by Michael D. Ward and Kristian Skrede Gleditsch is an exellent short introduction. Moran's I is explained on p.23.
Applied Spatial Data Analysis with R by Bivand, Pebesma, Gomez-Rubio is a popular choice for doing spatial modelling in R.
In terms packages, R , as usual, has many packages to do all sorts of spatial analysis. One package that computes Moran's I is ape
For spatial kringing and the likes: gstat, akima, fields, gss


text:
Q: Footer hides floating nav - Any way to slide floating nav up once it reaches the footer? I'm trying to add a floating navigation to the side bar. I have jquery floating the nav to the top after you begin scrolling. It works fine at the top, but once you reach the bottom the footer hides the navigation. The navigation needs to scroll up once it reaches a certain point. Any solutions?
 <script type="text/javascript">
   $(document).ready(function () {
var top = $('#floatingNav').offset().top - parseFloat($('#floatingNav').css('marginTop').replace(/auto/, 0));
$(window).scroll(function (event) {
var y = $(this).scrollTop();

  if (y >= top) {

     $('#floatingNav').addClass('fixed');
   } else {

     $('#floatingNav').removeClass('fixed');
   }
  });
});

</script>

Here's the example: http://psidev.inhousewp.synergydatasystems.com/products/

A: Give the navigation a higher z-index than the footer. Something like z-index:99; will definitly do it.

A: Is this like what you're looking for: http://jsfiddle.net/N5AC8/1/
$(document).ready(function() {
      var top = $('#floatingNav').offset().top - parseFloat($('#floatingNav').css('marginTop').replace(/auto/, 0));
      var maxTop = $(document.body).height() - $('footer').height() - $('#floatingNav').outerHeight();
      $(window).scroll(function(event) {
          var y = $(this).scrollTop();
          console.log(y, maxTop);
          $('#floatingNav').css({
              position: '',
              top: ''
          });
          if (y >= maxTop) {
              $('#floatingNav').css({
                  position: 'absolute',
                  top: maxTop
              });
          } else if (y >= top) {
              $('#floatingNav').addClass('fixed');
          } else {
              $('#floatingNav').removeClass('fixed');
          }
      });
  });

This is not really optimized, but should give you something to work from if it's what you're looking for.


text:
Q: Why does my UINavigationController crash on release configuration? I have a requirement to remove a previous view controller in a stack.  I have successfully used this method in the past, without any problems:
NSMutableArray *vcs = [NSMutableArray arrayWithArray:self.navigationController.viewControllers];
    BOOL removedFlag = YES;
    while (removedFlag == YES)
    {
        removedFlag = NO;
        for (UIViewController *vc in vcs)
        {
            if( ![vc isKindOfClass:[self class]] && ![vc isKindOfClass:[MenuVC class]] )
            {
                [vcs removeObject:vc];
                removedFlag = YES;
                break;
            }
        }
    }
    [self.navigationController setViewControllers:[NSArray arrayWithArray:vcs]];

Now I'm updating the app, and it mysteriously crashes on release configuration, not on debug.  In addition, there are no warnings whatsoever in debug mode.  I think something changed with the SDK.  It never did this before.
I've made a sample project available:
http://dl.dropbox.com/u/7834263/RemoveTest.zip
This is an ARC-enabled project.

A: The first line should actually be:
NSMutableArray *vcs = [self.navigationController.viewControllers mutableCopy];

NSMutableArray is a subclass of NSArray. arrayWithArray is a method of the NSArray class -- it creates an immutable array. The mutableCopy method creates a mutable copy of the original array. You never really should have been able to call removeObject on your vcs array because it was never actually an NSMutableArray -- it was an NSArray.

A: A simple way to remove the previous viewController in the stack could be:
 int vcIdx=[self.navigationController.viewControllers indexOfObject:self]-1;
 NSMutableArray *vControllers = [[NSMutableArray alloc] initWithArray:self.navigationController.viewControllers];
 [vControllers removeObjectAtIndex:vcIdx];
 self.navigationController.viewControllers=vControllers;


text:
Q: Almost conjugation-invariant neighborhoods of units in locally compact groups Let $G$ be a locally compact topological group with unity $e$ and left Haar measure $m$. Let also $g\in G$ be a given element and $U$ a neighborhood (of compact closure) of $e$.
I am interested to get another, smaller neighborhood $V$, contained in $U$, with the conjugation-invariance property $gVg^{-1}=V$ (with respect to the given element $g$).
This is immediate for Abelian $G$. Also, it is easy if the order of $g$ is finite, say $o(g)=n$, because then we can just take $V:=\cap_{j=0}^{n-1} g^jUg^{-j}$.
If $o(g)=\infty$, this may fail, as relatively easy examples can show. However, I would be satisfied by a quazi-invariance property: for any $0<\varepsilon<1$, find some $V\subset U$ with $m(V\cap gVg^{-})> (1-\varepsilon)m(V)$.
When do we have the first, or the approximative second, invariance property? What generally well-known properties, conditions ensure it and what groups (and for what kind of elements, besides of course having $o(g)=\infty$) or perhaps neighborhoods, (if the property depends on that) are such that it fails?