text:
Q: Prediction data from CSV file used ML.NET and ASP.NET MVC. Object reference not set to Model I am creating an application using ASP.NET MVC and ML.NET to calculate prediction over data contained in an Excel CSV file.
I use two models to display data: ModelInput and ModelOutput. When I start the application, I get an error that there are no objects generated from the model, in this case from ModelOutput.
Can someone tell me where I'm going wrong about loading the object from the model?
[enter image description here][1]
Code:
 @*
        For more information on enabling MVC for empty projects, visit
 https://go.microsoft.com/fwlink/?LinkID=397860
        *@
        @{
        }

        @model _01_ML_NET_NisML.Model.ModelOutput
        @{
        ViewData["Title"] = "OutPut - item Precipitation Prediction";
        Layout = "~/Views/Shared/_Layout.cshtml";
        }

ModelOutput - Welcome to Precipitation Prediction for the Item by Nis
 Location

using ML.NET in ASP.NET Core

        <meta http-equiv="refresh" content="600"></meta>

            <form asp-action="PrecipitationPrediction">

                    <input type="submit" value="PrecipitationPrediction" class="btn btn-
 primary" />

            </form>

        @if (ViewBag.Result != null)
        {

 Final Predicted Prediction Quantity are niz:  @ViewData["Prediction"]

                @{
                    //foreach (var item in
 (IEnumerable<_01_ML_NET_NisML.Model.ModelOutput>)ViewBag.data)
                    foreach (var item in
 (IEnumerable<_01_ML_NET_NisML.Model.ModelOutput>)ViewBag.data)
                    {

 @item.Prediction

                    }
                }

}

public class ModelInput
{
    [ColumnName("Year"), LoadColumn(0)]
    public float Year { get; set; }

    [ColumnName("MONTH_ID"), LoadColumn(1)]
    public float MONTH_ID { get; set; }

    [ColumnName("PRECIPITATION"), LoadColumn(2)]
    public float PRECIPITATION { get; set; }

    internal static IEnumerable<ModelOutput> Select(Func<object, object> p)
    {
        throw new NotImplementedException();
    }
}

public class ModelOutput
{
    //public float Score { get; set; }

    //[ColumnName("PredictedLabel")]
    [ColumnName("PredictedLabel")]
    public float Prediction { get; set; }
    public float Score { get; set; }

    //public float PRECIPITATION { get; set; }
    //public float Prediction { get; set; }
    //public float[] Score { get; set; } //float[]

    //public float Score { get; set; }
}

ConsumeModel.cs - Predict2 and Engine2 method used
public class ConsumeModel
{
    private static Lazy<PredictionEngine<ModelInput, ModelOutput>> PredictionEngine = new
    Lazy<PredictionEngine<ModelInput, ModelOutput>>(CreatePredictionEngine);

    private static PredictionEngine<ModelInput, ModelOutput> CreatePredictionEngine()
    {
        throw new NotImplementedException();
    }

    // For more info on consuming ML.NET models, visit https://aka.ms/mlnet-consume
    // Method for consuming model in your app
    public static ModelOutput Predict(ModelInput input)
    {
        /* DODATO po objasnjenju!!!
        // Add input data
        //var input = new ModelInput();

        // Load model and predict output of sample data
        //ModelOutput result = ConsumeModel.Predict(input);
        */

        ModelOutput result = PredictionEngine.Value.Predict(input);
        return result;
    }

    public static PredictionEngine<ModelInput, ModelOutput> Predict2(ModelInput input)
    {
        // Create new MLContext
        MLContext mlContext = new MLContext();

        //input = new ModelInput();

        // Load Trained Model
        DataViewSchema predictionPipelineSchema;

        // Load model & create prediction engine
        string modelPath = @"C:\Users\PavleiMila\AppData\Local\Temp\MLVSTools\01_ML_NET_NisML\01_ML_NET_NisML.Model\MLModel.zip";

        //ITransformer mlModel = mlContext.Model.Load(modelPath, out var modelInputSchema);
        ITransformer mlModel = mlContext.Model.Load(modelPath, out predictionPipelineSchema);

        var predEngine = mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>(mlModel);

        // Predicted Data
        ///IDataView predictions = mlModel.Transform((IDataView)input);
        // 6. Evaluate model on test data
        IDataView testData = mlContext.Data.LoadFromTextFile<ModelInput>("Padavine Nis-1946-
  2019 new1 test.csv", separatorChar: ',', hasHeader: true);
        IDataView predictions = mlModel.Transform(testData);
        //var metrics = mlContext.Regression.Evaluate(predictions, "Prediction");

        // Get Predictions
        float[] Score = (float[])predictions.GetColumn<float>("Score").ToArray();
        //var predEngine1 = mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>
 (mlModel);
        //IEnumerable<ModelOutput> predictions1 = ModelInput.Select(input =>
  predictionEnginePool.Predict(input));
        return predEngine;
        //return Score;
    }

    public static PredictionEngine<ModelInput, ModelOutput> Predict3(ModelInput input)
    {
        // Create new MLContext
        MLContext mlContext = new MLContext();

        //input = new ModelInput();

        // Load Trained Model
        DataViewSchema predictionPipelineSchema;

        // Load model & create prediction engine
        string modelPath = @"C:\Users\PavleiMila\AppData\Local\Temp\MLVSTools\01_ML_NET_NisML\01_ML_NET_NisML.Model\MLModel.zip";

        var trainingData = new List<ModelInput>
        {
            new ModelInput { Year = 1946, MONTH_ID = 1, PRECIPITATION = 8 },
            new ModelInput { Year = 1946, MONTH_ID = 2, PRECIPITATION = 8 },
            new ModelInput { Year = 1946, MONTH_ID = 3, PRECIPITATION = 7 },
            new ModelInput { Year = 1946, MONTH_ID = 4, PRECIPITATION = 26 },
            new ModelInput { Year = 1946, MONTH_ID = 5, PRECIPITATION = 94 },
            new ModelInput { Year = 1946, MONTH_ID = 6, PRECIPITATION = 24 },
            new ModelInput { Year = 1946, MONTH_ID = 7, PRECIPITATION = 3 },
        };

        //IDataView mlData = mlContext.Data.LoadFromEnumerable(modelPath, out
  predictionPipelineSchema);
        IDataView mlData = mlContext.Data.LoadFromEnumerable<ModelInput>(trainingData);

        var dataPrepPipeline = mlContext.Transforms.Text.FeaturizeText("YearF", "Year")

 //.CopyColumns(DefaultColumnNames.PredictedLabel, nameof(ModelOutput.Prediction))

 .Append(mlContext.Transforms.Text.FeaturizeText("Year", "Year"))

.Append(mlContext.Transforms.Concatenate("Features", "Year", "MONTH_ID"))

 .Append(mlContext.Transforms.NormalizeMinMax("Features", "Features"))
                                                         .AppendCacheCheckpoint(mlContext);

        var dataPrepModel = dataPrepPipeline.Fit(mlData);
        var dataPrepDataView = dataPrepModel.Transform(mlData);

        var pipeline = dataPrepPipeline.Append(

 mlContext.BinaryClassification.Trainers.AveragedPerceptron(labelColumnName: "Precipitation",
 numberOfIterations: 10, featureColumnName: "PredictedLabel"));

        mlContext.Model.Save(dataPrepModel, dataPrepDataView.Schema, "./dataprep.zip");

        var model = pipeline.Fit(mlData);

        var modelDataView = model.Transform(mlData);

        mlContext.Model.Save(model, modelDataView.Schema, "./model.zip");

        var predEngine = mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>
 (model);

        return predEngine;
        //return Score;
    }

    public static PredictionEngine<ModelInput, ModelOutput> CreatePredictionEngine(IDataView
 input) //()
    {

        // Create new MLContext
        MLContext mlContext = new MLContext();

        //input = new ModelInput();

        // Load Trained Model
        DataViewSchema predictionPipelineSchema;

        // Load model & create prediction engine
        string modelPath = @"C:\Users\PavleiMila\AppData\Local\Temp\MLVSTools\01_ML_NET_NisML\01_ML_NET_NisML.Model\MLModel.zip";

        //ITransformer mlModel = mlContext.Model.Load(modelPath, out var modelInputSchema);
        ITransformer mlModel = mlContext.Model.Load(modelPath, out predictionPipelineSchema);

        var predEngine = mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>
(mlModel);

        // Predicted Data
        IDataView predictions = mlModel.Transform(input);

        // Get Predictions
        //float[] Score = (float[])predictions.GetColumn<float>("PredictedLabel");
        float[] Score = (float[])predictions.GetColumn<float>("Score").ToArray();

        return predEngine;
        //return metrics;
    }

    public static ModelOutput CreatePredictionEngine1(IDataView input) //()
    {
         // 1. Initialize ML.NET environment
        MLContext mlContext = new MLContext();

        // 2. Load training data
        IDataView trainData = mlContext.Data.LoadFromTextFile<ModelInput>("Padavine Nis-1946-
2019 new1 train.csv", separatorChar: ',', hasHeader: true);

    // 3. Add data transformations
    var dataProcessPipeline =
 mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "Prediction", "Score")

 .Append(mlContext.Transforms.Concatenate(outputColumnName: "Features", "Year", "MONTH_ID"));

    // 4. Add algorithm
    var trainer = mlContext.Regression.Trainers.Sdca(labelColumnName: "Prediction",
 featureColumnName: "Features");
    var trainingPipeline = dataProcessPipeline.Append(trainer);

    // 5. Train model
    var model = trainingPipeline.Fit(trainData);

    // 6. Evaluate model on test data
    IDataView testData = mlContext.Data.LoadFromTextFile<ModelInput>("Padavine Nis-1946-2019
 new1 test.csv", separatorChar: ',', hasHeader: true);
    IDataView predictions = model.Transform(testData);
    var metrics = mlContext.Regression.Evaluate(predictions, "Prediction");
    Console.WriteLine($"Model Quality" + $"(RSquared):{metrics.RSquared}");
    Console.WriteLine($"Model Quality", metrics);

        // 7. Predict on sample data and print results
        var input1 = new ModelInput
     {
            Year = 1946,
            MONTH_ID = 1,
            PRECIPITATION = 8,
     };

        var result = mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>
(model).Predict((ModelInput)input1);
        Console.WriteLine($"Predicted fare: " + $"{result.Prediction}");

        // Save trained model
        mlContext.Model.Save(model, trainData.Schema, "MLModel.zip");

        return (ModelOutput)predictions;
        //return result.Prediction;
    }

    public static ModelOutput CreatePredictionEngine2() //()
    {
        // 1. Initialize ML.NET environment
        MLContext mlContext = new MLContext();

        // 2. Load training data
        IDataView trainData = mlContext.Data.LoadFromTextFile<ModelInput>("Padavine Nis-1946-
 2019 new1 train.csv", separatorChar: ',', hasHeader: true);

        // 3. Add data transformations
        var dataProcessPipeline =
 mlContext.Transforms.Categorical.OneHotEncoding(outputColumnName: "Prediction", "Score")

 .Append(mlContext.Transforms.Concatenate(outputColumnName: "Features", "Year", "MONTH_ID"));

        // 4. Add algorithm
        var trainer = mlContext.Regression.Trainers.Sdca(labelColumnName: "Prediction",
 featureColumnName: "Features");
        var trainingPipeline = dataProcessPipeline.Append(trainer);

        // 5. Train model
        var model = trainingPipeline.Fit(trainData);

        // 6. Evaluate model on test data
        IDataView testData = mlContext.Data.LoadFromTextFile<ModelInput>("Padavine Nis-1946-
2019 new1 test.csv", separatorChar: ',', hasHeader: true);
        IDataView predictions = model.Transform(testData);
        var metrics = mlContext.Regression.Evaluate(predictions, "Prediction");
        Console.WriteLine($"Model Quality" + $"(RSquared):{metrics.RSquared}");
        Console.WriteLine($"Model Quality", metrics);

        // 7. Predict on sample data and print results
        var input1 = new ModelInput
        {
            Year = 1946,
            MONTH_ID = 1,
            PRECIPITATION = 8,
        };

        var result = mlContext.Model.CreatePredictionEngine<ModelInput, ModelOutput>
  (model).Predict((ModelInput)input1);
        Console.WriteLine($"Predicted fare: " + $"{result.Prediction}");

        // Save trained model
        mlContext.Model.Save(model, trainData.Schema, "MLModel.zip");

        return (ModelOutput)predictions;
        //return result.Prediction;
    }

    public IActionResult DataMgmt()
    {
        object ViewBag = null;
        //ViewBag.PartialView = "_DefaultDataMgmt";
        var admindatamgmt = new ConsumeModel();
        //admindatamgmt.Category = "default value";
        //admindatamgmt.Operation = "default value";
        return IDataView(admindatamgmt);
    }

    private IActionResult IDataView(ConsumeModel admindatamgmt)
    {
        throw new NotImplementedException();
    }

Controller:
public class PrecipPredictionController : Controller
{
         public IActionResult Index()
         {
             return View();
         }

    [HttpGet]
    //[Route("PrecipitationController")]
    public IActionResult PrecipitationPrediction() //Index()
    {
        return View();
        //return this.View("PrecipitationPrediction.cshtml", "Home");
    }

    [HttpPost]
    public ActionResult PrecipitationPrediction(ModelInput input)
    {
        //int a = 0;
        //ViewBag.Result = a.ToString();

        dynamic d = input;

        //ViewBag.Result = d.PRECIPITATION;  //"";
        ViewBag.Result = "";

        //var PrecipitationPredictions = ConsumeModel.Predict(input);
        //PredictionEngine<ModelInput, ModelOutput> PrecipitationPredictions =
 ViewBag.Result.CreatePredictionEngine1(input); //Predict2 CreatePredictionEngine
        PredictionEngine<ModelInput, ModelOutput> PrecipitationPredictions =
 ConsumeModel.Predict2(input); //Predict2 CreatePredictionEngine
        ViewBag.Result = PrecipitationPredictions;

        ViewData["Year"] = input.Year;
        ViewData["MONTH_ID"] = input.MONTH_ID;

        //return View("PrecipitationPrediction", "Precipitation"); //
        return View();
    }

    public ActionResult PrecipitationPrediction2(ModelInput input)
    {
        //var PrecipitationPredictions = ViewBag.Result.Predict2(input);
        //var PrecipitationPredictions = ViewBag.Result.CreatePredictionEngine1(input);
 //Predict2 //CreatePredictionEngine
        var PrecipitationPredictions = ViewBag.Result.CreatePredictionEngine2();
        ViewBag.Result = PrecipitationPredictions;

        //ViewData["Year"] = input.Year;
        //ViewData["MONTH_ID"] = input.MONTH_ID;
        ViewData["Year"] = 1946;
        ViewData["MONTH_ID"] = 1;

        //return View("PrecipitationPrediction", "Precipitation"); //
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]

    public IActionResult DataMgmt()
    {
        ViewBag.PartialView = "PrecipitationPrediction";

        return View();
    }
}

      [1]: https://i.stack.imgur.com/yZvgS.jpg


text:
Q: Problem using Nintegrate and NDsolve I am going to use Nintegrate to integrate the result of NDsolve and also a Table. How I can do this? My code is:
Clear["Global`*"]

yy = 10^-4;
rr = 0.999;
xx = 10^-15;
zz = 10^-4;
mm = 10^-4;

ic = -17.5

s = NDSolve[{D[y[t],
     t] == (3 y[t])/5 - (12 m[t]^2 y[t])/5 + (2 r[t] y[t])/
      5 - (6 x[t]^2 y[t])/5 + (3 y[t]^2)/5 + (7 y[t] z[t])/
      5 - (y[t] z[t]^2)/10,
   D[r[t], t] == -((2 r[t])/5) - (12 m[t]^2 r[t])/5 + (2 r[t]^2)/
      5 - (6 r[t] x[t]^2)/5 + (3 r[t] y[t])/5 + (7 r[t] z[t])/
      5 - (r[t] z[t]^2)/10,
   D[x[t], t] == (9 x[t])/5 - (6 m[t]^2 x[t])/5 + (r[t] x[t])/
      5 - (3 x[t]^3)/5 + (3 x[t] y[t])/10 + (x[t] z[t])/
      5 - (x[t] z[t]^2)/20,
   D[z[t], t] ==
    12/5 + (12 m[t]^2)/5 - (12 r[t])/5 - (24 x[t]^2)/5 - (18 y[t])/
      5 - (18 z[t])/5 - (6 m[t]^2 z[t])/5 + (r[t] z[t])/
      5 - (3 x[t]^2 z[t])/5 + (3 y[t] z[t])/10 + (13 z[t]^2)/10 -
     z[t]^3/20,
   D[m[t], t] == -2 Sqrt[3] - (6 m[t])/5 -
     2 Sqrt[3] m[t]^2 - (6 m[t]^3)/5 +
     2 Sqrt[3] r[t] + (m[t] r[t])/5 +
     2 Sqrt[3] x[t]^2 - (3 m[t] x[t]^2)/5 +
     2 Sqrt[3] y[t] + (3 m[t] y[t])/10 +
     2 Sqrt[3] z[t] + (6 m[t] z[t])/5 -
     z[t]^2/(4 Sqrt[3]) - (m[t] z[t]^2)/20, x[ic] == xx, y[ic] == yy,
   m[ic] == mm, z[ic] == zz, r[ic] == rr}, {x, y, z, m, r}, {t, ic,
   10}]

I use the result to find
H = Table[
  Exp[NIntegrate[z[t]/5 +  (z[t]^2)/20 /.
     First@s, {t, 0, i}]], {i, -17.5, 10, 0.2}]

Now I am going to compute:
NIntegrate[Exp[-t] x[t]^2 (H)^-1 , {t, 0, -7}]

but this does not work. In fact I dont know how to call H and x[t] together?

A: I think this gives what you want:  We construct the integral inside the definition of H by adding another ODE to the NDSolve system, which I called logH.  This in fact calculates the integral from ic, not from 0.  So to define H we need to subtract logH[0] from logH[t] before exponentiating.  This should be a much more accurate (and faster) way of computing H than interpolating a table.
ClearAll[x, y, z, m, r, logH, t];

yy = 10^-4;
rr = 0.999;
xx = 10^-15;
zz = 10^-4;
mm = 10^-4;

ic = -17.5;

s = NDSolve[{D[y[t],
      t] == (3 y[t])/5 - (12 m[t]^2 y[t])/5 + (2 r[t] y[t])/
       5 - (6 x[t]^2 y[t])/5 + (3 y[t]^2)/5 + (7 y[t] z[t])/
       5 - (y[t] z[t]^2)/10,
    D[r[t], t] == -((2 r[t])/5) - (12 m[t]^2 r[t])/5 + (2 r[t]^2)/
       5 - (6 r[t] x[t]^2)/5 + (3 r[t] y[t])/5 + (7 r[t] z[t])/
       5 - (r[t] z[t]^2)/10,
    D[x[t], t] == (9 x[t])/5 - (6 m[t]^2 x[t])/5 + (r[t] x[t])/
       5 - (3 x[t]^3)/5 + (3 x[t] y[t])/10 + (x[t] z[t])/
       5 - (x[t] z[t]^2)/20,
    D[z[t], t] ==
     12/5 + (12 m[t]^2)/5 - (12 r[t])/5 - (24 x[t]^2)/5 - (18 y[t])/
       5 - (18 z[t])/5 - (6 m[t]^2 z[t])/5 + (r[t] z[t])/
       5 - (3 x[t]^2 z[t])/5 + (3 y[t] z[t])/10 + (13 z[t]^2)/10 -
      z[t]^3/20,
    D[m[t], t] == -2 Sqrt[3] - (6 m[t])/5 -
      2 Sqrt[3] m[t]^2 - (6 m[t]^3)/5 +
      2 Sqrt[3] r[t] + (m[t] r[t])/5 +
      2 Sqrt[3] x[t]^2 - (3 m[t] x[t]^2)/5 +
      2 Sqrt[3] y[t] + (3 m[t] y[t])/10 +
      2 Sqrt[3] z[t] + (6 m[t] z[t])/5 -
      z[t]^2/(4 Sqrt[3]) - (m[t] z[t]^2)/20, x[ic] == xx, y[ic] == yy,
     m[ic] == mm, z[ic] == zz, r[ic] == rr,
    (* add this line *)
    logH'[t] == z[t]/5 + (z[t]^2)/20, logH[ic] == 0
    },
   {x, y, z, m, r, logH}, {t, ic, 10}];

Now construct H from logH.
ClearAll[H];
With[{logH = logH /. First@s},
  H[t_] := Exp[logH[t] - logH[0]]];

H[t]

We can see an image of the plot of logH inside the InterpolatingFunction in the image above.
Finally, here is the integral:
NIntegrate[
 Evaluate[Exp[-t] x[t]^2 (H[t])^-1 /. First@s],
 {t, 0, -7}]
(*  -2.25183  *)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Static propery or static readony field I have some intialized Property/Fields that are "constant" and I want to know which one of the following line is the best to use :

*

*public static Color MyColor { get { return Color.Red; } }

*public static readonly Color MyOtherColor = Color.Red;
Is there some runtime differences after (lazy)initialization ?
Are the performance usages differents ?

A: If they are constants, then use a constant:

public const Color MyColor = Color.Red;

In answer to the question, here's a good read on the msdn forums: Memory consumption: static fields vs static properties
Edit:
As Joe pointed out in the comments, Color cannot be declared a constant because it is not a compile time constant.
A better answer to this question is answered by Joe.
In the end, there will be no noticeable difference between using a static readonly field vs property. Use whatever fits best with the situation.

A: The Field usage guidelines recommend using public static read-only fields for predefined object instances.  For example:
public struct Color
{
    // this is a predefined immutable instance of the containing Type
    public static readonly Color Red = new Color(0x0000FF);

    ...
}

In your case, I'd probably use a property:
public class MyClass
{
    // Not a predefined instance of the containing Type => property
    // It's constant today, but who knows, tomorrow its value may come from a
    // configuration file.
    public static Color MyColor { get { return Color.Red; } }
}

UPDATE

It's crystal clear when I see your answer, but using ILSpy in System.Drawing shows me the following code: public static Color Red { get { return new Color(KnownColor.Red); } }

The guidelines linked above (which use Color as an example) are for .NET 1.1 and have possibly evolved.  Personally I don't think you can go wrong by using a property.  .NET 4.0 Field Guidelines are similar, but use DateTime.MaxValue and DateTime.MinValue as examples of predefined object instances.

A: A few practical considerations:

*

*If you plan to use the value in a switch statement or expression, it
must be a const, not a read only field or property.

*You may want to use a read only field as opposed to a constant if you
plan to use the value it other assemblies.  If you have a constant in
assembly A and use that constant in assembly B, the constant value gets
compiled into assembly B.  If you then change the constant and recompile
only assembly A, then assembly B will still contain the original
value, and must be recompiled.  This is not the case with a read only
field because the value will be retrieved from assembly A at runtime.


text:
Q: Eclipse IDE for Scala : symbol is missing from classpath When I build my Scala-Spark project in Eclipse Oxygen (ubuntu 16.04), it returns me this issue in "Problems" console:
 Symbol 'term <none>.typesafe.scalalogging' is missing from the classpath. This symbol is required by 'trait org.graphframes.Logging'. Make sure that term scalalogging is in your classpath and check for conflicting dependencies with `-Ylog-classpath`. A full rebuild may help if 'Logging.class' was compiled against an incompatible version of <none>.typesafe. Example.scala   /FakeYelp/src/main/scala/bigdata/FakeYelp   line 18 Scala Problem

Symbol 'term com.typesafe' is missing from the classpath. This symbol is required by 'trait org.graphframes.Logging'. Make sure that term typesafe is in your classpath and check for conflicting dependencies with `-Ylog-classpath`. A full rebuild may help if 'Logging.class' was compiled against an incompatible version of com.  Example.scala   /FakeYelp/src/main/scala/bigdata/FakeYelp   line 18 Scala Problem

Symbol 'type <none>.slf4j.LazyLogging' is missing from the classpath. This symbol is required by 'trait org.graphframes.Logging'. Make sure that type LazyLogging is in your classpath and check for conflicting dependencies with `-Ylog-classpath`. A full rebuild may help if 'Logging.class' was compiled against an incompatible version of <none>.slf4j.  Example.scala   /FakeYelp/src/main/scala/bigdata/FakeYelp   line 18 Scala Problem

Error is on:
val gFrame = GraphFrame(vertexDF, edgeDF)

How can fix this issue?
UPDATE
This is my pom.xml maven configuration:
<dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

<!-- https://mvnrepository.com/artifact/graphframes/graphframes -->
<dependency>
    <groupId>graphframes</groupId>
    <artifactId>graphframes</artifactId>
    <version>0.5.0-spark2.1-s_2.11</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core_2.10 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.10</artifactId>
    <version>2.1.1</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-sql_2.11 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-sql_2.11</artifactId>
    <version>2.1.1</version>
    <scope>provided</scope>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.spark/spark-graphx_2.11 -->
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-graphx_2.11</artifactId>
    <version>2.1.1</version>
    <scope>provided</scope>
</dependency>
</dependencies>

A: You can't use ..._2.10 and ..._2.11 together. Maven has no idea about these suffixes being meaningful and so can't provide useful errors. Add a property and use _${scala.binary} to switch dependencies together (and make sure it corresponds to the Scala version you are using).
There may be additional problems, but this needs to be fixed first.


text:
Q: Air bubbles in Ice and cause for their shape?
I was looking at the ice formed in my refrigerator and found out there were a lot of air bubbles inside it.
The shape of the air pockets seemed strange to me.
There were many small spherical ones and the bigger ones were in the shape of vertical ellipses.
I am not able to understand what's the cause of these different shapes of bubbles.
can anyone explain?

A: If I see this correctly the vertical bubbles seem to be at the top. My guess is that the bubbles were at the top and only surface tension kept the air from being released, when the temperature cooled this surface tension could have been disturbed and the air may have started to escape; this would cause the water to close in from the sides of the bubble but this may have been slowed by the low temperature and the water may have frozen before the hole was closed.

A: As water freezes, zones of ice and zones of water form. On the scale of a bubble, the interface might well be a plane.
As the water cools, dissolved gasses form bubbles. A bubble can be engulfed as the interface advances past it.
As ice freezes more gas comes out of solution. The bubble grows. The part that has been engulfed cannot expand. So the bubble becomes elongated.
The spherical bubbles were likely engulfed late, after all the gas had moved into bubbles.


text:
Q: Prime numbers Inequality: I recently started research in number theory and prime numbers and got stuck in this problem. I coded it by Mathematica and can't find a counterexample. However, It must be true but I can't prove that:
Problem: Lets that $ \lbrace p_1,p_2,\cdots p_l\rbrace$  and $\lbrace q_1,q_2,\cdots q_t\rbrace$ be two distinct subsetof prime numbers greater such that $p_i,q_i>2$. Is this inequality true or not:
$$
\prod_{i=1}^{t}(1-\frac{1}{q_i})\prod_{i=1}^{l}(1-\frac{1}{p_i})+\sum_{j=1}^{t}\frac{1}{q_j}\prod_{i=1, i\neq j}^{t}(1-\frac{1}{q_i})+ \sum_{j=1}^{l}\frac{1}{p_j}\prod_{i=1}^{l}(1-\frac{1}{p_i})>\frac{1}{2}
$$
By simplification we can use this:
$$
 \underbrace{\prod_{i=1}^{l}(1-\frac{1}{q_i})}_{A}\underbrace{\prod_{i=1}^{t}(1-\frac{1}{p_i})}_B+ \underbrace{\prod_{i=1}^{l}(1-\frac{1}{q_i})}_A\underbrace{\sum_{j=1}^{l}\frac{1}{q_j-1}}_C+\underbrace{\prod_{i=1}^{t}(1-\frac{1}{p_i})}_B \underbrace{\sum_{j=1}^{t}\frac{1}{p_j}}_D>\frac{1}{2}\\
$$
For $p=l=1$ we have got:
$$
\dfrac{(p-1)(q-1)}{pq}+\dfrac{1}{p}+\dfrac{q-1}{q^2}>\dfrac{1}{2}
$$
and it is true.

Hint: Any information can be useful.

A: Let $p_i$ be the sequence of primes $\equiv 1\bmod 4$ and $q_j$ the sequence of primes $\equiv 3\bmod 4$.
Then $$\sum_i \frac1{p_i} = \infty,\quad\sum_j \frac1{q_j} = \infty,\quad
\prod_i (1-\frac1{p_i})=0,\quad\prod_j (1-\frac1{q_j})=0$$
$$\lim_{I\to \infty} \sum_{i=1}^I \frac1{p_i}\prod_{i'=1,i'\ne i}^I (1-\frac1{p_{i'}}) = 0,
\quad \lim_{J\to \infty} \sum_{j=1}^J \frac1{q_j}\prod_{j'=1,j'\ne j}^J (1-\frac1{q_{j'}}) = 0$$
So taking $I=J$ large enough you get a counter-example.


text:
Q: AngularJS: How to load javascript files into the partials using ng-include My main javascript files (they are in index.html) don't want to work in the partials (page1.html, etc.).For example jquery, hightlight syntax. The problem is with loading them during I click on my menu.
HTML CODE:

{{page.title}}

JS CODE
app.controller('TestCtrl', ['$scope', function($scope){
$scope.pages =
    [
        {
            title: 'Test',
            url: 'page1.html'
        },
        {
            title: 'Test2',
            url: 'page2.html'
        },
        {
            title: 'Test3',
            url: 'page3.html'
        }
    ];
$scope.view = $scope.pages[0].url;
$scope.loadPage = function($page){
    $page.url ?  $scope.view = $page.url : '';
};

The content is loaded when I click in certain link (page1.html, page2.html, page3.html). But script dont want to work. What is the problem here?

A: You mean the script in index.html not works in loaded partials?
So i think it's related to that scripts. You should initialize those scripts again after loading template file.
Most of jquery plugins have plugin initializer function, Just run it again. e.g $('.codeblock').highliter();


text:
Q: Why does this "read file" function I've created in C behave differently in Linux than it does in Windows? I am using this function to read in a text file that contains strings which are read in and inserted into an AVL tree. Everything works perfectly fine in Windows, however once I try to run it in Linux it produces entirely different results (I get a bunch of redundant nodes whose keys are simply blank spaces). Would anyone be able to explain why this might be the case?
node *read_file(char *list_name)
{
    char array[255];
    char *token = NULL;
    node *found = NULL;
    node *tree = NULL;
    FILE *file = fopen(list_name, "r");

    if (file == NULL)
    {
        printf("Could not open file\n");
        return NULL;
    }

    while (fgets(array, 255, file) != NULL)
    {
        token = strtok(array, " \n");
        while (token != NULL)
        {
            found = find_key(token, tree);

            if (found == NULL)
            {
                tree = insert(token, tree);
            }
            else
            {
                found->frequency++;
            }
            token = strtok(NULL, " \n");
        }
    }

    fclose(file);
    return tree;
}

A: If you have issues using stdio in windows respect unix (or linux) just use always b specifier to fopen(3) call.  Line terminators in unix consist on a single \n char, while in windows they are composed of a sequence of \r\n characters.  The solution adopted by the windows port consist in allowing you to specify "rt", instead of "r" to the fopen(3) call, so the \r are filtered out before passing them to the calling code.  Probably your problem will be solved by just using "rt" instead of "r" (Posix spec allows this flag to be used in unix, but ignores it, so using it always is no harmful)   There's another "b" specifier, that allows you to consider the file a binary file (so the transformation of eliminating all the \r chars isn't done.  This is mainly mean for binary files.


text:
Q: MissingSchemaError: Schema hasn't been registered for model products MissingSchemaError: Schema hasn't been registered for model products
getCartItems MissingSchemaError: Schema hasn't been registered for model "products".
Use mongoose.model(name, schema)
at NativeConnection.Connection.model (F:\ecommerceApp\ecommerce-backend\node_modules\mongoose\lib\connection.js:1242:11)
This is the controller
Cart
const mongoose = require('mongoose');
const cartSchema = new mongoose.Schema({
    user: { type: mongoose.Schema.Types.ObjectId, ref: 'user', required: true },
    cartItems: [
        {
        product : {
            type :mongoose.Schema.Types.ObjectId,
            ref : "product",
            required:true
        },
        quantity : {
            type:Number,
            default:1
        }
    }
    ]
} ,{timestamps:true});

module.exports = mongoose.model('Cart' , cartSchema , 'cart');

Products
const mongoose = require('mongoose');
const productSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        trim: true
    },
    slug: {
        type: String,
        required: true,
        unique: true
    },
    quantity: {
        type: Number,
        required: true
    },
    price: {
        type: Number,
        required: true
    },
    description: {
        type: String,
        required: true,
        trim: true
    },
    offer: { type: Number },
    productPictures: [{
        img: { type: String }
    }],
    reviews: [{
        userid: { type: mongoose.Schema.Types.ObjectId, ref: "User", review: String }
    }],
    category: { type: mongoose.Schema.Types.ObjectId, ref: "Categories" },
    createdby: {
        type: mongoose.Schema.Types.ObjectId, ref: "User", required: true
    },
    updatedAT: {
        type: Date
    }

}, { timestamps: true });

module.exports = mongoose.model('Product', productSchema);

Document
Products
{"_id":{"$oid":"6027d3a8cf712436607e6a6f"},"name":"Samsung Galaxy S21 Plus (Phantom Silver, 256 GB)  (8 GB RAM)","slug":"Samsung-Galaxy-S21-Plus-(Phantom-Silver-256-GB)-(8-GB-RAM)","price":5000,"quantity":10,"description":"With the Samsung Galaxy S21 Plus Smartphone, you can click amazing shots and record stunning videos at up to 8K resolution as it comes with a 64 MP camera setup. This smartphone is 5G-ready, enabling you to stream videos and download content from the Web with minimal lag. Moreover, its powerful processor and long-lasting battery make it a delight to use this smartphone.","productPictures":[{"_id":{"$oid":"6027d3a8cf712436607e6a70"},"img":"wGFfBkAhQ-samsung-galaxy-j6-sm-j600gzbgins-original-imaf6zpf6q8tjcva.jpeg"}],"category":{"$oid":"6020d53117616c5228246ac4"},"createdby":{"$oid":"601400873e5a422f9c81ae1c"},"reviews":[],"createdAt":{"$date":"2021-02-13T13:27:04.135Z"},"updatedAt":{"$date":"2021-02-13T13:27:04.135Z"},"__v":0}

Cart
{"_id":{"$oid":"6027d3bacf712436607e6a71"},"user":{"$oid":"60238bea8f89fb538c845f5b"},"cartItems":[{"quantity":2,"_id":{"$oid":"6027d3d4cf712436607e6a73"},"product":{"$oid":"6027d3a8cf712436607e6a6f"}}],"createdAt":{"$date":"2021-02-13T13:27:22.393Z"},"updatedAt":{"$date":"2021-02-13T13:27:48.217Z"},"__v":0}

Router export method , Here is the error which is not populating the population not happening
Throws in when called from PostMan
exports.getCartItems = (req, res) => {
  //const { user } = req.body.payload;
  //if(user){
    console.log('req.user._id' , req.user._id);
    Cart.findOne({ user: req.user._id })
    .populate("cartItems.product", "_id name price productPictures")
    .exec((error, cart) => {
    console.log('getCartItems' , error);
      if (error) return res.status(400).json({ error });
      if (cart) {
        let cartItems = {};
        cart.cartItems.forEach((item, index) => {
          cartItems[item.product._id.toString()] = {
            _id: item.product._id.toString(),
            name: item.product.name,
            img: item.product.productPictures[0].img,
            price: item.product.price,
            qty: item.quantity,
          };
        });
        res.status(200).json({ cartItems });
      }
    });
  //}
};

A: You have a typo. You mean products but typed proucts


text:
Q: Select, Copy and Paste Images What I want my app to do:
1 - Select an area of Image and get the coordinates. This code below should do this:
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import javax.swing.*;

public class ScreenCaptureRectangle {

Rectangle captureRect;

ScreenCaptureRectangle(final BufferedImage screen) {
    final BufferedImage screenCopy = new BufferedImage(
            screen.getWidth(),
            screen.getHeight(),
            screen.getType());
    final JLabel screenLabel = new JLabel(new ImageIcon(screenCopy));
    JScrollPane screenScroll = new JScrollPane(screenLabel);

    screenScroll.setPreferredSize(new Dimension(
            (int)(screen.getWidth()/3),
            (int)(screen.getHeight()/3)));

    JPanel panel = new JPanel(new BorderLayout());
    panel.add(screenScroll, BorderLayout.CENTER);

    final JLabel selectionLabel = new JLabel(
            "Drag a rectangle in the screen shot!");
    panel.add(selectionLabel, BorderLayout.SOUTH);

    repaint(screen, screenCopy);
    screenLabel.repaint();

    screenLabel.addMouseMotionListener(new MouseMotionAdapter() {

        Point start = new Point();

        @Override
        public void mouseMoved(MouseEvent me) {
            start = me.getPoint();
            repaint(screen, screenCopy);
            selectionLabel.setText("Start Point: " + start);
            screenLabel.repaint();
        }

        @Override
        public void mouseDragged(MouseEvent me) {
            Point end = me.getPoint();
            captureRect = new Rectangle(start,
                    new Dimension(end.x-start.x, end.y-start.y));
            repaint(screen, screenCopy);
            screenLabel.repaint();
            selectionLabel.setText("Rectangle: " + captureRect);
        }
    });

    JOptionPane.showMessageDialog(null, panel);

    System.out.println("Rectangle of interest: " + captureRect);
}

public void repaint(BufferedImage orig, BufferedImage copy) {
    Graphics2D g = copy.createGraphics();
    g.drawImage(orig,0,0, null);
    if (captureRect!=null) {
        g.setColor(Color.RED);
        g.draw(captureRect);
        g.setColor(new Color(255,255,255,150));
        g.fill(captureRect);
    }
    g.dispose();
}

public static void main(String[] args) throws Exception {
    Robot robot = new Robot();
    final Dimension screenSize = Toolkit.getDefaultToolkit().
            getScreenSize();
    final BufferedImage screen = robot.createScreenCapture(
            new Rectangle(screenSize));

    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            new ScreenCaptureRectangle(screen);
        }
    });
}
}

2 - get the coordinates and use it on getSubimage method.
double w  = captureRect.getWidth();
double h  = captureRect.getHeight();
double x  = captureRect.getX();
double y  = captureRect.getY();

int W = (int) w;
int H = (int) h;
int X = (int) x;
int Y = (int) y;

BufferedImage selectImg = screen.getSubimage(x, y, w, h);

3 - this code create a new image file and copy the imageselected.
BufferedImage img = new BufferedImage ( 5000, 5000, BufferedImage.TYPE_INT_RGB );
img.createGraphics().drawImage(selectImg, 0, 0, null);
File final_image = new File("C:/Final.jpg");
ImageIO.write(img, "jpeg", final_image);

The idea of app is:
- Select an area of the image.
- Copy that image and paste in other file. ( when I pressed any button )
- The program will continue run until I press another button.
- Every image that I copy the program will paste it beside the last one.
I think I am near to the solution. Can any one help me to "connect the parts" ?

A: Start by taking a look at:

*

*How to Write a Mouse Listener

*How to Use Buttons, Check Boxes, and Radio Buttons

*How to Write an Action Listeners

*Performing Custom Painting

*Writing/Saving an Image
You need to take the concepts you have and rework them into a coherent workable solution.  That is, provide functionality between the areas you need (selecting a region and saving the file) so that they work cleanly together...
The following example takes a screenshot, allows you to select an area, click save and the file will be saved.  The example checks to see how many files are already in the current directory and increments the count by 1 so you are not overwriting the existing files...

import java.awt.AWTException;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class ScreenImage {

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

    public ScreenImage() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                    ex.printStackTrace();
                }
                try {
                    Robot robot = new Robot();
                    final Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
                    final BufferedImage screen = robot.createScreenCapture(new Rectangle(screenSize));

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(new TestPane(screen));
                    frame.setSize(400, 400);
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (AWTException exp) {
                    exp.printStackTrace();
                }
            }
        });
    }

    public class TestPane extends JPanel {

        private BufferedImage master;

        public TestPane(BufferedImage image) {
            this.master = image;
            setLayout(new BorderLayout());
            final ImagePane imagePane = new ImagePane(image);
            add(new JScrollPane(imagePane));

            JButton btnSave = new JButton("Save");
            add(btnSave, BorderLayout.SOUTH);

            btnSave.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    try {
                        BufferedImage img = imagePane.getSubImage();
                        master = append(master, img);
                        File save = new File("Capture.png");
                        ImageIO.write(master, "png", save);
                        imagePane.clearSelection();
                        JOptionPane.showMessageDialog(TestPane.this, save.getName() + " was saved", "Saved", JOptionPane.INFORMATION_MESSAGE);
                    } catch (IOException ex) {
                        ex.printStackTrace();
                        JOptionPane.showMessageDialog(TestPane.this, "Failed to save capture", "Error", JOptionPane.ERROR_MESSAGE);
                    }
                }

                public BufferedImage append(BufferedImage master, BufferedImage sub) {

                    // Create a new image which can hold both background and the
                    // new image...
                    BufferedImage newImage = new BufferedImage(
                                    master.getWidth() + sub.getWidth(),
                                    Math.max(master.getHeight(), sub.getHeight()),
                                    BufferedImage.TYPE_INT_ARGB);
                    // Get new image's Graphics context
                    Graphics2D g2d = newImage.createGraphics();
                    // Draw the old background
                    g2d.drawImage(master, 0, 0, null);
                    // Position and paint the new sub image...
                    int y = (newImage.getHeight() - sub.getHeight()) / 2;
                    g2d.drawImage(sub, master.getWidth(), y, null);
                    g2d.dispose();

                    return newImage;

                }

            });

        }

    }

    public class ImagePane extends JPanel {

        private BufferedImage background;
        private Rectangle selection;

        public ImagePane(BufferedImage img) {
            background = img;
            MouseAdapter ma = new MouseAdapter() {

                private Point clickPoint;

                @Override
                public void mousePressed(MouseEvent e) {
                    clickPoint = e.getPoint();
                }

                @Override
                public void mouseDragged(MouseEvent e) {
                    Point dragPoint = e.getPoint();

                    int x = Math.min(clickPoint.x, dragPoint.x);
                    int y = Math.min(clickPoint.y, dragPoint.y);
                    int width = Math.abs(clickPoint.x - dragPoint.x);
                    int height = Math.abs(clickPoint.y - dragPoint.y);

                    selection = new Rectangle(x, y, width, height);
                    repaint();

                }

            };

            addMouseListener(ma);
            addMouseMotionListener(ma);
        }

        public void clearSelection() {
            selection = null;
            repaint();
        }

        public BufferedImage getSubImage() {

            BufferedImage img = null;
            if (selection != null) {

                img = background.getSubimage(selection.x, selection.y, selection.width, selection.height);

            }
            return img;

        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(background.getWidth(), background.getHeight());
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            int x = (getWidth() - background.getWidth()) / 2;
            int y = (getHeight() - background.getHeight()) / 2;
            g2d.drawImage(background, x, y, this);
            if (selection != null) {
                Color stroke = UIManager.getColor("List.selectionBackground");
                Color fill = new Color(stroke.getRed(), stroke.getGreen(), stroke.getBlue(), 128);
                g2d.setColor(fill);
                g2d.fill(selection);
                g2d.setColor(stroke);
                g2d.draw(selection);
            }
            g2d.dispose();
        }

    }

}

So apart from rendering the selection the hardest part would be generating the resulting image...
Basically, this done by creating a new BufferedImage and painting the old image and the new, sub, image together.
public BufferedImage append(BufferedImage master, BufferedImage sub) {

    // Create a new image which can hold both background and the
    // new image...
    BufferedImage newImage = new BufferedImage(
                    master.getWidth() + sub.getWidth(),
                    Math.max(master.getHeight(), sub.getHeight()),
                    BufferedImage.TYPE_INT_ARGB);
    // Get new image's Graphics context
    Graphics2D g2d = newImage.createGraphics();
    // Draw the old background
    g2d.drawImage(master, 0, 0, null);
    // Position and paint the new sub image...
    int y = (newImage.getHeight() - sub.getHeight()) / 2;
    g2d.drawImage(sub, master.getWidth(), y, null);
    g2d.dispose();

    return newImage;

}

The example replaces the previous (master) image with the one created here, so it will constantly be appending new images to the end of it...

A: You need more listeners for button pressed and released.. some lines in the mouseMoved also better placed in mousePressed.
You would want to update your captureRect when you release the mouse (in mouseReleased method).
Then you just write it to the file. You may adjust other things according to your needs.
And for clarity maybe it's better to add a save button into your UI.
public class ScreenCaptureRectangle {

    Rectangle captureRect;
    Point start = new Point();
    SimpleDateFormat sdf;

    ScreenCaptureRectangle(final BufferedImage screen) {
        sdf = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        final BufferedImage screenCopy = new BufferedImage(
                screen.getWidth(),
                screen.getHeight(),
                screen.getType());
        final JLabel screenLabel = new JLabel(new ImageIcon(screenCopy));
        JScrollPane screenScroll = new JScrollPane(screenLabel);

        screenScroll.setPreferredSize(new Dimension(
                (int) (screen.getWidth() / 3),
                (int) (screen.getHeight() / 3)));

        JPanel panel = new JPanel(new BorderLayout());
        panel.add(screenScroll, BorderLayout.CENTER);
        JButton btnSave = new JButton("SAVE");
        btnSave.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent ae) {
                double w = captureRect.getWidth();
                double h = captureRect.getHeight();
                double x = captureRect.getX();
                double y = captureRect.getY();

                int W = (int) w;
                int H = (int) h;
                int X = (int) x;
                int Y = (int) y;

                BufferedImage selectImg = screen.getSubimage(X, Y, W, H);
                try {
                    String fName = generateFileName();
                    if (fName != null) {
                        File f = new File(fName);
                        if (f.createNewFile()) {
                            ImageIO.write(selectImg, "jpg", f);
                        }
                    }
                } catch (IOException ex) {
                    Logger.getLogger(ScreenCaptureRectangle.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
        panel.add(btnSave, BorderLayout.AFTER_LAST_LINE);

        final JLabel selectionLabel = new JLabel(
                "Drag a rectangle in the screen shot!");
        panel.add(selectionLabel, BorderLayout.SOUTH);

        repaint(screen, screenCopy);
        screenLabel.repaint();

        screenLabel.addMouseMotionListener(new MouseMotionAdapter() {

            @Override
            public void mouseDragged(MouseEvent me) {
                Point end = me.getPoint();
                captureRect = new Rectangle(start,
                        new Dimension(end.x - start.x, end.y - start.y));
                repaint(screen, screenCopy);
                screenLabel.repaint();
                selectionLabel.setText("Rectangle: " + captureRect);
            }

        });

        screenLabel.addMouseListener(new MouseAdapter() {

            @Override
            public void mousePressed(MouseEvent me) {
                start = me.getPoint();
                repaint(screen, screenCopy);
                selectionLabel.setText("Start Point: " + start);
                screenLabel.repaint();
            }

            @Override
            public void mouseReleased(MouseEvent me) {
                int endX = me.getX();
                int endY = me.getY();
                if (endX > start.x && endY > start.y) {
                    captureRect = new Rectangle(start.x, start.y, endX-start.x, endY-start.y);
                    System.out.println("Rectangle of interest: " + captureRect);
                }
            }

        });

        JOptionPane.showMessageDialog(null, panel);
    }

    private String generateFileName() {
        return new StringBuilder("screencrop_").append(sdf.format(new Date())).append(".jpg").toString();
    }

    public void repaint(BufferedImage orig, BufferedImage copy) {
        Graphics2D g = copy.createGraphics();
        g.drawImage(orig, 0, 0, null);
        if (captureRect != null) {
            g.setColor(Color.RED);
            g.draw(captureRect);
            g.setColor(new Color(255, 255, 255, 150));
            g.fill(captureRect);
        }
        g.dispose();
    }

    public static void main(String[] args) throws Exception {
        Robot robot = new Robot();
        final Dimension screenSize = Toolkit.getDefaultToolkit().
                getScreenSize();
        final BufferedImage screen = robot.createScreenCapture(
                new Rectangle(screenSize));

        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new ScreenCaptureRectangle(screen);
            }
        });
    }
}


text:
Q: Access the child value in JSON Objects react native I have this function to fetch the user data such in the code below.
constructor(props){
    super(props);
    this.state = {
        user_id: this.props.navigation.state.params.user_id,
        user: null
    }
}

componentWillMount(){
    this.loadUserDetail()
}

loadUserDetail(){
    AccountController.loadUserDetail(this.state.user_id).then(data=>{
        if(data.status == true){
            this.setState({ user: data.user })
        }
    })
}

From the loadUserDetail() function, I set the user data in a state and the this.state.user result is as follow :
{ company_name: 'Universal Sdn Bhd', address: 'test', company_desc: 'test' }

So I'm trying to display these data in my render() by directly specifying the object like this.state.user.company_name but it doesn't work.
Here is how my rendering looked like :
render() {
    return (
        <View style={{flex: 1}}>
            <Text style={{ fontSize: 20, fontWeight: 'bold' }}>{ this.state.user.company_name }</Text>
        </View>
    )
}

By displaying the data like in the code, it throws me this error

TypeError: null is not an object (evaluating 'this.state.user.company_name')

I'm able to display the data if I store every specific value in a state after fetching the data in the loadUserDetail() function but if let say I have a lot of data in my array then I have to set every each of them in a state and I want to avoid doing so.

A: Your render needs to allow for the fact that it can be called when this.state.user is null and show an appropriate display for that case, since your component will not have the user until/unless the asynchronous operation completes. For instance:
render() {
    const { user } = this.state;
    return (
        <View style={{flex: 1}}>
            {user
            ?  <Text style={{ fontSize: 20, fontWeight: 'bold' }}>{ user.company_name }</Text>
            :  <Text style={{ fontSize: 20, fontStyle: 'italic' }}>loading</Text>
            }
        </View>
    )
}

If you don't want your component to show a pending state for when it doesn't have user, the call to load the user should be in the parent component instead, and it should only render the child when the user is known (passing it as props).

Side note: Inline style is generally a maintenance hassle. Consider using classes instead.
Side note 2: Presumably, loadUserDetail can fail. You should have a catch handler on it to deal with the failure.


text:
Q: Adaptive AngularJS directive Here is our jQuery code:
$(document).ready(function(){
    $(window).on("load resize", function(){
        if ($(window).width()<=960){
            $(".myDirective").css("flex-direction", "column")
        }
        else{
            $(".myDirective").css("flex-direction", "row")
        }
    })
});

Now I want to create an AngularJS directive with the same function. How should I do this?
I know how to create a directive with the specific style:
.directive('myDirective', function(){
    return{
        link: function(scope, element, attrs){
            element.css({
                flexDirection: 'column'
            });
        }
    }
});

But how to add conditions?

A: In your html apply this windowWidth directive to your element whose class you have set to .myDirective.
Ex.

app.directive('windowWidth', function($window) {
    return {
        restrict: 'A',
        link: function(scope, $element) {
            scope.$watch(function() {
                if($window.width < 960) {
                    $element.css("flex-direction", "column");
                } else {
                    $element.css("flex-direction", "row");
                }
            })
        },
    }
});


text:
Q: trying to repeat condition nth times after np.where condition meets I'm trying to use multiple np.where to solve my equation problem for my 2 datasets below:
import pandas as pd
df_A1 = pd.DataFrame([[46, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],[47, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], columns=['RTMB','RTMM',1,2,3,4,5,6,7,8,9,10])

Dataset 1 df_A1

RTMB
RTMM
1
2
3
4
5
6
7
8
9
10

46
4
0
0
0
0
0
0
0
0
0
0

47
2
0
0
0
0
0
0
0
0
0
0

import pandas as pd
df_Pokok = pd.DataFrame([[6852110,9228999,10497987,11941460,0,0],[34794991,18556525,21108047,24010403,0,0]], columns=[0,1,2,3,4,5])

Dataset 2 df_Pokok

0
1
2
3
4
5

6852110
9228999
10497987
11941460
0
0

34794991
18556525
21108047
24010403
0
0

I'm trying to repeat Nth times condition at the last np.where (i just put 0, 0 in code below there because I'm confused and lost in my own thought) in the dataframe based on respective month in dataset 1 (column name from 1-10th, the column name actually goes longer to Nth number)
to provide more context and explanation of the Dataset and what I'm trying to achieve:

*

*0-5 in Dataset 2 is a Year unit, so the last condition must be taken
value of each column (after failing to satisfy both np.where(col <= df_VD['RTMM']), divide by 12 and enter the respective month in Dataset 1

*Dataset 1 RTM_B & RTMM is a month unit

*Dataset  2 column 0 is only used if the column name in 1-10 below the RTMM value

*For the remaining iterations will continue to fill the month column in Dataset 1 as long as the month column is not more than RTM_B

here is what im trying to do so far:
for col in df_A1.iloc[:, 5:]:
    df_A1[col] = np.where(int(col) > df_VD['RTM_B'], 0, np.where(int(col) <= (df_VD['RTMM']), df_VD['POKVER'], np.where(((((df_VD['RTM_B']).astype(int) - (int(col)-1))%12) == 0) ,0 ,0)))

and this is the result what im desired for :

RTMB
RTMM
1
2
3
4
5
6
7
8
9
10

46
4
685,211
685,211
685,211
685,211
769083
769083
769083
769083
769083

47
2
34,794,991
34,794,991
1,546,377
1,546,377
1,546,377
1,546,377
1,546,377
1,546,377
1,546,377
1,546,377

the 769083 is value from 'df_Pokok' column 2 divided by 12 and placed to each month respectively for 12 times, and after it continue to the next column of 'df_Pokok' column 3 and repeat the process untill RTMB is finished
Please kindly let me know if im not explain the problem clear enough, thank you so much


text:
Q: Color-code a Leaflet GeoJSON polyline based on additional values I almost repeated Color-code a Leaflet polyline based on additional values, e.g. altitude, speed, because after more than eight years, I have not found a satisfactory answer.
I need a gradien color of a GeoJSON LineString object.
The style option of L.GeoJSON object allows to specify only solid color.
The available extensions allow creating only an L.Polyline object with gradient color (this and this, for example).
But I update my line dynamically in real time, so it should be an L.GeoJSON object.
Can anyone suggest an idea or solution how to make a gradient color of the line exactly in a L.GeoJSON object?

A: Both mentioned projects use an custom L.Renderer for coloring a polyline segments. You can using this renderer (if it is possible) to color the GeoJSON object via the style option as follows:
var polyline = L.geoJSON(geoJSONdata,{
    style: function(feature){
        return {
            renderer: new L.Renderer.RendererGradient(),
            colors: colorsArray, // options for renderer
            weight: 5 // options for polyline
        }
    }
}).addTo(map);

Here we use a renderer from  leaflet-polycolor that allows do it.
However, I extracted the renderer from leaflet-polycolor and put it in a separate git repo because the size of the renderer alone is almost four times smaller than the entire project.
The comments and samples included.
But it seems to me that using a renderer is an overkill for such task. But there is no other way.


text:
Q: How to make text vertical in a jQuery UI Layout toggler? I am using the jquery-ui-layout plugin in a website: jQuery UI Layout Hompage
There are options togglerContent_open and togglerContent_closed that allow you to place html inside of the toggler. I want to include text in my EAST pane, but my problem is the text displays horizontally across a vertical toggler, so only the first character can be seen.

How can I display it so that it reads vertically instead? Like either of (sry, very rough mock-up) the options below. Is it an option in jQuery UI Layout or just css?

EDIT: Does anyone know if this is possible by modifying jQuery UI Layout settings?

A:

.parentPane {
    border: 1px solid #ccc;
}

.parentPane > div {
    display:inline-block;
    height:100px;
    vertical-align:top;
    text-align:center;
}

.eastPane {
    background-color:#CA7DBD;
    width: 49.5%;
}

.westPane {
    background-color:#4679BD;
    width: 49.5%;
}

.rotator {
    background-color:#ccc;
    display:inline-block;
    margin-top: 20px;
    position:relative;
    transform: rotate(90deg);
}
.wizard1 {
    left:0;
}
.wizard2 {
    right:40px;
    ;
}
.wizard2 {
    right:40px;
    ;
}
.wizard3 {
    right:80px;
    ;
}
.wizard4 {
    right:120px;
    ;
}

East Pane

West Pane

Wizard 1

Wizard 2

Wizard 3

Wizard 4

You can make use of CSS3 transform property. This would rotate the text, however the alignment wouldn't still various such container's (div's or span's) apart. Hence, you would use relative positioning to align them next to each other. This is the general syntax you would use of rotation.
transform: rotate(90deg);

Making use of the relative positioning , you can define the distance between multiple content (where the text is vertical).
See the below snippet

.rotator {
    background-color:#ccc;
    display:inline-block;
    margin-top: 20px;
    position:relative;
    transform: rotate(90deg);
}

.wizard1 {
     left:0;
}

.wizard2 {
     right:40px;;
}

.wizard2 {
     right:40px;;
}

.wizard3 {
     right:80px;;
}

.wizard4 {
     right:120px;;
}

Wizard 1

Wizard 2

Wizard 3

Wizard 4

Hope this helps!!!


text:
Q: Calculating successive prime factorizations Everyone knows that factorization is hard. But what if I wanted to calculate the prime factorization of every number from 2 to N? If we have computed the prime factorization of every number in [2, n-1] and if a number, n, has a small prime factor, then computing the factorization of n is easy, because roughly 73% of numbers are divisible by either 2, 3 or 5. Of course, some cases, such as when n is product of two prime of a similar size, are still difficult, but on average, we might expect this problem to be reasonably easy, as we should only ever have to find one factor of a number, to reduce our problem to two problems we've solved before (i.e. factoring d and n/d).
I ask because I'm interested in finding the sum of the sum of squares r(n) (http://mathworld.wolfram.com/SumofSquaresFunction.html), as n ranges from 0 to N. This counts the number of integer points in a circle. As can be seen on the Wolfram Mathworld page, there is a formula for r(n) in terms of the prime factorization of n.
I've taken two approaches thus far:
1) Count the number of points satisfying x^2 + y^2 = n, with 0 < x < y, and then use some permutation argument to find r(n)
2) Compute the prime factorization of n (independently, each time), and compute r(n) with this information.
Experimentally, 2) seems to be faster, but it doesn't scale up well, in comparison to the first method, which is slower, but doesn't get THAT much slower. I'm interested in computing R(N) = sum from 1 to N of r(n) for 40 digit N.
Another option would be to use something like the Sieve of Eratosthenes to generate all primes up to N, then combine them in various ways, to calculate the prime factorizations of all the numbers from 2 to N, and use the same formula as before.
Does anyone have any ideas which of these options may work most effectively? 1) is the easiest to implement, starts off slow, but probably scales up quite well. 2) starts off quick, doesn't scale up well, a quick factor-finding is certainly more difficult to implement, but may do very well if modified to use memoization of previous factorizations, or using some prime generating technique as mentioned above.
Even if 1) is the quickest, I'd still be interested in learning the quickest way of generating all prime factorisations from 0 to N.

A: The Sieve of Eratosthenes can be modified to compute the factorizations of all numbers from 2 to N. Instead of just marking off multiples of primes, keep track of each multiple as it strikes a number from the list. I give a complete solution with code at my blog.


text:
Q: Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[Http]: StaticInjectorError Http Got this error
ERROR Error: Uncaught (in promise): Error: StaticInjectorError(AppModule)[Http]:
  StaticInjectorError(Platform: core)[Http]:
    NullInjectorError: No provider for Http!
Error: StaticInjectorError(AppModule)[Http]:

Here is code
Service:
import { Injectable } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';
import { HttpModule } from '@angular/http';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class MakeService {

  constructor(private http: Http) { }

  getMakes() {
    return this.http.get('api/makes')
      .pipe(map((response) => response.json()));
  }
}

App Module
import { MakeService } from './services/make.service';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpClientModule } from '@angular/common/http';
import { RouterModule } from '@angular/router';

import { AppComponent } from './app.component';
import { NavMenuComponent } from './nav-menu/nav-menu.component';
import { HomeComponent } from './home/home.component';
import { CounterComponent } from './counter/counter.component';
import { FetchDataComponent } from './fetch-data/fetch-data.component';
import { VehicleFormComponent } from './vehicle-form/vehicle-form.component';

@NgModule({
  declarations: [
    AppComponent,
    NavMenuComponent,
    HomeComponent,
    CounterComponent,
    FetchDataComponent,
    VehicleFormComponent
  ],
  imports: [
    BrowserModule.withServerTransition({ appId: 'ng-cli-universal' }),
    HttpClientModule,
    FormsModule,
    RouterModule.forRoot([
      { path: '', component: HomeComponent, pathMatch: 'full' },
      { path: 'vehicles/new', component: VehicleFormComponent },
      { path: 'counter', component: CounterComponent },
      { path: 'fetch-data', component: FetchDataComponent },
    ])
  ],
  providers: [
    MakeService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

A: You seem to have mixed the syntaxes that were used for making Http Calls before Angular 4.3 and after Angular 4.3
Angular 4.3 and prior used to use Http and for that, HttpModule was required to be added.
You're most probably using Angular with a version greater than 4.3 and RxJS version greater than 5.5
You should use HttpClient. You just need this:
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class MakeService {

  constructor(private http: HttpClient) { }

  getMakes() {
    return this.http.get('api/makes');
  }
}


text:
Q: GitHub Cloning gives "file name too long" When I clone my repository via GitHub Desktop it throws error that there is a file which name is too long ,I know that the file limit is 255 and I disabled it from regedit and from policy editor but the problem still occurs and i dont know what to do

A: Go to your GitHub Desktop Folder -> app -> resources -> app -> git -> etc -> gitconfig
And there under [core] section add this field "longpaths = true"
For My case:
Path Is:
C:\Users\username\AppData\Local\GitHubDesktop\app-3.0.7\resources\app\git\etc

And updated file (gitconfig) format:
[core]
    symlinks = false
    autocrlf = true
    fscache = true
    longpaths = true

A: For anyone who is wondering how to fix this I found a way!
Go to your GitHub Desktop Folder -> app -> resources -> app -> git -> mingw64 -> etc -> gitconfig , and there under [core] section add this field "longpaths = true" :)

A: Go to GitHubDesktop Folder (located in AppData\Local\GitHubDesktop) > app > resources > app > git > etc > gitconfig
C:\Users\YourUser\AppData\Local\GitHubDesktop\app-3.1.6\resources\app\git\etc

Open 'gitconfig' with any program that works (I opened it with Windows NotePad) and add "longpaths = true" in the [core] section

Then save the file. Open GitHub Desktop again and it will work:)


text:
Q: Online Source for Rackmount Server Shipping Box I have three Dell rackmount servers (2 2U, 1 4U) that I need to ship from Las Vegas to New York. Old shipping boxes that came with the servers were discarded sometime ago. Where can I buy some that fit nicely and can be shipped by UPS or Fedex? I've tried UPS, Fedex, and Uhaul already.
Thanks in advance.

A: Try Uline.  They have a full range of shipping supplies including many specialty items for keyboards, laptops, etc.  Their target audience is companies who ship things on a regular basis. So, you may get stuck with a minimum quantity and have to buy more than you need.

*

*Styrofoam sheets
http://www.uline.com/BL_874/Polystyrene-Sheets

*Foam Planks
www.uline.com/BL_868/Plank-Foam

*Edge Protectors
www.uline.com/Product/Detail/S-6065/Protectors/4-x-4-x-48-Foam-Edge-Protectors

*Corner Protectors
www.uline.com/Product/Detail/S-6064/Protectors/3-5-8-x-3-x-2-Foam-Corner-Protectors

*Expanding Foam In Bags
www.uline.com/BL_7708/Instapak-Quickreg-Room-Temperature
And they have more boxes than you can imagine.  This URL should get you started:

*

*Heavy Duty Double-Wall Boxes
PS: Sorry that many of the above URL's aren't hyperlinks.  New users can only have one link per post.

A: I don't have a direct answer but when faced with a similar situation I simply used a whole lot of bubble-wrap and shoved it into a large very sturdy box that I obtained from a local moving company.

A: As @John Gardiniers says, lots of wrap and  a sturdy box is great.  Several shipping agencies in our area use a foam in place system and it works well and fully protects the hardware.  Not available everywhere but link might help find a local location FoamInPlace

A: Call Dell Business or your Dell rep, I'm sure they can throw a few empty boxes your way.

A: Reach out to Austin Foam Plastics, Inc. they provide the shipping boxes to dell and will sell direct.


text:
Q: Resize UIImageView after Scale Aspect Fit I have a UITableViewCell containing only a UIImageView that is constrained to the superview on all four sides so that the cell scales to fit the full image.
The UIImageView is set to Scale Aspect Fit so that the large images resize to fit within the width of the cell. However, after the aspect fit takes place, the UIImageView remains the same size as before the scaling, and the cell in turn retains the size of the larger, unscaled image.
Is there any way in Interface Builder to force the height of the UIImageView to scale down when the image is scaled down by the Fit property? Or, equally, is there any way to programmatically tell the UIImageView to resize its height to match the newly scaled UIImage height?

A: I encountered similar problem while embedding UIImageView into UIStackView. I consider this a bug because when image view has Mode:AspectFit then unbound dimension expected to resize to the scaled image instead of original.
My workaround was:

*

*created height constraint with identifier for the image view, e.g. "constraintImageHeight"

*in the code after putting a new image into the view, the constraint is reset to calculated height, e.g.:
imgView.image = picture;
 for c in imgView.constraints {
     if c.identifier == "constraintImageHeight" {
         c.constant = picture.size.height
             * imgView.bounds.width / picture.size.width;
         break;
     }
 }


text:
Q: What is the difference between overriding ToString and using implicit/explicit conversion operators in C#? In C#, what is the difference between this:
public override string ToString()
{
    return "Person: " + Name;
}

And this:
public static implicit/explicit operator string(Person person)
{
    return "Person: " + Name;
}

A: Semantics is somewhat different.
Conversion operators say "convert to string (or another) type":

C# enables programmers to declare conversions on classes or structs so that classes or structs can be converted to and/or from other classes or structs, or basic types.

Object.ToString supposed to return

A string that represents the current object.

meaning "give me (usually human) readable text representation of the object".
(I'm not saying though that such semantics is always respected. E.g. sometimes you may see ToString and FromString are used as conversion functions.)


text:
Q: How to make some columns initially inactive in table? How to make so that in the Column Toggle component some columns were initially checked = false for a table?
Demo of Column Toggle component on Stackblitz.

A: you have to set the activeCols to some default values on init like this -
import { Component, OnInit } from '@angular/core';
import {MatTableDataSource} from '@angular/material';

const COLS = ['position', 'name', 'weight', 'symbol'];

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements OnInit {
  activeCols = COLS;
  allCols = COLS;
  dataSource = new MatTableDataSource<Element>(ELEMENT_DATA);

  ngOnInit(){
    this.activeCols = ['position', 'name'];
  }
}

export interface Element {
  name: string;
  position: number;
  weight: number;
  symbol: string;
}

const ELEMENT_DATA: Element[] = [
  {position: 1, name: 'Hydrogen', weight: 1.0079, symbol: 'H'},
  {position: 2, name: 'Helium', weight: 4.0026, symbol: 'He'},
  {position: 3, name: 'Lithium', weight: 6.941, symbol: 'Li'},
  {position: 4, name: 'Beryllium', weight: 9.0122, symbol: 'Be'},
  {position: 5, name: 'Boron', weight: 10.811, symbol: 'B'},
  {position: 6, name: 'Carbon', weight: 12.0107, symbol: 'C'},
  {position: 7, name: 'Nitrogen', weight: 14.0067, symbol: 'N'},
  {position: 8, name: 'Oxygen', weight: 15.9994, symbol: 'O'},
  {position: 9, name: 'Fluorine', weight: 18.9984, symbol: 'F'},
  {position: 10, name: 'Neon', weight: 20.1797, symbol: 'Ne'},
  {position: 11, name: 'Sodium', weight: 22.9897, symbol: 'Na'},
  {position: 12, name: 'Magnesium', weight: 24.305, symbol: 'Mg'},
  {position: 13, name: 'Aluminum', weight: 26.9815, symbol: 'Al'},
  {position: 14, name: 'Silicon', weight: 28.0855, symbol: 'Si'},
  {position: 15, name: 'Phosphorus', weight: 30.9738, symbol: 'P'},
  {position: 16, name: 'Sulfur', weight: 32.065, symbol: 'S'},
  {position: 17, name: 'Chlorine', weight: 35.453, symbol: 'Cl'},
  {position: 18, name: 'Argon', weight: 39.948, symbol: 'Ar'},
  {position: 19, name: 'Potassium', weight: 39.0983, symbol: 'K'},
  {position: 20, name: 'Calcium', weight: 40.078, symbol: 'Ca'},
];


text:
Q: Feature Names Mismatch when Passing X_test to .predict() Function (Again, Still) Ok I'm still having this issue and I'm at a loss as to where I'm going wrong. I thought I had a working solution, but I was wrong.
After finding a regression pipeline through TPOT, I go to use the .predict(X_test) function and I get the following error message:
ValueError: Number of features of the model must match the input. Model n_features is 117 and input n_features is 118

I read somewhere on Github that XGBoost likes to have the X features passed to it in the form of a Numpy Array, and not a Pandas Dataframe. So I did that and now I receive this error message whenever a RandomForestRegressor ends up in my pipeline.
So I investigate:
X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=test_size, random_state=seed, shuffle=False)

# Here is where I convert the features to numpy arrays
X_train=X_train.values
X_test=X_test.values

print('[INFO] Printing the shapes of the training/testing feature/label sets...')
print(X_train.shape)
print(X_test.shape)
print(Y_train.shape)
print(Y_test.shape)

    [INFO] Printing the shapes of the training/testing feature/label sets...
    (1366, 117)
    (456, 117)
    (1366,)
    (456,)
# Notice 117 rows for X columns...

# Now print the X_test shape just before the predict function...
print(X_test.shape)

    (456, 117)
# Still 117 columns, so call predict:

predictions = best_model.predict(X_test)

    ValueError: Number of features of the model must match the input. Model n_features is 117 and input n_features is 118

WHY!!!!!!?????
Now the tricky thing is, I'm using a custom tpot_config to only use the regressors XGBRegressor, ExtraTreesRegressor, GradientBoostingRegressor, AdaBoostRegressor, DecisionTreeRegressor, and RandomForestRegressor, so I need to come up with a way to train and predict the features whereby all of them will work with the data in the same way, so that no matter what pipeline it comes up with, I won't have this issue each time I go to run my code!
There have been similar questions asked at these links on SO:
Here
Here
Here
Here
... but I don't understand why my model is not predicting, when I AM passing it the same number of (X) features as was used in training the model!? Where am I going wrong here???
EDIT
I should also mention, that leaving the features as dataframes and not converting them to numpy arrays sometimes gives me a "feature names mismatch" error when XGBRegressor is in the pipeline as well. So I'm at a loss as to how to handle both the list of tree regressors (which like Dataframes) and XGBoost (which likes Numpy arrays). I have also tried "re-arranging" the columns(?) to make sure that the X_train and X_test Dataframes are in the same order like some have suggested but that didn't do anything.
I have posted my full code in a Google Colab notebook here where you can make comments on it. How can I pass the testing data to the .predict() function no matter what pipeline TPOT comes up with??????

A: Thanks to weixuanfu at GitHub, I may have found a solution by moving the feature_importance code section down to the bottom of the my code, and yes using numpy arrays for the features. If I run into this issue again, I will be posting it below:
https://github.com/EpistasisLab/tpot/issues/738


text:
Q: Rover uncontrollable in low gravity I've built a rover with the new rover wheels. It works great on Kerbin, but when I bring it to a low-gravity world like Minmus it is uncontrollable. When I accelerate, the back goes up. When I try to decelerate, the front goes up. Driving properly is practically impossible. How can I prevent this?

A: The reason for this is that the default rover control keys (AWSD) are also mapped to vehicle rotation. You don't notice on Kerbin because the rotation power of command pods is too weak to overcome the gravity, but on low-gravity moons the effect becomes much more notable.
There are, however, two ways, to solve this problem.
Method A:
Go to the Settings menu and map the rover controls to other keys (many players use IJKL, because that's the keys used by most of the 3rd party Rover mods which existed before 0.19)
Method B:
Switch into docking mode, where the AWSD keys control lateral movement, which is only available when you have RCS thrusters on.


text:
Q: How do I get rid of Windows File Explorer left-pane entries On my left pane on Windows File Explorer, I have a bunch of entries that I don't care for:

How do I get rid of them? Some where added by Adobe (red), other's came with Windows itself but I don't use them.

A: To hide the folders under This PC, you can copy & paste the following into an Admin PowerShell window:
$FD = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\FolderDescriptions'
gci $FD |
 ?{(gp $_.PSPath).Name -match 'Local (Music|Pictures|Video)|3D'} | %{
    $PropBag = Join-Path $_.PSPath 'PropertyBag'
    If ( !( Test-Path $PropBag )) {
        New-Item $PropBag | Out-Null
    }
    $Splat = @{
        Path  = $PropBag
        Name  = 'ThisPCPolicy'
        Value = 'Hide'
    }
    Set-ItemProperty  @Splat
}

I'm not familiar with Creative Cloud Files, but you should be able to locate it in the registry under either:
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace
or
HKLM\Software\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace
as a GUID-named subkey similar to these. Delete the one you determine to be Creative Cloud.


text:
Q: Reading web.config settings file system performance Does reading web.config settings via
WebConfigurationManager.AppSettings("Setting1") or WebConfigurationManager.ConnectionStrings("Conn1").ConnectionString cause physical access to underlying web.config file each time it happens?
If yes, will wrapping those setting in shared (static) methods
Public Class MyAppSettings
    Public Shared Function Conn1() As String
        Return WebConfigurationManager.ConnectionStrings("Conn1").ConnectionString
    End Function
    Public Shared Function Setting1() As String
        Return WebConfigurationManager.AppSettings("Setting1")
    End Function
End Class

change the way how web.config is accessed? Will settings be cached until web.config file is modified?

A: Every call to those methods will cause physical access to web.config.  Wrapping them in static methods changes nothing, physical access occurs on every call.


text:
Q: How to display the data using flutter? I can display while mapping the data (using flutter)
main.dart
//Im looping on it using map
List<Quote> quotes = [
Quote(
    author: 'Oscar Wilde',
    text: 'Be yourself, everyone else is already taken'),
Quote(
    author: 'Oscar Wilde',
    text: 'I have nothing to declare except my genius'),
Quote(
    author: 'Oscar Wilde',
    text: 'The truth is rarely pure and never simple'),
];

// Im using map then not display on the screen
body: Column(
      children: quotes.map((quote) => Text(quote)).toList(),
),

Thank you very much

A: You can try with a list generator instead of the map. Or you use Listview builder as @Jahn mentioned
import 'package:flutter/material.dart';

const Color darkBlue = Color.fromARGB(255, 18, 32, 47);

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData.dark().copyWith(
        scaffoldBackgroundColor: darkBlue,
      ),
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Center(
          child: MyWidget(),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  List<Quote> quotes = [
    Quote(
        author: 'Oscar Wilde',
        text: 'Be yourself, everyone else is already taken'),
    Quote(
        author: 'Oscar Wilde',
        text: 'I have nothing to declare except my genius'),
    Quote(
        author: 'Oscar Wilde',
        text: 'The truth is rarely pure and never simple'),
  ];

  @override
  Widget build(BuildContext context) {
    return Column(
      children: List<Widget>.generate(
        quotes.length,
        (index) {
          return Text('${quotes[index].author}');
        },
      ),
    );
  }
}

class Quote {
  String? author;
  String? text;

  Quote({this.author, this.text});
}

A: To add card, add do this:
@override
  Widget build(BuildContext context) {
    return Column(
      children: List<Widget>.generate(
        quotes.length,
        (index) {
          return Card(
                   shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(40), // if you need this
                      side: BorderSide(
                         color: Colors.grey.withOpacity(0.2),
                         width: 1,
                      ),
                   ),
                child: Container(
                   color: Colors.white,
                   width: 200,
                   height: 200,
                   child: Text('${quotes[index].author}'),
                ),
            );
        },
      ),
    );
  }


text:
Q: Get value from jstl text field through jQuery I am working on a project in spring with jstl and jQuery. I have a text field in jsp page as -
<form:input path="suv.userName" cssClass="textField" placeholder="Username (Email-Id)"/>

Problem is - when i am trying to get the field value through jQuery as - alert($("#suv.userName").val());

I am getting the undefined message. But when i am trying with javascript as -
alert(document.getElementById("suv.userName").value);

I am getting the proper value.
I think there is something problem in suv.userName haveing a '.' between. Please help how to get the value in jQuery.

A: Since . is a meta-character you have to escape it with \\ in order to make that selector valid.
Try,
alert($("#suv\\.userName").val());

DEMO


text:
Q: Slave to Slave Comminication with HC-06 devices? Is this possible, communication between HC-06 devices. A mean is this possible while i use 2 hc-06 devices send and receive data ?

A: in a bluetooth connection at least one of the two devices must have the ability to start communication and to do so must be able to exercise the role of master. The HC-06 can only be a slave. Needs that at least one of the two was the HC -05, which can be configured as master and slave.


text:
Q: Apparently inconsistent reference behavior in NumPy When referencing a given row from another one in a 2D numpy array, I noticed what to me looks like unexpected behavior
a = np.array([[1,2], [3, 4]])
a[1] = a[0]
a[1] += 100

After this operation, a will be equal to:
array([[  1,   2], [101, 102]])

I do not understand why the reference to a[0] is not considered and only a[1] is modified. Especially because with Python lists this is not the case:
a = [[1,2], [3,4]]
a[1] = a[0]
a[1][1] = 999

This will give a:
[[1, 999], [1, 999]]

A: A NumPy array of any not-object dtype does not contain references. So when you set a[1] = a[0] it just copies the content of a[0] into a[1]. That means that any subsequent assignments to a[1] or a[0] won't change the other one.
A list on the other hand doesn't copy when you have a[1] = a[0] it just inserts a reference to a[0] in a[1]. That means an assignment to either a[1] or a[0] will also change the other one.
The take-away is probably: Don't think of a NumPy array as containing references. It's actually not a nested "array" even if multidimensional. It's always a one-dimensional array that uses "strides" to "appear multidimensional".

It may help to compare "identities" here. That's a bit more complicated because NumPy doesn't work with references but works with a memory buffer. However NumPy provides a function to check for shared memory:
>>> import numpy as np
>>> a = np.array([[1,2], [3, 4]])
>>> a[1] = a[0]
>>> np.shares_memory(a[1], a[0])  # the arrays don't share memory
False

>>> a = [[1,2], [3,4]]
>>> a[1] = a[0]
>>> a[1] is a[0]                  # they are the same object
True

Note that this is different if you just take a "view" of a NumPy array without assigning it to an array. The assignment to the NumPy array is what does the copy. That's because, like I said, NumPy arrays don't store references, it only stores elements. So you can have a view into an array but you can't insert a view as view into a NumPy array.
For example:
>>> a = np.array([[1,2], [3, 4]])
>>> b = a[0]                      # b is now a view into "a"
>>> np.shares_memory(b, a[0])
True

>>> a[1] = b
>>> np.shares_memory(b, a[1])     # a[1] is not a view into "a[0]".
False


text:
Q: Firebase taking too long to fetch data ( javascript ) /*** Define all functions here (Query)! ***/
function get_all_loc(){ //get all locs in array
ref = database.ref('locs/');  //get from -- > locs in db
ref.on('value', gotData, errData);  // getData or error !
all_locs_arr = [] ; //empty array everytime button is clicked -> to show new query :P if db updated meanwhile ! silly :P
all_locs_str = ""; //empty str everytime button is clicked -> to show new query :P if db updated meanwhile ! silly :P
function gotData(data){
    all_locs_arr = data.val(); console.log(all_locs_arr); //firebase func to get data from db , storing it in all_loc_arr
    for(var loc_index=0; loc_index<all_locs_arr.length ; loc_index++){
        all_locs_str += "
"+all_locs_arr[loc_index]+"
";
        //console.log(all_locs_str);// add all locs in string
    }
get_raw_matrix();
}function errData(data){
    console.log("db_error! locs !");
}
}
get_all_loc(); // call get_all_loc function to get all locations into array & str , early fetch

This is my function for querying data from firebase.
after , all_locs_arr = data.val(); , i am doing console.log(all_locs_arr) ,
and for array (of length 10,000) , its taking more than 5 minutes to print on console.
Its an array of strings. the size of each string in the array is less than 10.
Why is fetching data so slow? Am I doing something wrong? Am I fetching too much of data?
I am not performing any search/sort, just fetching the entire data, still, it is slow .

A: Got it, I was simply fetching a lot of data.
ref = database.ref('locs/')

The above line meant , i was fetching everthying in locs , that was 10k entries .
I changed it to ref = database.ref('locs/' + some_variable)
It means i am fetching only required entry from locs .


text:
Q: Fancybox iframe title link I have a problem. I have a page http://www.hmaloha.com/bionutrient.php where when clicked over the play button, a video plays on fancybox iframe and a logo is at the top when the video loads. Now I need to add a link to that logo. I have been trying to alter the fancybox code but no luck. Any help?
$(document).ready(function(){
            $('#malohaStory').click(function(){
                $.fancybox({
                    overlayOpacity: 1,
                    overlayColor: '#bbb',
                    padding : 0,
                    autoScale : false,
                    transitionIn : 'none',
                    transitionOut : 'none',
                    titleShow : true,
                    titlePosition : 'float', // 'float', 'outside', 'inside' or 'over'
                    titleFormat : function(){
                        return ' ';
                    },
                    type: 'iframe',
                    href: 'http://hmaloha.com/js/flowplayer/video/index.html',
                    height: 545,
                    width: 920,
                    swf : {
                        wmode : 'transparent',
                        allowfullscreen : 'true'
                    }
                });
                return false;
            });

        });

A: Within your $.fancybox() call, include the beforeLoad method as shown below, changing my example link with your url:
beforeLoad: function() {
  this.title = '' + this.title + '';
}

So your final code (if you keep everything you have above, although I don't know what your titleFormat function is doing) would look like this:
$(document).ready(function(){
        $('#malohaStory').click(function(){
            $.fancybox({
                overlayOpacity: 1,
                overlayColor: '#bbb',
                padding : 0,
                autoScale : false,
                transitionIn : 'none',
                transitionOut : 'none',
                titleShow : true,
                titlePosition : 'float', // 'float', 'outside', 'inside' or 'over'
                titleFormat : function(){
                    return ' ';
                },
                type: 'iframe',
                href: 'http://hmaloha.com/js/flowplayer/video/index.html',
                height: 545,
                width: 920,
                swf : {
                    wmode : 'transparent',
                    allowfullscreen : 'true'
                }
                beforeLoad: function() {
                  this.title = '' + this.title + '';
                }
            });
            return false;
        });

    });


text:
Q: Openpyxl compare cells I have 2 sheets with some data (18k rows each) and need to check if value from source.xlsx exists in a target.xlsx file. The rows in the source file should be unique. If the cell from source file exists in the target file (in specific column) then in next column in target file need to fill value from some column which is in the source file. It is quite tricky so example would look like:
target.xlsx

Data	price

1234grt

7686tyug

9797tyu

9866yyy

98845r

4567yut

1234grt

98845r

source.xls

Data	price

98845r    	$50

7686tyug  	$67

9797tyu   	$56

4567yut   	$67

9866yyy   	$76

98845r    	$56

1234grt	$34

for i in range(1, source_sheet_max_rows, 1):
print(i)
if source_wb[temp_sheet_name].cell(row=i, column=1).value in target_values:
    for j in range(1, target_sheet_max_rows, 1):
        if target_wb[temp_sheet_name].cell(row=j, column=1).value == source_wb[temp_sheet_name].cell(row=i,
                                                                                column=1).value:
            target_wb[temp_sheet_name].cell(row=j, column=2).value = source_wb[temp_sheet_name].cell(row=i,
                                                                                column=2).value
            target_wb.save(str(temp_sheet_name))

target_values - contains the values from col 1 in target sheet
The above code works, but is very heavy and I think there is some better way do it. The files contain more than 18k rows so it would take ages to compare data. The tricky part is that I need to know in which row in the target file my cell from source file is to fill column with corresponding value. I am using openpyxl but if it is easier I could use pandas.
Thx

A: From my understanding of your question it seems like the rows in target file are not arranged in the same specific order as the source file.
for i in range(1, souce_sheet_max_rows):
    for j in range(1, target_sheet_max_rows):
        if target_wb[temp_sheet_name].cell(row=j, column=1).value == source_wb[temp_sheet_name].cell(row=i, column=1).value:
            target_wb[temp_sheet_name].cell(row=j, column=2).value == source_wb[temp_sheet_name].cell(row=i, column=2).value
            break
target_wb.save(temp_sheet_name)

A:
Question: check if value from source.xlsx exists in a target.xlsx file.

Implement it like the following example:
Documentation: OpenPyXl - accessing-many-cells
Python - Mapping Types — dict, Python - object.__init__
class SourceSheet:
    def __init__(self, ws):
        self.ws = ws

    def __iter__(self):
        """
        Implement iterRows or iterRange
        :return: yield a tuple (value_to_search, value_to_fill)
        """
        # Example iterRange
        for row in range(1, self.ws.max_rows + 1):
            yield (self.ws.cell(row=row, column=1).value, self.ws.cell(row=row, column=2).value)

class TargetSheet:
    def __init__(self, ws):
        self.ws = ws

        """
        Create a 'dict' from all Values in Column A
        This allows Random Access the Cell Value to get the Cell Row Index
        Dict.key == Cell Value
        Dict.value = Cell Row Index
        _columnA = {} # {cell.value:cell.row}
        """
        self._columnA = dict(((c.value, c.row) for c in ws['A']))

    def find(self, value):
        """
        Implement either linear Search using iterRows over one Column or
                         search in dict to find 'value'
        :param value: The value to find
        :return: The Cell, to write the 'value_to_fill'
        """
        # Example using dict
        if value in self._columnA:
            return self.ws.cell(row=self._columnA[value], column=2)

sourceSheet = SourceSheet(ws1)
targetSheet = TargetSheet(ws2)

for value_to_search, value_to_fill in sourceSheet:
    print("SourceSheet:{}".format((value_to_search, value_to_fill)))
    targetCell = targetSheet.find(value_to_search)

    if targetCell:
        print("Match: Write value '{}' to TargetSheet:'{}'".format(value_to_fill, targetCell))
        targetCell.value = value_to_fill
    else:
        print("Value '{}' not fount in TargetSheet!".format(value_to_search))

Output:
SourceSheet:('cell.A1.value', 'cell.B1.value')
Match: Write value 'cell.B1.value' to TargetSheet:'Cell.B1:'
SourceSheet:('cell.A2.value', 'cell.B2.value')
Match: Write value 'cell.B2.value' to TargetSheet:'Cell.B2:'
SourceSheet:('cell.A3.value', 'cell.B3.value')
Match: Write value 'cell.B3.value' to TargetSheet:'Cell.B3:'

Tested with Python: 3.5


text:
Q: Directory.GetFiles(...) with pattern *.??? returns funny results I am using following Code:
var di = new DirectoryInfo("path/to/dir");
var matchingFiles = di.GetFiles("*.???);

As expected, files like

*

*file.bat

*test.1.xml

*a.txt.txt

are returned. However, there are some funny results. As the MS-documentation mentions, the shortname is searched too. I also found the information about the dot-selector working in .NET 4+. Still I cannot see this explains following results:

*

*file1.xml.2

*afilewithoutextension

Q1: How can this results be explained.
Q2: How can a match for pattern *.[3 arbitrary chars] be achieved.

A: Q2) You could use LINQ and the Path class instead:
var files = Directory.EnumerateFiles("path/to/dir", "*.*")
    .Where(file => Path.GetExtension(file).TrimStart('.').Length == 3);

A:
How can this results be explained.

Short names, as you note, are always searched; and they always have a three character extension (even if those characters are spaces).

How can a match for pattern *.[3 arbitrary chars] be achieved.

Do the check in your code (eg. use a regex). MS-DOS wildcards are very limited, and backwards compatibility requirements makes them yet weaker; they are really only useful for specific matches and not general filtering.


text:
Q: CloudFormation fails with ec2:RequestSpotFleet IAM error I'm trying to create an AWS spot fleet through CloudFormation, but I'm getting this permission error. I'm creating this stack through a root account, so I don't see a possible reason for an IAM error via CloudFormation.
I'm creating this stack from the CLI with root account credentials.
Has anybody encountered this before?

A: I would check the instructions for the Amazon EC2 Spot Fleet Role:

If you create a managed compute environment that uses Amazon EC2 Spot
  Fleet Instances, you must create a role that grants the Spot Fleet
  permission to bid on, launch, tag, and terminate instances on your
  behalf. Specify the role in your Spot Fleet request. You must also
  have the AWSServiceRoleForEC2Spot and AWSServiceRoleForEC2SpotFleet
  service-linked roles for Amazon EC2 Spot and Spot Fleet.

Also, to quote the documentation on Spot Fleet Pre-requisites:

If you use the Amazon EC2 console to create a Spot Fleet, it creates a
  role named aws-ec2-spot-fleet-tagging-role that grants the Spot Fleet
  permission to request, launch, terminate, and tag instances on your
  behalf. This role is selected when you create your Spot Fleet request.
If you use the AWS CLI or an API instead, you must ensure that this
  role exists.


text:
Q: kCFURLErrorBadURL : How to solve? I am building a web service based on PHP language. Browser shows the exact data. But while i am trying get data from my iPhone app then shows the following error

*

*kCFURLErrorBadURL    = -1000

How to solve the problem from Server End (PHP) ?

A: The browser might bring correction for the URL while the connectivity classes either don't do them or do not the same corrections.
The URL must conform RFC 1738, check the URL you are using and make required corrections (preferably on the server side).