Subsequent calls to WMIC return a localdatetime with a deviating timezone

Question: The problem
In our company environment we use several batch files which use WMIC to retrieve the current time. Usually to print it to log files, but also to include the timestamp in a file name.
Starting with Windows 10 - we do not remember seeing this behavior on Windows 7 - we experienced that some of our log file parsers (they create some nice graphs for evaluation) seemed to draw weird stuff. After some research we found out, that for short time periods, the call to WMIC returns a different timestamp.
This is how we call WMIC, and what it returns.
C:\> WMIC.exe OS Get localdatetime /value
LocalDateTime=20191114112607.134000+060

Now we made an experiment and called WMIC every second for a larger period of time. Here is an excerpt of the resulting timestamps:
20191114112607.134000+060
20191114122608.394000+120
20191114122609.687000+120
[...]
20191114123105.161000+120
20191114123106.431000+120
20191114113107.672000+060

We live in a region in MEZ timezone, that is UTC+1. This is why we expect the timestamps with the +060 minute indication. We also do not expect it to change, unless twice a year, that is when day light savings time switches to MESZ (UTC+2) and vice versa.
As you can see in the timestamps above: For almost exactly 5 minutes, WMIC returns the +120 timestamp.
The analysis
I also logged the output of some other calls, to check whether this is a global Windows problem or rather a wmic behavior. All seems to be a sort of (buggy?) behavior of WMIC.
All functions/programs and even another WMIC call returned the expected time. This is my script
while ($true) {
    Get-Date -Format G
    Get-TimeZone

    $timeservers | ForEach-Object {
        $server = $_
        w32tm.exe /stripchart /computer:$server /dataonly /samples:1 | Out-Default
    }

    cmd.exe /c date /T | Out-Default
    cmd.exe /c time /T | Out-Default

    WMIC.exe Path Win32_LocalTime Get /Format:value | Out-Default

    # All 'correct' except:
    WMIC.exe OS Get localdatetime /value | Out-Default

    Start-Sleep -Seconds 1
}

The output of the above script shows that only the OS Get localdatetime call is returning the 'wrong' timestamp. We have searched the System and Application event log for entries that could tell us why this happens, but there were no entries logged. I also checked the Task Scheduler if some action was scheduled to run when this happens, but nothing.
Registry time zone information
C:\>reg query HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation
    Bias    REG_DWORD    0xffffffc4
    DaylightBias    REG_DWORD    0xffffffc4
    DaylightName    REG_SZ    @tzres.dll,-321
    DaylightStart    REG_BINARY    00000300050002000000000000000000
    DynamicDaylightTimeDisabled    REG_DWORD    0x0
    StandardBias    REG_DWORD    0x0
    StandardName    REG_SZ    @tzres.dll,-322
    StandardStart    REG_BINARY    00000A00050003000000000000000000
    TimeZoneKeyName    REG_SZ    W. Europe Standard Time
    ActiveTimeBias    REG_DWORD    0xffffffc4

The questions

Can someone explain the behavior?
What could influence the outcome of WMIC?
Would you think this is a sort of bug?
What other analysis could be done to narrow this down?
Comment: I added the registry settings to my question. Still need to try out with disable time service because I was ooo.
Comment: Two things come to mind: 1. Have you tried disabling Windows Time Service and reproducing the issue? 2. Please run `reg query HKLM\SYSTEM\CurrentControlSet\Control\TimeZoneInformation` to dump timezone setting stored in registry and share them
Answer: That is now a known Windows Bug.
Internally there is a global variable which caches the DST offset which keeps its value for 5 minutes. After 5 minutes the value goes away which leaves you with a jumping local time.
This logic was being used in RS5/1809 but not in 19H1 or in Windows Server 2012 R2.
Workarounds:

Boot the machines often enough so that LocalDateTime and LastBootUpTime cannot end up with different timezones when the machine is running for a longer time
Setting the InstallDate to the time of the last reboot using a script that runs at startup should also avoid the issue


Combining uninstall, stop, install, start script via monit

Question: We have socket listener which listens on port 9000 so below is how we wrote the alert for monit. The listener runs via yajsw daemon tool. So currently when it fails on port 9000 we get an email. What we want to extend is that if it is not running to stop,uninstall, install and finally start programe. We have all the script to the processes stated but how to put in monit? All of it are in shell script files.
check process cs9000 with pidfile /var/run/wrappercs9000.pid # check your app pid

  start program  =
  stop program  =
 if failed port 9000    # if you want to check your app that listen on port 9000
    then
    restart

Answer: With Monit, you won't get the ability to restart the program until you provide the start program and stop program directives. When you populate those options and restart Monit, you'll gain the ability to take actions based on process conditions.
An example:
check process nslcd
        with pidfile "/var/run/nslcd/nslcd.pid"
        start program = "/sbin/service nslcd start"
        stop program = "/sbin/service nslcd stop"
        if 10 restarts within 11 cycles then timeout
        if cpu usage > 95% for 11 cycles then restart
        if totalmemory > 472 MB then restart

If you want the "stop program" to run a script, give the full path to the script.
Comment: what I want to do is that to detect if my app is not running then I want to run the stop script followed by uninstall script. Then I want to run install and finally start script. How will the stop program take two script is that possible?
Comment: Yes... or you can wrap the stop and uninstall script into one script.
Comment: ok let me understand it first the cs9000 with pidfile /var/run/wrappercs9000.pid will check the process with process id exist or not then it will run the start or stop first? So when will it then check failed port and restart should do wat ? Can you explain the sequence I am lost here.
Comment: If the PID doesn't exist, the process will start using the command you specify. If the PID dies, the process will restart using the stop command and start command.
Comment: ok now I am clearer thank you. So how to have two scripts under the stop and start command accordingly.
Comment: `start program = "/path/to/script1 && /path/to/script2"`


Qt: Why does my custom qgraphicsview widget create error during compiling on Linux?

Question: My Qt project compiled successfully on Windows, but when I was trying to compile it on Linux it gives me all kinds of errors including the one I'm asking here:
I have a custom QGraphicsView class in my project, and it's prompted from the Qt designer. When I compiled my codes on a Linux machine, it gives me errors:
/usr/mvl1/hy2vf/metaData/bin/ui_gtvalidation.h:55: error: ISO C++ forbids declaration of 'myGraphicsView' with no type

/usr/mvl1/hy2vf/metaData/bin/ui_gtvalidation.h:55: error: expected ';' before '*' token

/usr/mvl1/hy2vf/metaData/bin/ui_gtvalidation.h: In member function 'void Ui_GTvalidation::setupUi(QDialog*)':

/usr/mvl1/hy2vf/metaData/bin/ui_gtvalidation.h:173: error: 'graphicsView' was not declared in this scope

/usr/mvl1/hy2vf/metaData/bin/ui_gtvalidation.h:173: error: expected type-specifier before 'myGraphicsView'

/usr/mvl1/hy2vf/metaData/bin/ui_gtvalidation.h:173: error: expected ';' before 'myGraphicsView'

Does anyone have had same issues? What's the solution?
Here is the part in ui_gtvalidation.h where it says the problems are. I'm actually not sure what part of my codes I should post to help, so let me know what you want to look at.
55:myGraphicsView *graphicsView;

173:graphicsView = new myGraphicsView(GTvalidation);
    graphicsView->setObjectName(QString::fromUtf8("graphicsView"));

myGraphicsView.h
#include <QtGui>

class myGraphicsView : public QGraphicsView{

public:
myGraphicsView(QWidget* parent = 0);

~myGraphicsView(void);

protected:
//Take over the interaction
virtual void wheelEvent(QWheelEvent* event);

};

myGraphicsView.cpp:
#include "myGraphicsView.h"

myGraphicsView::myGraphicsView(QWidget *parent) : QGraphicsView(parent){
}

myGraphicsView::~myGraphicsView(void){
}

void myGraphicsView::wheelEvent(QWheelEvent* event) {

setTransformationAnchor(QGraphicsView::AnchorUnderMouse);

// Scale the view / do the zoom
double scaleFactor = 1.15;
if(event->delta() > 0) {
    // Zoom in
    scale(scaleFactor, scaleFactor);
} else {
    // Zooming out
    scale(1.0 / scaleFactor, 1.0 / scaleFactor);
}

// Don't call superclass handler here
// as wheel is normally used for moving scrollbars
}

Comment: Your problem is actually in your `gtvalidation.ui` file. When you promote a widget to custom class, you need to specify include header correctly. For some reason compiler cannot find specified header in Linux. The most simple reason of this could be capitalization mismatch (as Linux filesystems are case sensitive and Windows ones are not). Check header files specified in promotion settings of your form in Designer.
Comment: you need to display the class myGraphicsView
Comment: Thanks @PavelStrakhov, that solved the problem. However, I can not find the check mark here to mark your answer lol. Sorry, newbie here.
Answer: Your problem is actually in your gtvalidation.ui file. When you promote a widget to custom class, you need to specify include header correctly. For some reason compiler cannot find specified header in Linux. The most simple reason of this could be capitalization mismatch (as Linux filesystems are case sensitive and Windows ones are not). Check header files specified in promotion settings of your form in Designer.


How to make babel/register affect on imported files?

Question: Below gulpfile.babel.js runs without error by babel-node gulpfile.babel.js (I know that to execute the gulp task I should to run gulp taskname, but babel-node gulpfile.babel.js is for debugging without running tasks).
require('@babel/register');
import gulp from 'gulp';

gulp.task('default', done => {
  console.log('No problem!');
  done();
});

If to include file (node-modules/my-config-helper/index.js in this example) which also contains import or export keywords,  error SyntaxError: Unexpected token export will occur.
require('@babel/register');
import gulp from 'gulp';

import ConfigHelper from 'my-config-helper';

node-modules/my-config-helper/index.js
require('@babel/register');

export default class ConfigHelper {
  constructor() {
    console.log('ConfigHelper: done');
  }
}

Looks like require('@babel/register'); affects only a single file but not to includes. O'K, what should I do? Just install babel-core and babel-register in my-config-helper in not enough.
Answer: You need to move the ES syntax into another file, and require that file from your index.js:
// index.js
require('@babel/register');
require("./gulp-stuff"); <-- from this point on - all ES code will be transpiled

// gulp-stuff.js
import gulp from 'gulp';
import ConfigHelper from './my-config-helper';
// ....

// my-config-helper.js
export default class ConfigHelper {
  constructor() {
    console.log('ConfigHelper: done');
  }
}

Comment: Oh, I see... Thank you for the answer!
Comment: how to use `import` statements in `index.js` and transpile everything in `index.js` *and* everything that subsequently gets imported too, regardless of the folder it is in (except for `/node_modules`)?


how can I include a variable ranging from 0 to 1 in a continuous linear model

Question: Imagine that I am trying to estimate house prices with the following model:
$Y_p=1 + \beta_{surface} * X_{surface} + \beta_{New York}*X_{New York} + \beta_{Boston}*X_{Boston}   $
With $X_{Boston}$ a dummy variable if in Boston
In other words, I assume that the house prices are linearly correlated with surface area, and that there is different mean price in Boston as in New York.
Now I would like to include a house that is between Boston and New York. I could set the both $X_{New York}$ and $X_{Boston}$ to 0.5.
But I am a bit stuck here, as now the predictor is not a dummy anymore but a continuous variable. What should I do to include all houses spread in between New York and Boston and still know the difference in mean price between the two cities?
Answer: Since it sounds like that you only care if the house is either in Boston, in NYC, or between Boston and NYC, just add the extra dummy.
$$Y_P = \beta_{surface}X_{surface} + \beta_{NYC}X_{NYC} + \beta_{Boston}X_{Boston} + \beta_{between}X_{between}$$
where $X_{between}$ is a dummy variable for whether the house is between the two cities.
You need to remove the constant from your regression equation, though. Otherwise, you'll run into a perfect multicollinearity issue (the dummy variable trap).


How to trigger focus event programatically in Reactjs

Question: I'm trying to trigger focus event programatically:
import { useRef } from "react";
import "./styles.css";

export default function App() {
  const ref = useRef();

  function focusTrig() {
    ref.current.focus();
  }

  return (

Hello CodeSandbox

Start editing to see some magic happen!

      <button onClick={focusTrig}>Focus trigger</button>

 console.log("FOCUSED!")}>
        Focus Target

  );
}

demo
The console.log binded with the onFocus event never run. Why?
UPDATE
If I turn the target element from DIV to INPUT, the the console.log get run. But this openly conflicts with the official documentation, that states:

These focus events work on all elements in the React DOM, not just
form elements.

ReactJS 17 DOC
Comment: see if this answers your question https://stackoverflow.com/questions/43145549/how-react-programmatically-focus-input
Answer: Add tabIndex to the div element which indicates that it can be focused

 {console.log("FOCUSED!")}}>
        Focus Target


QStringList contains throwing error

Question: I've got a string I want to compare to the contents of a QStringList.
My string is held in test[1] and my QStringList is imagez.
I believe the QStringList::contains is what I need to use but I'm getting an error.
if(imagez::contains(test[1]) == true){
    foundFiles << file;
}

Error:

expected a class or namespace

Can someone help me out here please!
Answer: Since imagez is a pointer to an object, not a class name, you want the -> operator not the namespace qualifier (::). Like this:
if(imagez->contains(test[1]))

No need to compare booleans for equality to true.
Comment: Awesome, I'm new to all these pointers and then trying to find my way through all the QT documentation is slow! I know what I want to do, just gotta find a way to do it, thanks bud.

QStringList contains throwing error


Question about Fraleigh book, semidirect products and group action.

Question: I have a question about Fraleigh book of abstract algebra, semidirect products and group action.
Is there any reason for Fraleigh to not include Semidirect products in his book?
I have looked into some books and some of them include Semidirect products but not group action, and some other include group action but not semidirect products, some include both. My Abstract Algebra teacher said there is some kind of relation between both of that concepts, but she didn't want to tell me what kind of relation was for some books not to include one of them.
Answer: Fraleigh's book (red hardback with a shaded 3d polygon on the front right?) is an introduction.
A better example of a pure introduction book is: Fundamentals of Abstract Algebra by McCoy. This book is about 1.5x as thick as Fraleigh's and covers less, it is full of examples and questions.
To someone who knows the material the book is almost useless, but to someone trying to learn it the book is valuable.
Practicing topics helps bridge the gap from symbols on paper to what you will later call "intuition" and see naturally in your later work.
Introduction books are very deliberate about what they do and do not have, the order it is presented in and so forth.
If you start doing questions (use any search engine and look for "abstract algebra assignment pdf" or something) you may find you start to spot a link.


Create e Edit OneToMany com ViewModel

Question: Estou criando uma aplicação simples de notícias em ASP.NET MVC 4.
Tenho uma classe Noticia e uma Categoria.
Fiz uma ViewModel
public class NoticiaCategoriaVM
{
    public Noticia Noticia { get; set; }
    public SelectList Categorias { get; set; }
    public HttpPostedFileBase UrlFotoCapa { get; set; }
}

No controller Create estou fazendo assim:
public ActionResult Create()
{
     var model = new NoticiaCategoriaVM();
     model.Categorias = new SelectList(_ctx.Categorias.ToList(), "CategoriaId", "Nome", "SelectedValue");

     return View(model);
}

E o Post da seguinte maneira:
public ActionResult Create(NoticiaCategoriaVM model)
{
}

View
@using App.Rdp.Models
@model NoticiaCategoriaVM

@{
    ViewBag.Title = "Create";
    Layout = "~/Areas/admin/Views/Shared/_LayoutAdmin.cshtml";
}

Cadastar Notícia

@using (Html.BeginForm("Create", "Noticia", FormMethod.Post, new { role = "form", enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary(true)

            @Html.LabelFor(model => model.Noticia.Titulo, new { @class = "control-label" })

        @Html.TextBoxFor(model => model.Noticia.Titulo, new { @class = "form-control input-lg" })
        @Html.ValidationMessageFor(model => model.Noticia.Titulo, null, new { @class = "help-block" })

            @Html.LabelFor(model => model.Noticia.Chapeu, new { @class = "control-label" })

        @Html.TextBoxFor(model => model.Noticia.Chapeu, new { @class = "form-control input-lg" })
        @Html.ValidationMessageFor(model => model.Noticia.Chapeu, null, new { @class = "help-block" })

@Html.LabelFor(model => model.Noticia.Categoria, new { @class = "control-label" })

                @Html.DropDownListFor(model => model.Categorias, Model.Categorias, "- Selecione uma Categoria -", new { @class = "form-control input-lg" })
                @Html.ValidationMessageFor(model => model.Noticia.Categoria, null, new { @class = "help-block" })

@Html.LabelFor(model => model.Noticia.DataPostagem, new { @class = "control-label" })

                @Html.TextBoxFor(model => model.Noticia.DataPostagem, new { @class = "form-control input-lg" })
                @Html.ValidationMessageFor(model => model.Noticia.DataPostagem, null, new { @class = "help-block" })

            @Html.EditorFor(model => model.Noticia.Destaque) Destaque

@Html.LabelFor(model => model.Noticia.UrlFotoCapa, new { @class = "control-label" })

                    Select file
                    Change
                    @Html.TextBoxFor(model => model.UrlFotoCapa, new { type = "file", accept = "image/x-png, image/jpeg", @class = "input-lg" })

                Remove

            @{
                if (ViewBag.Imagem != null)
                {
                    @ViewBag.Imagem
                }
            }

@Html.LabelFor(model => model.Noticia.Conteudo, new { @class = "control-label" })

        @Html.TextAreaFor(model => model.Noticia.Conteudo, new { @class = "form-control input-lg" })
        @Html.ValidationMessageFor(model => model.Noticia.Conteudo, null, new { @class = "help-block" })

        <input type="submit" class="btn btn-primary" value="Cadastrar Notícia" />

}

    @Html.ActionLink("Voltar Para Lista", "Index")

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Porém ao enviar o formulário recebo o seguinte erro:
Edit: Erro completo
Erro de Servidor no Aplicativo '/'.

Nenhum construtor sem parâmetros foi definido para este objeto.

Descrição: Ocorreu uma exceção sem tratamento durante a execução da atual solicitação da Web. Examine o rastreamento de pilha para obter mais informações sobre o erro e onde foi originado no código.

Detalhes da Exceção: System.MissingMethodException: Nenhum construtor sem parâmetros foi definido para este objeto.

Erro de Origem:

Exceção sem tratamento foi gerada durante a execução da atual solicitação da Web. As informações relacionadas à origem e ao local da exceção podem ser identificadas usando-se o rastreamento de pilha de exceção abaixo.

Rastreamento de Pilha:

[MissingMethodException: Nenhum construtor sem parâmetros foi definido para este objeto.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
   System.Activator.CreateInstance(Type type) +6
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +197

[MissingMethodException: Nenhum construtor sem parâmetros foi definido para este objeto. Tipo de objeto 'System.Web.Mvc.SelectList'.]
   System.Web.Mvc.DefaultModelBinder.CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType) +233
   System.Web.Mvc.DefaultModelBinder.BindSimpleModel(ControllerContext controllerContext, ModelBindingContext bindingContext, ValueProviderResult valueProviderResult) +284
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +281
   System.Web.Mvc.DefaultModelBinder.GetPropertyValue(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, IModelBinder propertyBinder) +17
   System.Web.Mvc.DefaultModelBinder.BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor) +382
   System.Web.Mvc.DefaultModelBinder.BindProperties(ControllerContext controllerContext, ModelBindingContext bindingContext) +101
   System.Web.Mvc.DefaultModelBinder.BindComplexElementalModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Object model) +55
   System.Web.Mvc.DefaultModelBinder.BindComplexModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +1198
   System.Web.Mvc.DefaultModelBinder.BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) +330
   System.Web.Mvc.ControllerActionInvoker.GetParameterValue(ControllerContext controllerContext, ParameterDescriptor parameterDescriptor) +331
   System.Web.Mvc.ControllerActionInvoker.GetParameterValues(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +105
   System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__19(AsyncCallback asyncCallback, Object asyncState) +743
   System.Web.Mvc.Async.WrappedAsyncResult`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +14
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Async.AsyncControllerActionInvoker.BeginInvokeAction(ControllerContext controllerContext, String actionName, AsyncCallback callback, Object state) +343
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1c(AsyncCallback asyncCallback, Object asyncState, ExecuteCoreState innerState) +25
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecuteCore(AsyncCallback callback, Object state) +465
   System.Web.Mvc.Controller.<BeginExecute>b__14(AsyncCallback asyncCallback, Object callbackState, Controller controller) +18
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +20
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.Controller.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +374
   System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.BeginExecute(RequestContext requestContext, AsyncCallback callback, Object state) +16
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(AsyncCallback asyncCallback, Object asyncState, ProcessRequestState innerState) +52
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallBeginDelegate(AsyncCallback callback, Object callbackState) +30
   System.Web.Mvc.Async.WrappedAsyncResultBase`1.Begin(AsyncCallback callback, Object state, Int32 timeout) +128
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +384
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +48
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +16
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

EDIT
Códido Action Index
public ActionResult Index()
        {
            var noticias = _ctx.Noticias.ToList().OrderByDescending(n => n.NoticiaId);
            return View(noticias);
        }

Realmente não sei o que está acontecendo.
Comment: Como você esta enviando o POST para o Create?
Já tentou inserir o atributo [HttpPost] no seu método Create(NoticiaCategoriaVM model)
Comment: O Atributo já está inserido.
Comment: Coloque sua view tambem.
Comment: Aparentemente estamos olhando o lugar errado. A Stack Trace indica '/', que normalmente é a rota do método `Index` do seu controller. O que tem nele?
Comment: Apenas pega todas as notícias que tem no banco e mostra em uma tabela.
Comment: Certo. Você pode por favor postar o código dessa `Index`?
Comment: Postei o código!
Answer: Tenta fazer o seguinte, criar um outro atributo em sua ViewModel para receber a categoria que for selecionada, por exemplo

public class NoticiaCategoriaVM
{
    public Noticia Noticia { get; set; }
    public SelectList Categorias { get; set; }
    public HttpPostedFileBase UrlFotoCapa { get; set; }
    public string CategoriaSelecionada { get; set; }
}

E então na sua view, faça isso:

@Html.DropDownListFor(model => model.CategoriaSelecionada, Model.Categorias, "- Selecione uma Categoria -", new { @class = "form-control input-lg" })

Feito isso? Vê se resolve. Se resolver, eu indico com "certeza" o problema que estava acontecendo.

Seria bom se você pudesse postar sua view  também, mas por hora tente
  fazer assim
 public ActionResult Create(NoticiaCategoriaVM model) {
//TODO: Seu método }
Substitua por algo assim
 [HttpPost] public ActionResult
Create([Bind(Include="Noticia.Id,Noticia.Titulo")] NoticiaCategoriaVM
model)  {    //TODO: Seu método }
O atributo Bind, constrói a sua view no controller, ele é implícito,
  mas recomenda-se usar explícito quando se trabalha com uma classe que
  possui outras classes como no seu caso. Tenta isso e nos dê um
  feedback por favor.
PS: Lembrando que no bind, você deve colocar os campos da tela que
  referenciam os objetos
Comment: Postei a view completa
Comment: Vê agora @HermesAutran se resolve
Comment: Funcionou cara, obrigado pela ajuda!
Comment: Não sei se você entendeu o que aconteceu, mas vamos lá, conforme havia dito, o que era o "problema".
@HermesAutran
Você estava pedindo para que fosse atribuído na lista que bindava o dropdownlist o que fosse selecionado nessa lista. Ai teria um erro mesmo pois ele não seria capaz de atribuir um tipo de valor diferente para o campo tipado.
Comment: Eu entendi sim, analisei bem o código e percebi onde estava errando e porque estava errando. Obrigado novamente.
Answer: Como você está usando os campos de notícia dentro da View, o objeto dentro do ViewModel precisa ser inicializado:
public class NoticiaCategoriaVM
{
    public Noticia Noticia { get; set; }
    public SelectList Categorias { get; set; }
    public HttpPostedFileBase UrlFotoCapa { get; set; }

    public NoticiaCategoriaVM() {
        Noticia = new Noticia();
    }
}

A classe Noticia também precisa ter um construtor vazio:
public class Noticia
{
    ...

    public Noticia() {}
}

Comment: Coloquei, mas ainda dá o mesmo erro.
Comment: Editei. Veja agora.
Comment: Fiz do jeito que você colocou, mas ainda persiste o erro!
Comment: Em qual instrução exatamente ocorre o erro? A Stack Trace deve indicar um fonte seu com a linha. Só vi dois objetos que poderiam não ter construtor.
Comment: Postei o erro completo com toda a descrição.
Comment: Expandi a resposta.

Create e Edit OneToMany com ViewModel


Running fixed-effects model stata

Question: I'm running a fixed effects model. My independent variable is store presence, and one of my dependent variables, i.county, measures county fixed effects.
I use xi: regress store_presence i.county other_var othervar2 where county is the US county code, a string variable.
But the regression output reports that some variables "have been omitted due to collinearity".
What should I do to fix this error and capture county-fixed effects in my model?
Comment: Firstly, you have got the terms dependent and independent the wrong way around. Also, please do not use this syntax to estimate fixed effects regressions. It is obsolete (`xi` has been replaced by explicit support for factor variables since Stata 11) and numerically cumbersome (use `xtreg, fe` or `areg` instead). Lastly, omission of variables is not an error, but intended behavior when the design matrix is singular. You need to fix this by making sure that your regression is well-specified.
Comment: Which variables have been omitted due to collinearity?
Answer: The fixed effects model uses the within estimator which after adjustments yields same results as LSDV (least squares dummy variables). The within estimator demean each variable by the group means (and adds the global mean in order to "fix" the intercept such that predictions are center around the response variable mean). If county is the panel identifier (PID) set in xtset PID time, then those are already accounted for. The estimates of the PID effects are not consistent so you should not display them anyhow (the within is preferred for computation efficiency, but this argument is noteworthy). If county is a different identifier (PID is individual and you want to control for their county) one can include them in the regression or cluster at the highest dimension. Instead of xtreg y x, robust do xtreg y x, cl(county). Stata allows for encoded variables (categorical variables with efficient storage and functionality, but with labels). Any string variable that should be considered categorical should be encoded as such: encode Strvar, gen(var).

Running fixed-effects model stata


how to redirect to www while also changing document root folder in htaccess

Question: How to create the following rules in .htaccess ?
Mod rewrite is enabled. But I am running into problems.
For each of the rules in each case (1) and (2) I want them to apply to the domains under that rule.
Currently all domains point to /public_html/. The .htaccess file is in /public_html/.htaccess.

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

1. Set /public_html/web/ as root path!
2. Redirect always to https://www, keep URL and parameters!

domain1.com
domain2.com
domain3.com

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

1. Set /public_html/live/ as root path!
2. Redirect always everything to https://www.domain4.net, keep URL and parameters!

domain4.net
domain5.com

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

1. Set /public_html/staging/ as root path!
2. Redirect always everything to  https://www.domain6.com, keep URL and parameters!

domain6.com
domain7.com
domain8.com
domain9.com

––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––––

1. Keep /public_html/ as root path!
2. Redirect always everything to https://www.domain10.com, keep URL and parameters!

domain10.com
domain11.com
domain12.com

When I attempt to solve with the following:
RewriteCond %{HTTP_HOST} ^domain1.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.domain1.com$
RewriteCond %{REQUEST_URI} !web/
RewriteRule (.*) /web/$1 [L]

RewriteCond %{HTTP_HOST} ^domain1.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.domain1.com [NC]
RewriteRule ^(.*)$ https://www.domain1.com/$1 [L,R=302,NC]

Whenever the URL is accessed it shows the subfolder in the URL which is not what I want!
I found the following from siteground: https://www.siteground.com/kb/how_to_change_my_document_root_folder_using_an_htaccess_file/
RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain-name.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.domain-name.com$
RewriteCond %{REQUEST_URI} !folder/
RewriteRule (.*) /folder/$1 [L]

and tried simply changing this as follows:
RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain-name.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.domain-name.com$
RewriteCond %{REQUEST_URI} !folder/
RewriteRule (.*) https://www.domain1.com/folder/$1 [L]

But this also shows the subfolder in the URL.
Comment: For #2 and #3, why are you concerned about the "root path" when you are redirecting to an entirely different domain? (Or do you have 5 domains pointing to the same host??)
Comment: unfortunately there is no access to the conf's on this server, so I need to achieve with .htaccess
Comment: I tried to simply the question as it was more complicated than I posted.. but I think I've lost something in translation. Could you please check the updated question which should explain things better I hope @MrWhite
Comment: yes exactly all the domains are on the same host, and I'm using one htaccess file for all domains
Comment: Gary, you probably want to set up `name based virtual hosts` instead, which will let you use the regular apache config to do things like set different `DocumentRoot` directives, etc.  Separating things out into separate vhosts will simplify many things, including what appears to be a needlessly overly complex `.htaccess` file/scheme
Comment: So, for #2 it's really `domain2.com` _and_ `domainzyx.net` for which you need to set the (virtual) root to `/live/`?
Comment: Rather than trying to do all that from a `.htaccess` file, simply set up individual virtual host entries for the domains that you're using and then add the logic you want to those virtual hosts
Answer: A few comments on your attempts...

RewriteCond %{HTTP_HOST} ^domain1.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.domain1.com$
RewriteCond %{REQUEST_URI} !web/
RewriteRule (.*) /web/$1 [L]

RewriteCond %{HTTP_HOST} ^domain1.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www.domain1.com [NC]
RewriteRule ^(.*)$ https://www.domain1.com/$1 [L,R=302,NC]

These directives are in the wrong order. The redirect needs to go first in order to prevent the /web subdirectory being exposed. However, in its current incarnation, this would result in a redirect loop as it simply redirects to itself again and again... (I guess maybe the exemplified code introduced this "redirect loop"?).

RewriteEngine on
RewriteCond %{HTTP_HOST} ^domain-name.com$ [NC,OR]
RewriteCond %{HTTP_HOST} ^www.domain-name.com$
RewriteCond %{REQUEST_URI} !folder/
RewriteRule (.*) https://www.domain1.com/folder/$1 [L]

Rewriting to an absolute URL (ie. with scheme + hostname) will implicitly trigger an external redirect and therefore expose the "hidden" subdirectory. You need to keep the redirect (to www.domain1.com) and the rewrite to /folder as separate rules - these are two different tasks.

My first thought is to treat this as one system. All redirects first, followed by the rewrites. I'll treat the redirect to www as the general case, so I'll include this last.
NB: Test with 302 (temporary) redirects first in order to avoid potential caching issues and only change to 301 (permanent) once you have confirmed everything works OK.
For example:
RewriteEngine On

#
# CANONICAL REDIRECTS
#

# Canonicalise www.domain4.net
RewriteCond %{HTTP_HOST} ^domain4\.net [NC,OR]
RewriteCond %{HTTP_HOST} ^(www\.)?domain5\.com [NC]
RewriteRule ^ https://www.domain4.net%{REQUEST_URI} [R=301,L]

# Canonicalise www.domain6.com
RewriteCond %{HTTP_HOST} ^domain6\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^(www\.)?domain7\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^(www\.)?domain8\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^(www\.)?domain9\.com [NC]
RewriteRule ^ https://www.domain6.com%{REQUEST_URI} [R=301,L]

# Canonicalise www.domain10.com
RewriteCond %{HTTP_HOST} ^domain10\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^(www\.)?domain11\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^(www\.)?domain12\.com [NC]
RewriteRule ^ https://www.domain10.com%{REQUEST_URI} [R=301,L]

# Redirect to www subdomain all other domains
# NB: If you have other domains that shouldn't be redirected OR other subdomains
#     then you will need to explicitly check the hostnames as above.
RewriteCond %{HTTP_HOST} !^www\.
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

#
# INTERNAL REWRITES
# NB: Since the request has already been canonicalised (above)
#     We only need to check the canonical hostnames below.
#

# Rewrite to /live
RewriteCond %{HTTP_HOST} ^www\.domain4\.net
RewriteRule !live/ /live%{REQUEST_URI} [L]

# Rewrite to /staging
RewriteCond %{HTTP_HOST} ^www\.domain6\.com
RewriteRule !staging/ /staging%{REQUEST_URI} [L]

# Rewrite to /web
RewriteCond %{HTTP_HOST} ^www\.domain1\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www\.domain2\.com [NC,OR]
RewriteCond %{HTTP_HOST} ^www\.domain3\.com [NC]
RewriteRule !web/ /web%{REQUEST_URI} [L]

# Keep root as the document root for all remaining domains...

This assumes you are already handling the HTTP to HTTPS redirection elsewhere in your config (preferably before these directives).
However, this is not necessarily complete, as the user could still potentially access the /web, /live or /staging subdirectories directly (for any domain) if they are known. This is probably not an issue if this is a new system where these subdirectories have not yet been exposed. Additional redirects can be implemented to canonicalise this if required. Although, if you have additional .htaccess files in these subdirectories then this redirect would need to be included in the subdirectory .htaccess file instead.
Just to clarify, this doesn't "change the document root folder" - that is only possible by changing the server config. This is simply a URL rewrite that hides the subdirectory. The application still sees the document root as defined by the server config, ie. /public_html/.
UPDATE:
If you do not already have a general HTTP to HTTPS redirect then you should add a separate redirect at the top of the .htaccess file. For example:
RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

This redirects from HTTP to HTTPS on the same host (which is actually a requirement should you ever implement HSTS). The redirects that follow then canonicalise the www subdomain as required.
If you have no intention to implement HSTS then you could combine the HTTP to HTTPS and non-www to www redirects into one. And then remove the non-www to www that is currently at the end of the redirect block. For example:
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} !^www\.
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+) [NC]
RewriteRule ^ https://www.%1%{REQUEST_URI} [R=301,L]

Comment: "I had to move the redirect for all other domains to the top" - No, that would be an error. It would not redirect `http://www.domain10.com` - since it has the www subdomain prefix. As stated below the code block, this code assumes you already have an HTTP to HTTPS redirect in place. If not, then you'll need an additional redirect. I'll update my answer....
Comment: NB: In comments, use backticks to surround inline code and URLs.
Comment: Thanks MrWhite this was very helpful! I had to move the redirect for all other domains to the top, because otherwise if a domain was entered like "http://www.domain10.com" prefaced with 'http'://www. it did not redirect to the https version , but since moving the global www rewrite to the top it's working now it seems! Thank you


Can I expose MySQL data using PHP and OData?

Question: As I understand it, OData is just a standardized way to expose relational data RESTfully.  If I've got a PHP application, it should be able to process those RESTful requests and manipulate a MySQL database based on the request data and then return an ATOM feed.  First, are the preceeding statements correct?  Second, does a PHP library to do this already exist or would I have to create my own?
If I have completely misunderstood these technologies and my question doesn't make sense, please feel free to let me know.
Comment: Did you find a server implementation to expose oData via PHP?
Comment: This is pretty old but I am interested in the same topic, where you able to find a good solution?
Answer: OData is a way of exposing all sorts of structured data over an HTTP interface. The underlying repository for data may be relational or not. For example, when using WCF Data Services on top of SQL Server it's certainly a relational data set, but the OData endpoints in SharePoint Server 2010 or on Windows Azure Table Storage run on top of other data models. The high order bit is to make all data available in a web-friendly way.
As for your specific question about MySQL/PHP, there is an OData client for PHP but to my knowledge there isn't a server implementation available. I know there is a MySQL provider for ADO.NET, maybe if it has Entity Framework support you can use WCF Data Services, but that means you'd be running on .NET and not on PHP, don't know if it's acceptable for your situation.
Answer: MySQL/PHP OData Server - http://sourceforge.net/projects/mysqlodata/
Answer: Here is a library to do what you want:
https://github.com/MSOpenTech/odataphpprod/
Answer: The library you needed came out only in September 2011. Here is an MSDN article.


Error: Call to a member function addWhere() on array in hook_views_query_alter()

Question: I'm getting the error 'Call to a member function addWhere() on array' in my hook.
Any thoughts?
I just need to add WHERE clause to my query.
use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\query\QueryPluginBase;

/**
 * Implementation of hook_views_query_alter
 *
 * @param $view
 * @param $query
 */
function MYMODULE_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'search_filter' && $view->getDisplay()->display['id'] == 'block_1') {
    $field = 'node__field_country.field_country_target_id';
    $value = 'somevalue';
    $operator = '=';
    $query->addWhere(0, $field, $value, $operator);

Answer: Try to add your condition to conditions array in the where  $query->where like the following:
/**
 * Implements hook_views_query_alter().
 */
function myModule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() === 'search_filter' && $view->current_display === 'block_1') {
    $field = 'node__field_country.field_country_target_id';
    $value = 'someValue';
    $operator = '=';
    if (isset($query->where[1]['conditions'])) {
      $query->where[1]['conditions'][] = [
        "field"    => $field,
        "value"    => $value,
        "operator" => $operator,
      ];
    }
  }
}

Read this Article it's very useful.
Comment: Thank for this, at least I see how to modify 'where' queries. But why I get an error with addWhere method, I just take this examples from here: https://api.drupal.org/api/drupal/core!modules!views!views.api.php/function/hook_views_query_alter/8.2.x
Answer: Try This code, In drupal 8 we cannot use 'function myModule_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
'. Refer Below code, This works for me, Above code not worked for me. Hope this will helpfull.
function Hook_views_query_alter($view, $query) {
   if ($view->id() == 'content') {
      $field = 'node_field_data.langcode';
      $value = array('en');
      $operator = 'IN';
      $query->where[1]['conditions'][] = [
        "field"    => $field,
        "value"    => $value,
        "operator" => $operator,
      ];
  }
}


If equation a holds and equation b does not hold is it necessary for a+ b to not hold?

Question: I've been using this trick a lot lately, I can't seem to prove why it works.  E.d. (using an inequality here, but point still remains)
:
$$|x-a| \ge |x| - |a|    \tag {1}$$
add $$|x|+|a|\ge |x-a|$$
$$|a|\ge|a|$$
Therefore, $(1)$ is true.
Comment: You tried to show $\beta\ge \gamma$ from $\alpha\ge \gamma$ and $\alpha\ge \beta$. This won't work, for example if $\alpha=3$, $\beta=1$, $\gamma = 2$.
Comment: @RobertZ aye but I was asking whether it's right  to prove things this way. I haven't quite seen this done in any textbook I've read
Comment: let x=3 ;a=4  then we have you saying:

$$|3-4|\ge|3|-|4| $$ aka $$1 \ge -1$$
$$|3|+|4|\ge|3-4|$$ aka $$7\ge  1$$
and
$$|4|\gt-|4|$$    true only because the negative sign is outside the absolute value.   three nearly unrelated statements.
Comment: a further example would be  x=3;a=-1 then we get $$5\ge2$$ $$4\ge5$$ second one clearly false, and  we would have gotten ( if not for your edit)  $$1\gt-1$$
Comment: STOP!  using it!!!!!  It is false and you have been lucky so far that it has worked.  All you are doing is proving that something is not mind numbingly obviously false.  That does not mean it is true.
Answer: Just $|x-a|+|a|\geq|x-a+a|=|x|$.
By your reasoning we can prove that $4>5$.
Indeed, since $3>1$ we "obtain":
$$3+4>1+5,$$
which is true.
"Hence", $4>5$.
Answer: You did
$$\text {unknown inequality}+\text{true inequality} = \text{true inequality}$$
and concluded that the unknown inequality is true. This does not work in general. Take
Unknown inequality: $2>3$
True Inequality: $5>1$
If you add these up you get a true inequality, $7>4$. But as you see this doesn't mean that the unknown inequality must've been true.

Now with equations it's a different matter.
Suppose you have
Unknown equation:$a=b$
True equation: $c=d$
True equation: $a+c=b+d$
To see that the unknown equation is true, just do
$$\text{second true equation} - \text{first true equation}$$
You know that both equations are true so the result of this must be true. But the result is $a=b$, the unknown equation!
Comment: Oh! Damn I see.
Comment: I wonder what addition does to the logical validity of the statement, like why does it work for equalities?
Comment: @Vrisk I edited the answer with that information Hope it helps!
Comment: Oh man, this makes so much sense! Thank you. I now appreciate inverses even more. Like this doesn't work with inequalities because there's no 'inverse'  because it's not one to one. Pretty neat
Comment: @Vrisk Happy to help!


Django error : object has no attribute 'resolve_expression'

Question: Can you give me a hint where to look or what to look for?
Using Python 3.7.9 and Django 3.1.8, I have the following exception when in DEBUG mode. The problem does not appear when running in normal mode.
The problem is new, it was first seen this week (it might have been there before). Going back in git does not help, the problem is still there. There is a lot of code changed.
Can you please give me a hint or a solution? Django is new for me and I do not know how to tackle the issue.
<code>Exception has occurred: AttributeError       (note: full exception trace is shown but execution is paused at: __getattribute__)
'Organization' object has no attribute 'resolve_expression'
  File "****/legal_entity/submodels/organization.py", line 416, in __getattribute__ (Current frame)
    return super().__getattribute__(name)
  File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1062, in resolve_lookup_value
    if hasattr(value, 'resolve_expression'):
  File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1267, in build_filter
    value = self.resolve_lookup_value(value, can_reuse, allow_joins)
  File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1380, in _add_q
    split_subq=split_subq, check_filterable=check_filterable,
  File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/sql/query.py", line 1358, in add_q
    clause, _ = self._add_q(q_object, self.used_aliases)
  File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/query.py", line 969, in _filter_or_exclude_inplace
    self._query.add_q(Q(*args, **kwargs))
  File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/query.py", line 962, in _filter_or_exclude
    clone._filter_or_exclude_inplace(negate, *args, **kwargs)
  File "****/.local/share/virtualenvs/****-zDD7ik9_/lib/python3.7/site-packages/django/db/models/query.py", line 942, in filter
    return self._filter_or_exclude(False, *args, **kwargs)
  File "****/core/subserializers/abstract/business_object.py", line 52, in get_authorized_activities
    user=instance.request_user
.................
</code>
Answer: An AttributeError is an error that is raised when an attribute reference fails.
So the object Organization has no attribute or variable resolve expression.
It might be that your method of reference is wrong because the attribute is there but django can't see it.
So I advice you show the affected code
Comment: The `resolve_expression` attribute is not  part of the model `Organization`. It doesn't appear anywhere in my code. Thus, I do not understand who and why asks for it. The same function is called for the real attributes of `Organization` and everything is ok in that case.


How do I click on a ListView item and open an Activity referring to the item I clicked on?

Question: I click on a custom listview item and everyone opens the same activity, I wanted each of the items to open a different activity.
I've tried in several ways but I'm not getting it, I'm a beginner and I do not have much knowledge, so I came here to ask for help.
It does not have to be the code ready, you can tell me something to help, it would help a lot
<code>    public class artilheiros extends AppCompatActivity {

int [] Imagens = {R.drawable.arg, R.drawable.bolivia, R.drawable.brasil, R.drawable.chile,
          R.drawable.colombia, R.drawable.chile, R.drawable.paraguai, R.drawable.uruguai,
          R.drawable.arg, R.drawable.bolivia, R.drawable.brasil, R.drawable.chile,
          R.drawable.colombia, R.drawable.chile, R.drawable.paraguai};

String [] Nomes = {"ART 1", "ART 2", "ART 3", "ART 4", "ART 5", "ART 6", "ART 7", "ART 8",
                    "ART 9", "ART 10", "ART 11", "ART 12", "ART 13", "ART 14", "ART 15"};

String [] Times = {"TIME 1", "TIME 2", "TIME 3", "TIME 4", "TIME 5", "TIME 6", "TIME 7",
        "TIME 8", "TIME 9", "TIME 10", "TIME 11", "TIME 12", "TIME 13", "TIME 14", "TIME 15"};

String [] Gols = {"999 gols", "999 gols", "999 gols", "999 gols", "999 gols", "999 gols", "999 gols",
       "999 gols", "999 gols", "999 gols", "999 gols", "999 gols", "999 gols", "999 gols", "999 gols"};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_artilheiros);

    final ListView listview = findViewById(R.id.listviewart);
    ListView listview2 = findViewById(R.id.listviewart);

    CustomAdapter customAdapter = new CustomAdapter();

    listview.setAdapter(customAdapter);

    int position = getIntent().getIntExtra("a", 0);

    listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            artilheiros a1 = (artilheiros) listview.getItemAtPosition(0);
            Intent it = new Intent(artilheiros.this, campeoes.class);
            it.putExtra("a1", position);
            startActivity(it);
        }
    });

}

class CustomAdapter extends BaseAdapter{

    @Override
    public int getCount() {
        return Imagens.length;
    }

    @Override
    public Object getItem(int position) {
        return null;
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        convertView = getLayoutInflater().inflate(R.layout.customlistview, null);
        ImageView imageView = (ImageView) convertView.findViewById(R.id.imageView);
        TextView textViewnome = (TextView) convertView.findViewById(R.id.textViewnome);
        TextView textViewtime = (TextView) convertView.findViewById(R.id.textViewtime);
        TextView textViewgols = (TextView) convertView.findViewById(R.id.textViewgols);

        imageView.setImageResource(Imagens[position]);
        textViewnome.setText(Nomes[position]);
        textViewtime.setText(Times[position]);
        textViewgols.setText(Gols[position]);

        return convertView;
    }
}
</code>
}
Comment: Based on the data you are have in your arrays I cannot image the activities you wish to start could be very different from each other. A more likely scenario would be that the activities are identical and only the content would change based on the value of the item you select in your `ListView`. Secondly: Your code would be much cleaner, more maintainable and easier to implement if you would create a custom class with getters and setters for the properties (images, names, times, goals). Create a new object of the class and add that to an `ArrayList` which you pass to your `Adapter`.
Answer: You can use a switch statement. Eg inside onItemClick:
<code>switch (position) {
case 0:
//start Activity 1
break;
case 1:
// start Activity 2
break;
// etc
}
</code>
You didn't tell us what those activities are, but a general principle is to use the least amount of activities as possible. Perhaps you can use a fragment and from onItemClick change some data for that fragment.
Comment: thanks, it worked out right here, in case it would be 6 items to open 6 activitys, 1 in each
Comment: Your welcome. In the future try to keep number of activities a minimum, since they are pretty large objects and have a lot of methods that you don't need.


Why does concatenating a list of string items generated from the name of a DataFrame column fail inside this function?

Question: I encountered a problem I can't explain when performing list concatenation inside vs. outside a function. Specifically, I tried to concatenate a list from a DataFrame column name inside a function and outside the function. Outside seems to work fine, but inside throws an error. See example below.
Example: Suppose I want to write a function that returns multiple lags of a column and assigns new names to the lagged variables based on the original column name. I could do something like this:
import pandas as pd
import numpy as np
rng = np.random.default_rng(22222222)

df = pd.DataFrame({'X':rng.random(10)})

print(df)

          X
0  0.279384
1  0.838032
2  0.298536
3  0.056188
4  0.532023
5  0.560038
6  0.127512
7  0.322774
8  0.813949
9  0.245242

Make the function:
def lagger(column, lags): #Takes as input a DataFrame column in the form df[colname]
    lags = [column.shift(i) for i in range(1, lags+1)]

    df = pd.concat(lags, axis=1) #a DataFrame with a column for each lag.

    names = [f"{column.name}_L{i}" for i in range(1,lags+1)] #generate new names

    df.rename(names, axis='columns', inplace=True)

    return df

Testing the function, I get this error:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[27], line 1
----> 1 lagger(df['X'], 3)

Cell In[25], line 6
      2 lags = [column.shift(i) for i in range(1, lags+1)]
      4 df = pd.concat(lags, axis=1) #a DataFrame with a column for each lag.
----> 6 names = [f"{column.name}_L{i}" for i in range(1,lags+1)] #generate new names
      8 df.rename(names, axis='columns', inplace=True)
     10 return df

TypeError: can only concatenate list (not "int") to list

Something's going on with the list comprehension. Let's try doing a similar comprehension outside the function:
[f"{df['X'].name}_L{i}" for i in range(1,4)]

['X_L1', 'X_L2', 'X_L3']

Works just fine!
So what's going on here? Why does this work outside the function but not inside?
To be clear, I've already found this answer that clears up how to generate multiple lags. I'm not asking about that. I'm asking what's the difference between doing [f"{column.name}_L{i}" for i in range(1,lags+1)] inside the function versus [f"{df['X'].name}_L{i}" for i in range(1,4)] outside the function? Why does it fail inside the function?
Answer: You overwrite your parameter lags with a list in your function. Thus range(1, lags+1) doesn't work anymore. Use another name. Also, your use of rename is incorrect, you should use set_axis:
def lagger(column, lags): #Takes as input a DataFrame column in the form df[colname]
    l = [column.shift(i) for i in range(1, lags+1)]
    df = pd.concat(l, axis=1) #a DataFrame with a column for each lag.
    names = [f"{column.name}_L{i}" for i in range(1, lags+1)] #generate new names
    return df.set_axis(names, axis='columns')

lagger(df['X'], 3)


Easy method of writing a sum of a power series

Question: I need help finding a simple method of writing a simple equation for power series/ maclaurin series. Do I look at how the series develops or could I write the equation based on the sigma notation itself.
an example of this is:
$$
\sum_{n=0}^\infty \frac{x^{2n}}{(n+1)!}
$$
How do I write a simple equation for this series?
Comment: Starting point: think of the basic power series you know. What looks similar? Can you manipulate it?
Comment: Why is $\sum_{n=0}^{\infty}\frac{x^{2n}}{(n+1)!}$ not simple, or from what equation do you talk? take 1/(n+1) outside the sum  and you have $e^{x^2}$
Answer: The equation for that series is:
$$
\frac{-1 + e^{x^2}}{x^2}
$$
To find this, you start with the basic series with a function you already know. For example the geometric series:
$$\frac{1}{1 - x} = \sum_{n=0}^\infty x^n = 1 + x + x^2 + x^3 + \cdots,$$
And then through algebra and working through the series editing you will work through the math to turn
$$ \sum_{n=0}^\infty x^n \rightarrow  \sum_{n=0}^\infty \frac{x^{2n}}{(n+1)!} $$
For example the first step you can take is make $n$ into $2n$ :
$$
\sum_{n=0}^\infty x^{2n} =   \frac{1}{1 - x^2}
$$
(also another hint, $\sum_{n=0}^\infty \frac{1}{n!} = e$ and $\sum_{n=0}^\infty \frac{x^n}{n!} = e^x$)
Comment: thank you so much this way more insightful than the solution sheet for my test exam
Comment: You should be a bit careful, since the series $\sum \frac{x^n}{n!} = e^x$. If you are trying to solve the problem, it's best you play around with that series.
Comment: i did what you told me to do and ended up with: ∑∞n=0 x^2n/n!=e/(1-x^2). how do i increase the factorial from n! to n+1!


Log4j how to configure Log level

Question: I run my war with jboss-as-maven-plugin version 7.3.Final (goal jboss-as:run) from Netbeans 7.2.1.
My pom.xml

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>jcl-over-slf4j</artifactId>
            <version>${slf4j.version}</version>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>${slf4j.version}</version>
            <scope>runtime</scope>
        </dependency>

slf4j.version is 1.7.2.
I have a strange behavior:
Here my log4j.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">

    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Target" value="System.out" />
        <param name="Encoding" value="UTF-8" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{HH:mm:ss,SSS} %-5p: %c - %m%n" />
        </layout>
    </appender>

    <logger name="org">
        <level value="warn" />
    </logger>

    <logger name="org.openid4java">
        <level value="debug" />
    </logger>

    <logger name="fr.mypackage">
        <level value="debug" />
    </logger>

    <root>
        <priority value="warn" />
        <appender-ref ref="console" />
    </root>

</log4j:configuration>

Use :
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
    private static final Logger logger = LoggerFactory.getLogger(MyController.class);

My logger in fr.mypackage don't log nicely. I mean all my logger.debug didn't work, only my logger.warn are displaying. I don't understand because I set fr.mypackage to debug level.
More strange is that log from org.openid4java at level INFO are display.
What should I do? Where is my mistake ?
Thanks
Answer: The problem is at the end. You have set the overall log level to WARN. Change the root logging level to "debug" and all should be fine.
<root>
    <priority value="warn" />
    <appender-ref ref="console" />
</root>

Answer: Adding appender reference to the logger definiton  will solve this issue
<logger name="fr.mypackage">
    <level value="debug" />
    <appender-ref ref="console" />
</logger>

Answer: Check in your server log trace level

Log4j how to configure Log level


negative value of prediction from a training set that only contains positives

Question: a catboost model recently gave me a % of predictions that are negative while none of the training set contains negative values for the label.
How is this possible especially in cases where the % of negative values is higher than 10% of the total predictions?
The features remain, statistically, within the training set bounds.
Comment: and i am bounded by catboost at the moment, can't use any other algorithm.
Answer: Here is an example in R, using a simple linear regression:
<code>> set.seed(1)
> training_pred <- data.frame(rbind(c(1,0),c(1,0),c(0,0),c(0,0),c(0,1),c(0,1)))
> colnames(training_pred) <- paste0("V",1:2)
> training_obs <- as.vector(cbind(1,as.matrix(training_pred))%*%c(1,-.7,-.8)+
+ rnorm(nrow(training_pred),0,0.2))
> training_obs
[1] 0.17470924 0.33672866 0.83287428 1.31905616 0.26590155 0.03590632
</code>
All the training data are positive. Let's fit a model and predict:
<code>> model <- lm(training_obs~V1+V2,training_pred)
> new_pred <- data.frame(matrix(c(1,1),nrow=1,dimnames=list(NULL,paste0("V",1:2))))
> predict(model,newdata=new_pred)
         1
-0.6693423
</code>
We get a negative prediction. Note that the new predictors are squarely within the bounds of the training predictors:
<code>> summary(training_pred)
       V1               V2
 Min.   :0.0000   Min.   :0.0000
 1st Qu.:0.0000   1st Qu.:0.0000
 Median :0.0000   Median :0.0000
 Mean   :0.3333   Mean   :0.3333
 3rd Qu.:0.7500   3rd Qu.:0.7500
 Max.   :1.0000   Max.   :1.0000
> summary(new_pred)
       V1          V2
 Min.   :1   Min.   :1
 1st Qu.:1   1st Qu.:1
 Median :1   Median :1
 Mean   :1   Mean   :1
 3rd Qu.:1   3rd Qu.:1
 Max.   :1   Max.   :1
</code>
Here is what is going on:

In the training sample, the predictors were all at $(1,0)$, $(0,0)$ and $(0,1)$, but in prediction, they are at $(1,1)$. And each separate predictor has a negative parameter estimate:
<code>> model

Call:
lm(formula = training_obs ~ V1 + V2, data = training_pred)

Coefficients:
(Intercept)           V1           V2
     1.0760      -0.8202      -0.9251
</code>
So you will need to look more deeply into the full joint distribution of your features. That they are within the training bounds is a marginal analysis, which is not sufficient.
Comment: thank you for your prompt reply, i will do the joint analysis now.

Regarding catboost it seems that an aggressive learning rate can be the cause as well. Investigating that possibility now.


Swap first number with second, second with third et cetera

Question: I have been given a random checksum algorithm that works this way

enter the number (up to 1 000 000)
the algorithm is n[0]-n[1]+n[2]-n[3] so it's just adding and subtracting parts of the number. If the number is 1243 then 1-2+4-3=0.

If the result is 0 then the checksum passed. If not, I need to swap numbers: First with second, then try, if won't work, second with third, then try and so on. So for 224 it would give me 0 by replacing second 2 and 4.
So far my code is:
<code>#include <stdio.h>
#include <stdlib.h>

  int intlen (long long n)
  {
    int len = 1;
    while ( abs (n) > 9 )
    {
       n /= 10;
       ++len;
    }
    return len;
}
short getDigit (long long num, int index)
{
    int pos = intlen (num) - index;
    while ( pos > 1 )
    {
        num /= 10;
        --pos;
}
    if(intlen(num) <= index) {
        return 0;
    }
    return num % 10;
}
int checkSum(int pin) {
    int wynik = 0;
    int typ = 0;
    int i = 0;
    for(i = 0; i < intlen(pin); i=i+3) {
        if(typ == 0) {
            wynik += getDigit(pin, i) - getDigit(pin, i+1) + getDigit(pin, i+2);
            typ = 1;
        } else {
            wynik -= getDigit(pin, i) - getDigit(pin, i+1) + getDigit(pin, i+2);
            typ = 0;
        }
    }
    return wynik;
}
int main()
{
  int wynik, pin;
  scanf("%d", &pin);
  wynik = checkSum(pin);
   printf("CS: %d\n", wynik);
  system("pause");
    return 0;
}
</code>
But I don't really know on how to do the swapping part. Could someone enlighten me the way on how to do it?
Comment: Figure out which digit is bigger. Subtract the difference (between `0` and `9`) from the bigger digit and add it to the smaller digit. But I would suggest loading your number into an array to make swapping easier.
Comment: All the code would be easier if it were an array...
Answer: Maybe I don't understand what you want to do, but if I did understand correctly this is all you need:
<code>#include <stdio.h>
#include <string.h>

int checkSum(char pin[])
{
    int wynik = 0;
    int sub = 0;
    int i = 0;

    for (i = 0; i < strlen(pin); i++, sub=!sub)
    {
        // use pin[I] - '0' to get the number stored in the array location
        // use sub?-1:1 * X to either subtract or add by multiplying by -1
        wynik = wynik + (sub?-1:1) * (pin[i]-'0');
    }

    return wynik;
}

int main()
{
    char pin[8]; // enough to hold 1000000\0
    int wynik;
    int swap;
    int i=0;

    puts("Enter pin:");
    scanf("%s", &pin);

    // update checksum
    wynik = checkSum(pin);
    printf("PIN=%s CS=%d\n", pin,wynik);

    for (i = 0; wynik != 0 && i < strlen(pin) - 1; i++)
    {
        // swap pin[i] with pin[i+1]
        swap = pin[i]; pin[i] = pin[i+1]; pin[i+1] = swap;

        // update checksum
        wynik = checkSum(pin);
        printf("PIN=%s CS=%d\n", pin,wynik);
    }
}
</code>
The whole thing is easier if you use an array and a string is an array of characters so that's almost perfect - the only thing you need to do to get the digit at some array index is subtract '0' from the value at that index.  The reason this works is that the characters '0' through '9' are contiguous.  That means you don't need getDigit() and intlen() can be replaced by strlen()


In a group of order 21, every normal subgroup is cyclic

Question: Let $P$ be a group of order $21$. How to prove that   each normal subgroup of $P$ is cyclic?
Comment: I replaced the images with TeX markup. See [math notation guide](http://math.stackexchange.com/help/notation).
Answer: Each  proper subgroup of P is cyclic, whether normal or not. Indeed the order of such a subgroup is a strict divisor of 21, by Lagrange's theorem, hence it is of order $1$, $3$ or $7$. It suffices to know a group of prime order is cyclic.


JBAS010447: Connection is not valid

Question: I need help, when i try to create a datasource connection on jboss show this error JBAS010447: Connection is not valid
my connection url is jdbc:oracle:thin:@//localhost:1521/ORCL
on my jboss log show ORA-28040: No matching authentication protocol
Comment: I'm voting to close this question as off-topic because it should be either translated to English or posted on https://es.stackoverflow.com.
Comment: question translated into english
Answer: I think your JDBC driver and Oracle Database version are not suitable. Please check your ojdbc.jar Check this link

JBAS010447: Connection is not valid


How to create a custom control to resemble an electronic breadboard using WPF?

Question: A breadboard is a tool that is used to implement simple electronic circuits, it is a set of nodes used to put ICs on them and connect between them using wires to build the circuit.
Wikipedia
What I want to do is to make a user control in WPF to be used in a larger application that simulates electronic circuits.
The user has to place ICs on that breadboard.
The first approach I used is to make the user control with a background image of a breadboard, inside it is a layout container ex: StackPanel (To stack ICs horizontally) with height that covers the central part of the image.
and then I made another user control that resembles an IC to be added to the former container, I drew the pins and a black rectangle.
Specifically what I want to do now is to make the size of the IC relative to that of the breadboard. meaning that when the size of the breadboard expands or shrinks the IC will remain in the same points it was.
This is the XAML code of the Breadboard:
<UserControl
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:Breadboard"
mc:Ignorable="d"
x:Class="Breadboard.MainControl"
x:Name="UserControl" d:DesignWidth="91.583" Width="Auto" d:DesignHeight="26.501" Padding="0">
<UserControl.Background>
    <ImageBrush ImageSource="Images/breadboard.png" Stretch="Uniform"/>
</UserControl.Background>

<StackPanel x:Name="LayoutRoot" Orientation="Horizontal" VerticalAlignment="Center" Margin="0" Height="8.835">
    <StackPanel.Background>
        <ImageBrush/>
    </StackPanel.Background>
    <local:IC Margin="0" Width="Auto"/>
</StackPanel>

This is the XAML code of the IC:

<Viewbox Stretch="Fill">

    <StackPanel x:Name="LayoutRoot" Height="40" Width="52.833">
        <StackPanel x:Name="UpperPins" HorizontalAlignment="Left" Orientation="Horizontal">
            <Image Source="Images/pin.png" Stretch="Fill" Width="7" Margin="3,0,0,0"/>
            <Image Source="Images/pin.png" Stretch="Fill" Width="7" Margin="6,0,0,0"/>
            <Image Source="Images/pin.png" Stretch="Fill" Width="7" Margin="6,0,0,0"/>
            <Image Source="Images/pin.png" Stretch="Fill" Width="7" Margin="6,0,3,0"/>
        </StackPanel>
        <Rectangle Fill="Black" Height="36"/>
        <StackPanel x:Name="LowerPins" HorizontalAlignment="Left" Orientation="Horizontal" RenderTransformOrigin="0.5,0.5">
            <StackPanel.RenderTransform>
                <TransformGroup>
                    <ScaleTransform/>
                    <SkewTransform/>
                    <RotateTransform Angle="180"/>
                    <TranslateTransform/>
                </TransformGroup>
            </StackPanel.RenderTransform>
            <Image Source="Images/pin.png" Stretch="Fill" Width="7" Margin="3,0,0,0"/>
            <Image Source="Images/pin.png" Stretch="Fill" Width="7" Margin="6,0,0,0"/>
            <Image Source="Images/pin.png" Stretch="Fill" Width="7" Margin="6,0,0,0"/>
            <Image Source="Images/pin.png" Stretch="Fill" Width="7" Margin="6,0,3,0"/>
        </StackPanel>
    </StackPanel>
</Viewbox>

This is the C# code of the IC (The Constructor):
namespace Breadboard{
public partial class IC : UserControl
{
    public IC(int pins)
    {
        if (pins % 2 != 0) throw new OddNumberOfPins();
        this.InitializeComponent();
        Width = (pins/2)*(6 + 7);
        UpperPins.Children.Clear();
        LowerPins.Children.Clear();
        UpperPins.Children.Add(new Image() { Source = new BitmapImage(new Uri(@"Images/pin.png",UriKind.Relative)), Stretch = Stretch.Fill, Width = 7, Margin = new Thickness(3, 0, 0, 0) });
        LowerPins.Children.Add(new Image() { Source = new BitmapImage(new Uri(@"Images/pin.png", UriKind.Relative)), Stretch = Stretch.Fill, Width = 7, Margin = new Thickness(3, 0, 0, 0) });

        for (int i = 0; i < (pins/2)-2; i++)
        {
            UpperPins.Children.Add(new Image() { Source = new BitmapImage(new Uri(@"Images/pin.png", UriKind.Relative)), Stretch = Stretch.Fill, Width = 7, Margin = new Thickness(6, 0, 0, 0) });
            LowerPins.Children.Add(new Image() { Source = new BitmapImage(new Uri(@"Images/pin.png", UriKind.Relative)), Stretch = Stretch.Fill, Width = 7, Margin = new Thickness(6, 0, 0, 0) });

        }
        UpperPins.Children.Add(new Image() { Source = new BitmapImage(new Uri(@"Images/pin.png", UriKind.Relative)), Stretch = Stretch.Fill, Width = 7, Margin = new Thickness(6, 0, 3, 0) });
        LowerPins.Children.Add(new Image() { Source = new BitmapImage(new Uri(@"Images/pin.png", UriKind.Relative)), Stretch = Stretch.Fill, Width = 7, Margin = new Thickness(6, 0, 3, 0) });

    }

    public IC():this(6)
    {

    }
}

public class OddNumberOfPins : Exception
{
    public OddNumberOfPins()
    {
       //TODO
    }
}
}

I'm using Expression Blend to do the XAML
Answer: Create a grid, with columns and rows equal to the number of pin holes.
Place empty columns/rows to account for empty columns/rows in the real device.
In each grid cell add a grid.
In the inner grids create a 3x3 row/column layout.
For the first and last row/column, create * Gridlengths so you can adjust relative sizes between the buffer area and the middle cell.
In the middle cell of the inner grids, add a rectangle with an ellipse using a drawing brush (so again, it stays relative).
Here's XAML with the first row filled in.
<Window x:Class="WpfApplication5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="579" Width="274">
    <Window.Resources>

    </Window.Resources>
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <UserControl Grid.Column="0" Style="{StaticResource ResourceKey=PinHole}"/>
        <UserControl Grid.Column="1" Style="{StaticResource ResourceKey=PinHole}"/>
        <UserControl Grid.Column="3" Style="{StaticResource ResourceKey=PinHole}"/>
        <UserControl Grid.Column="4" Style="{StaticResource ResourceKey=PinHole}"/>
        <UserControl Grid.Column="5" Style="{StaticResource ResourceKey=PinHole}"/>
        <UserControl Grid.Column="6" Style="{StaticResource ResourceKey=PinHole}"/>
        <UserControl Grid.Column="7" Style="{StaticResource ResourceKey=PinHole}"/>
        <UserControl Grid.Column="9" Style="{StaticResource ResourceKey=PinHole}"/>
        <UserControl Grid.Column="10" Style="{StaticResource ResourceKey=PinHole}"/>
        <UserControl Grid.Column="11" Style="{StaticResource ResourceKey=PinHole}"/>
        <UserControl Grid.Column="12" Style="{StaticResource ResourceKey=PinHole}"/>
        <UserControl Grid.Column="13" Style="{StaticResource ResourceKey=PinHole}"/>
        <UserControl Grid.Column="15" Style="{StaticResource ResourceKey=PinHole}"/>
        <UserControl Grid.Column="16" Style="{StaticResource ResourceKey=PinHole}"/>
    </Grid>
</Window>

Now, when you add ICs, split them up into visual parts (top-left corner, etc), and arrange the parts in the right grid cell locations, together as a unit.
In code, you can have an IC unit that you give a top-left cell to, and then the parts of the IC will set their Grid.Row and Grid.Column to the right locations.
Comment: Thank you, but this has to do with the shape of the breadboard itself, I think I can achieve the same effect with any layout with a background image of the breadboard like this [one](http://i.imgur.com/wELgj.jpg)
But this has nothing to do with the real problem I am facing right now. As I said above I want to make the size of the IC relative to that of the breadboard. meaning that when the size of the breadboard expands or shrinks the IC will remain in the same points it was.
Comment: I've added a StackPanel inside the main grid to stack ICs vertically and it works and the width of the ICs (rectangles) inside that StackPanel keeps relevant to the size of breadboard but its height is not because I had to specify it exactly not auto. So how can I make the height relevant to the size of the breadboard as the width.
I've also thought of putting the ICs directly on the main grid, but I couldn't access the cells directly.
Comment: @IslamMoustafa I forgot to add what to do about the ICs. Check the answer now.
Comment: Thank you so much, but can you give me an example with code because I don't know what do you mean by a "visual part" is in WPF
Comment: I'm did it by adding Rectangles to the grid and setting their Grid.Row and Grid.Column and determining their width and height by setting Grid.ColumnSpan and Grid.RowSpan, but still you know the it doesn't look like a real IC, so can you advice me on the best way to implement it to look like a real IC with all the pins and stuff. I thought of inheriting the Rectangle class but it is sealed.
Comment: You'll have to get creative with the drawing brush. That's what will let your parts scale
Answer: Move the Viewbox that you currently have in your IC XAML up to surround the Breadboard's root StackPanel. Once you do that you can used fixed sizing on everything inside the Breadboard and set the desired relative size on the IC also as a fixed size and the Viewbox will handle all the scaling for you, keeping all the internal relative sizing of your controls intact.
Comment: Ok, I don't think that this approach will be valid in multiple ICs Scenario.
Comment: What do you think the problem would be with multiple child controls?
Comment: May be I didn't understand your answer that much, because when the ViewBox of that one IC surround that of the breadboard's, what will happen when a new IC id added..!?
Can you please provide any example..
Comment: The Viewbox doesn't belong to the IC. I was recommending removing it from IC and putting it around the parent control instead so it would be structured like:


Mail Server with different IP than Web Server

Question: I recently had a problem. Somebody hacked a Wordpress Site of one of my customers and sent about 70.000 Spam Emails. So my Server IP got blacklisted on some Providers.
I'm looking now for a solution to send my emails through another Mail Server with a different IP.
My first question is: Is it possible to have different IPs for Web Server and Mail Server or will the E-Mails get marked as Spam?
My second question: If it's possible, how can I configure ISPConfig or Postfix to make realize that?
The other solution would be to clone my server completely but I think that's not a good one...
Comment: 1) yes, this is very common as mail/web server can be on different servers 2) on `/etc/postfix/main.cf` for postfix set the `smtp_bind_address` to whatever IP is available. Note that id you fixed your spamming issue you can request to be lifted from the blacklists
Comment: Most blacklists will lift the ban on your IP usually within 24-48 hours after the spam emails have ceased.
Answer:
Yes, you can do this by either having a separate NIC (network card) or by adding an additional IP to your current NIC.  The exact way of doing this is dependant on your OS but I would hope google would be your friend in helping out how to do that
I am not an expert but a quick google would suggest you can change the smtp_bind_address  entry in /etc/postfix/main.cf and then restart Postfix in order to use a specific IP when sending (you can also change inet_interfaces to set the IP you listen on to receive emails).

You should also make sure you start the process of getting the IP un-blacklisted as you never know when it might be needed in the future!
Comment: I already started unblacklisting and most of the lists deleted the ip from the blacklist. But still there are few BL left...
Comment: My problem with the IP is, that my Server has no second IP available, so I think the solution with smtp_bind_address will not work. The only thing I can do is to use another server. But this server also needs to have postfix installed and communicate with my postfix on the first server. How can I do that? (Or is there a more simple solution?)
Comment: you need to get an extra IP from your ISP, should be cheaper than a whole new server
Comment: I tried. But my Reason "Server abused for Spam" was not OK for the RIPE. Which kind of reason would be okay for that?


Randomly sample bounds from many multi-dimensional points

Question: Let $\mathbb{M}$ be an $m\times n$ matrix, with $m < n$.
My data consists of a large list of points $\mathbf{x}_i\in\mathbb{R}^n$, $i=1,...,N$, where each point satisfies $\mathbb{M}\cdot\mathbf{x}_i = 0$ and $\mathbf{A} < \mathbf{x} < \mathbf{B}$, where vector inequality denotes all component-wise inequality, and $\mathbf{A},\mathbf{B}$ are some vector bounds.
For each vector $\mathbf{b}\in\mathbb{R}^n$, let $\mu(\mathbf{b})$ denote the number of points $\mathbf{x}_i$ that satisfy $\mathbf{x}_i \leq \mathbf{b}$. Obviously $\mu(\mathbf{A}) = 0$ and $\mu(\mathbf{B}) = N$.
Naively taking a random vector $\mathbf{b}$ inside $\mathbf{A} < \mathbf{b} < \mathbf{B}$ will surely yield very low values of $\mu(\mathbf{b})$. Similarly, $\mu(\mathbf{x}_i) = 1$ for most points $\mathbf{x}_i$ I've tried.
So here's my problem. I need a way to randomly sample vectors $\mathbf{b}$ such that all values of $\mu$ are more or less equally represented.
Comment: I wasn't sure how to tag (or title) this question. Feel free to suggest edits.
Comment: There are trivial solutions. E.g., for $x=(x_i), y=(y_i)$ in $\mathbb{R}^n$ define $$(x\vee y)_i=\max(x_i,y_i)$$ and  consider the set of vectors $$B=\{b_A=x_{1_1}\vee x_{i_2}\vee \cdots\vee x_{i_m}\}$$ as $A=\{i_1,i_2,\ldots,i_m\}$ ranges over all nonempty subsets of $\{1,2,\ldots,N\}.$ Sampling from $B$ seems to satisfy all your requirements, because the cardinality of $b_A$ will be at least $m$ and (generically) all allowable nonzero cardinalities will appear. One would think that this set of possibilities is too limited. Assuming that's the case, please clarify your requirements.
Comment: @whuber I have tried this method. The values in the middle of the range of $\mu$ are underrepresented. For example, if $m$ is 1, $\mu=1$ most of the time. But if $m=2$, $\mu$ can jump to 10, rarely touching the values in between. I have added an edit to the question to make it clear that the values in the range of $\mu$ should be more or less equally represented.
Comment: So you're saying you don't care about what the values of $b$ are--it's ok if they are limited to at most $2^N-1$ discrete vectors--provided that $\mu(b)$ has a uniform distribution on $\{1,2,\ldots,N\}$?
Comment: @whuber Yes, that's what I am saying. The distribution of $\mu(\mathbf{b})$ doesn't have to be strictly uniform. I just want all values in its range to be represented, with no values significantly less represented than other values.
Answer: There is a simple way: by picking a coordinate index and sorting the $x_i$ based on their component in this index, we can easily find any specified number of the $x_i$ that are determined by an inequality of the form $x_i \le b$.

As a preliminary calculation, sort the $x_i$ on each coordinate $j$, writing $x_{[i]}^{j}$ for the $i^\text{th}$ smallest element of the data $(x_1^j, x_2^j, \ldots, x_N^j)$, $1\le j\le n$.  (Because the question uses subscripts to index vectors, I will use superscripts to index their coordinates.)  For convenience of notation, write $x_{[0]}^j = A^j$ and $x_{[N+1]}^j=B^j$ for all $j$, whence for each $j,$ $1\le j \le n,$
$$A^j = x_{[0]}^j \lt x_{[1]}^j \le \cdots \le x_{[i]}^j \le \cdots \le x_{[N]}^j \lt x_{[N+1]}^j = B^j.$$
Select $i \in \{0,1,\ldots,N\}$ uniformly at random and choose $j \in \{1,2,\ldots, n\}$ in any manner you like.  This determines a set $E_i^j$ of vectors $b$ with
$$b^j \in [x_{[i]}^{j}, x_{[i+1]}^j) \text{ and } b^{j^\prime} \in [x_{[N]}^{j^\prime}, B^{j^{\prime}}) \text{ for } j^\prime \ne j.$$
Let $y$ be an arbitrary vector.  Since $y \le b$ if and only if $y^k \le b^k$ for all $1\le k \le n$, this--by the construction of $b$--means $y^j \lt x_{[i+1]}^j$ and $y^{j^\prime} \le x_{[N]}^{j^\prime}$.  Provided there are no ties for $x_{[i+1]}^j$, the former inequality has exactly $i$ solutions (by definition) and the assumptions about $B$ show that the latter set of inequalities is always satisfied.  Therefore $\mu(b) = i$. Select $b\in E_i^j$ in any manner you like.  Since $i$ has a uniform distribution, so does $\mu(b)$.

Two coordinates of $N=10$ vectors are shown as blue dots.  The rectangle delimited by $A$ and $B$ is shown as a pale unit square.  To include exactly $i=5$ vectors, pick either the fifth smallest of the first coordinates and the largest of all other coordinates (shown at the left for $j=1$) or the fifth smallest of the second coordinates and the largest of all other coordinates (shown at the right for $j=2$).  A value of $b$ is shown as a red dot and the region of points it selects is depicted as a darker shaded rectangle.  In this construction it does not matter whether all vectors are confined to a linear subspace, provided only that the coordinates vary over the subspace.
The only condition required for this to work was that there exist at least one coordinate $j$ for which there are no ties among the $(x_i^j)$.  This method will still produce an approximately uniform distribution of $\mu(b)$ provided there is at least one coordinate where the sizes of the tied groups are all very small compared to $N$.
Comment: Sorry, "$x$" has become seriously overloaded, hasn't it?  I'll see if I can fix it without introducing any errors :-).
Comment: I am writing the data matrix as $(x_i^j)$. All such values are real numbers. The first index $i$ is for the vector and the second $j$ is for the coordinate.
Comment: I defined that term in the first line of the answer: it's a *number* equal to the $i^\text{th}$ smallest among all $N$ of the $j^\text{th}$ coordinates. I hope the illustration I added will help clarify any issues related to this notation.
Comment: Good point--I neglected to indicate their corresponding components.  I'll fix that.  I'll also make the use of superscripts for coordinates more consistent throughout.
Comment: +1 Thanks. I finally got the idea. Sorry about the notation issues... Deleting comments...
Comment: The notation issues were entirely my fault; I appreciate your patience with them.


Ping command is not accepted if firewall is on at remote system

Question: I am using ping command to know whether remote machine is on or not. But problem is that ping command (ICMP Packect) is not accepted at remote machine if firewall is on and it assumed that remote machine is off because ping status returns false. Is there any alternative way to know that remote machine is on or not assuming firewall is on.
Comment: I find it strange that this question is tagged 'c++'.
Answer: Depending on the firewall configuration you may be able to use a TCP SYN ping.
Effectively you will either get an ACK back if it's listening on the port, or a RST if it's not.
Various tools exist that do this, notably NMAP
Answer: If the other computer is on the same local area network, it should still answer to ARP requests even though it's blocking ping. In this case, you could try to use something like arping. More information on Wikipedia.
Over a larger network, I can't think of a reliable way of telling whether a host is on or not without its cooperation.
Comment: It says remote machine. It makes no comment as to whether it is on the same subnet or not.
Comment: The questions states that its on a remote network, so I dont think ARP will help much here.
Answer: If the firewall is any good, there is no way to check for this. The whole point of a firewall is that, if the packet you send is rejected, you don't get any clues at all as to the state of the receiving server: the core idea is that you don't get to tell between the case of
1) the server isn't there, and
2) the firewall blocked you.
In order to tell if the remote server is on, you have to decide on some port on which the server will respond, and make an appropriate hole in the firewall.
Answer: (not enough reputation yet to comment so I'm adding this as an answer)
This is a reason that I usually encourage allowing at least a few icmp types (echo request, echo reply and time exceeded come to mind) on all machines, because dropping ICMP is not really hiding the existence of the machine anyway (it might for machines behind it, though), but mostly hinders monitoring and network debugging.
If you're really paranoid about pingflood attacks, some sort of rate limiting might do (or filters only on the border side of the network).
Take note that not answering to an echo request is not a sign of the machine not being there, that is usually signalled by the last router replying with an ICMP packet type 3, code 1 (host unreachable), so making a machine really invisible is more complicated than it appears.
As for the original question, one of the nmap scans usually does the job (more than often a so-called "tcp ping" scan).
Answer: The way that I do this is to initiate a TCP connection to a known open port. If it's a web server, it will respond on port 80 (or 443). A positive response indicates that the machine is alive. A negative response indicates one of many possible problems, such as connectivity through the network, incorrect firewall configuration, service outage, or the machine being down.
If you're setting up monitoring and just want to know when to pay attention to the machine, just rely on a known-open port. At least if it stops responding, you'll know something is up.
Answer: Most modern firewalls may also intercept the initial SYN-SYN/ACK-ACK to hep prevent resource exhaustion type attacks (i.e. send a lot of SYNs forcing the server to put a entry in its connection table and then never continue the connection -- to make this type of attack more aggressive, these connections can be from spoofed IP addresses).
You may need to open a connection and actually request data to have more assurance that the server is actually up (of course caching servers and other things could foil even this).
What type of server is it?  The connection type can be geared to the service offered by the server.  Tools like nmap (http://nmap.org/) can request the http header for instance.
Answer: Isn't this a Windows question? Windows is the only OS that's retarded enough to block ping by default.
I really hate this. I wonder how many man-years have been wasted by people troubleshooting the network just because ping didn't work.
Comment: I doubt that very much, I imagine it's just the most common one :)

I agree blocking pings is not especially useful.

Lots of consumer-grade routers block pings with their default ACLs.
Answer: You can do an ARP Ping.   Even if the firewall is preventing ICMP pings from occurring, ARP Ping basically asks if anyone is using the specific IP.  ARP is used to make sure there's not IP collisions, so the machine has to respond. Once such tool is here.
Comment: ARP ping will work only if you are in the same LAN (local network).
Comment: Hmmm.  Even though he said it was remote, I assumed he was vpn'ed into its LAN.


Why ternary diagrams work

Question: I am trying to understand why ternary diagrams work. In order that the altitude criterion be valid, if I correctly understand, given equilateral triangle $ABC$, whose vertices I name as the three phases $A,B,C$, the sum $XL'+XM'+XN'$ (see figure on the left; I use the same notation for sides and their length) of the distances of point $X$, contained inside the triangle, from the sides must equate the height of $ABC$. Why does that holds?

Moreover, in order that the intersection method hold and the ratios between the three phases be respected, I would say that, if we respectively call $L,M$ and $N$ the intersection point between straight line $\overline{CX}$ and $AB$, between straight line $\overline{AX}$ and side $BC$ and between straight line $\overline{BX}$ and side $AC$, I would say that the following equality should hold:$$\frac{AN}{CN}=\frac{AL}{BL}\frac{BM}{CM}$$because, if $a,b$ and $c$ respectively are the quantities of phases $A,B$ and $C$, I would say that the equality is equivalent to $\frac{c}{a}=\frac{b}{a}\frac{c}{b}$ (where the factors correspond to each other: $\frac{c}{a}=\frac{AN}{CN}$ etc.). How can it be proved?
While ternary diagrams are ubiquitous in several sciences, like geology, I can find nothing explaining the mathematical foundations of such diagrams, why they work.
I suspect that what I have said can be proved by using elementary or analytic geometry, but I must admit that I can find no way to prove them to myself (there is possibly some rust on my knowledge of elementary geometry). I thank you very much for any answer!
Comment: The altitude criterion comes from [Vivani's Theorem](http://en.wikipedia.org/wiki/Viviani%27s_theorem). Are you also asking how to show that the "intersection method" works?
Comment: @user86418 Thnak you very much! Viviani's theorem is easy, but very nice! Yes, I'm asking why the "intersection method" works, too
Answer: The diagram below uses a slightly different labeling ($A$, $B$, and $C$ are opposite $L$, $M$, and $N$ respectively). Here's a computational justification of the intersection method. (It's possible there are simpler arguments.)
Let $(x, y, z)$ denote spatial Cartesian coordinates. Without loss of generality, the triangle lies in the plane with equation $x + y + z = 1$. If $X = (a, b, c)$, then the labeled points have Cartesian coordinates
\begin{align*}
A &= (1, 0, 0), & B &= (0, 1, 0), & C &= (0, 0, 1), \\
L &= \frac{1}{b + c}(0, b, c),&
M &= \frac{1}{a + c}(a, 0, c),&
N &= \frac{1}{a + b}(a, b, 0).
\end{align*}
By the Cartesian distance formula,
$$
XA^{2} = (1 - a)^{2} + b^{2} + c^{2}
   = (b + c)^{2} + b^{2} + c^{2}
   = 2(b^{2} + bc + c^{2})
$$
and
$$
LA^{2} = 1 + \frac{b^{2} + c^{2}}{(b + c)^{2}}
  = 2\frac{b^{2} + bc + c^{2}}{(b + c)^{2}}.
$$
Thus $\dfrac{XA}{LA} = b + c = 1 - a$. By similar calculations (or symmetry of the labels!), $\dfrac{XB}{MB} = a + c = 1 - b$ and $\dfrac{XC}{NC} = a + b = 1 - c$.
It follows that
$$
\frac{LX}{LA} = 1 - \frac{XA}{LA} = a,\quad
\frac{MX}{MB} = b,\quad
\frac{NX}{NC} = c,
$$
so that $\dfrac{LX}{LA} + \dfrac{MX}{MB} + \dfrac{NX}{NC} = a + b + c = 1$, as claimed.
Comment: @Self-teachingDavide: You're welcome! And your suspicions are correct, as can be checked with the distance formula:$$MA=\frac{c\sqrt{2}}{a + c},\quad MC=\frac{a\sqrt{2}}{a + c}, \qquad\therefore \frac{MA}{MC} = \frac{c}{a}.$$The other ratios are similar.
Comment: I see: $\frac{AN}{BN}=\frac{b}{a}$ and $\frac{BL}{CL}=\frac{c}{b}$. I heartily thank you! Moreover, it can be esaily checked by means of similarity of triangles that $\frac{LX}{LA}=\frac{d(X,BC)}{h}$ (where $h$ is the height of $ABC$), which proves that the "altitude method" and the "intersection method" are equivalent.
Comment: ...one interesting thing more: your calculation for the ratios shows that $\frac{BN}{AN}=\frac{LX/LA}{MX/MB}=\frac{\text{quantity of phase }A}{\text{quantity of phase }B}$, which shows that we can calculate the ratios between the phases on the sides of the triangle.
Comment: Thank you so much for your detailed and very clear answer! There is one thing that I cannot infer: I think that $\frac{AM}{CM}=\frac{AN}{BN}\frac{BL}{CL}$ must hold, but I don't see a way to deduce it... $\infty$ thanks again!

Why ternary diagrams work