text:
Q: Generating fake data to populate database I am trying to use factory boy and faker to generate some fake data for a website I am building. Here is my models.py:
# External Imports
from django.db import models
import uuid

# Internal Imports
from applications.models.application import Application
from users.models.user import User
from .session import Session

# Fake data
import factory
import factory.django
import factory.fuzzy
from datetime import datetime
from faker import Faker
from faker.providers import BaseProvider
import random

class ButtonClick(models.Model):
    """**Database model that tracks and saves button clicks for an application**
    """
    # identifier
    id = models.UUIDField(default=uuid.uuid4, primary_key=True, editable=False)

    # info
    button_name = models.CharField(max_length=128, null=True, blank=True)
    application = models.ForeignKey(
        Application, related_name='button_clicks', null=True, blank=True, on_delete=models.CASCADE)
    user = models.ForeignKey(
        User, related_name='button_clicks', null=True, blank=True,      on_delete=models.CASCADE)
    session = models.ForeignKey(
        Session, related_name='button_clicks', null=True, blank=True, on_delete=models.CASCADE)
        timestamp = models.DateTimeField(auto_now=True)

class Meta:
    db_table = 'button_clicks'
    ordering = ('-timestamp', )

def __str__(self):
    return f'{self.application} - {self.button_name}'

fake = Faker()
faker = Factory.create()

class ApplicationFactory(factory.DjangoModelFactory):
    class Meta:
        model = Application

    application = factory.LazyAttribute(lambda _: faker.word())

class FakeButtonClick(factory.django.DjangoModelFactory):
    class Meta:
        model = ButtonClick

    button_name = factory.Faker('first_name')
    application = factory.SubFactory(ApplicationFactory)
    user = factory.Faker('name')
    session = factory.Faker('random_int')
    timestamp = factory.Faker('date')

When I try to run the following code in the terminal, I get an error:
>>> from analytics.models.button_click import FakeButtonClick
>>> for _ in range(200): FakeButtonClick.create()
...

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/factory/base.py", line 564, in create
    return cls._generate(enums.CREATE_STRATEGY, kwargs)
  File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/factory/django.py", line 141, in _generate
    return super(DjangoModelFactory, cls)._generate(strategy, params)
  File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/factory/base.py", line 501, in _generate
    return step.build()
  File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/factory/builder.py", line 279, in build
    kwargs=kwargs,
  File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/factory/base.py", line 315, in instantiate
    return self.factory._create(model, *args, **kwargs)
  File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/factory/django.py", line 185, in _create
    return manager.create(*args, **kwargs)
  File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/django/db/models/manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/django/db/models/query.py", line 431, in create
    obj = self.model(**kwargs)
  File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/django/db/models/base.py", line 482, in __init__
    _setattr(self, field.name, rel_obj)
  File "/Users/ryan/bloks/bloks-backend/venv/lib/python3.7/site-packages/django/db/models/fields/related_descriptors.py", line 219, in __set__
    self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "9714": "ButtonClick.application" must be a "Application" instance.

I have created some very simple data using factory boy and faker in the past but the traceback seems to be implying that I need to create an application instance within my FakeButtonClick class? I checked the documentation and application doesn't appear to be an available instance for factory boy/faker. Do I need to create the instance myself? Maybe a subfactory?

A: Your ButtonClick model has 3 fields defined as a ForeignKey: application, user and session.
When you want to create a ButtonClick instance, Django requires that you provide a valid value to each field defined as a ForeignKey — here, this means providing either model instances or None (since those ForeignKey are nullable).
With FactoryBoy, this means that you'll have to:

*

*Define a Factory class for each of these models.

*Use a factory.SubFactory pointing to those factories for each of the fields.

An example would be:

class UserFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = User
    username = factory.Faker('username')

class SessionFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Session
    uuid = factory.Faker('uuid4')
    user = factory.SubFactory(UserFactory)

class ApplicationFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = Application
    name = factory.Faker('name')

class ButtonClickFactory(factory.django.DjangoModelFactory):
    class Meta:
        model = ButtonClick
    user = factory.SubFactory(UserFactory)
    # Ensure that click.user == click.session.user
    session = factory.SubFactory(SessionFactory, user=factory.SelfAttribute('..user'))
    application = factory.SubFactory(ApplicationFactory)

You can take a look at the docs.
By the way, with FactoryBoy's faker integration, you don't need to import it directly: factory.Faker('uuid4') is equivalent to faker.Faker().uuid4().

A: Here's my database-populate file, probably may help you (a lot simpler than your file I believe):
# Don't change the format. Order matters!

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')

import django
django.setup()

import random
from faker import Faker

from todo.models import Todo

fakegen = Faker()

def populate(N = 10):
    for entry in range(N):
        fake_tmp = fakegen.catch_phrase()
        levels = ['important', 'normal', 'unimportant']

        fake_title = fake_tmp if len(fake_tmp) <= 40 else (fake_tmp[:37] + '...')
        fake_desc = fakegen.sentence(nb_words=70)
        fake_level = levels[random.randint(0, 2)]

        todo_item = Todo.objects.get_or_create(title=fake_title, desc=fake_desc, level=fake_level)

if __name__ == '__main__':
    print('Populating data...')
    populate(20)
    print('Populating complete')

A: This is how I generated fake data into Django sqlite
Mackaroo website
go to this website and fill out details and download file in any format (sql, json or csv) any format
The good thing about this website you can provide regular expression on your columns null values and any format for numbers, dates etc
then either download it or dump it in your database

A: for future readers!
To generate fake data for django you can use django-seed.
It's an easy process as

*

*pip install django-seed (install django-seed)

*add django_seed in your apps in settings.py file.
INSTALLED_APPS = (
    ...
    'django_seed',
)

*python manage.py seed <app-name>
for example: to seed api app of django python manage.py seed api --number=15
If you need, you can also specify what value a particular field should have. For example, if you want to seed 15 of MyModel, but you need my_field to be the same on all of them, you can do it like this:
python manage.py seed api --number=15 --seeder "MyModel.my_field" "1.1.1.1"


text:
Q: Update data using Entity Framework This is my view for editcar :
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<J2V.Models.vehicule>" %>
//code
<% using (Html.BeginForm("editcar", "Agence", FormMethod.Post, new { @class = "search_form" })) { %>
    <%: Html.ValidationSummary(true) %>
    <fieldset>
        <legend>vehicule</legend>
        // Those colonne will not be modified
        <%: Html.HiddenFor(model => model.Matv) %>
        <%: Html.HiddenFor(model => model.Idag) %>
        <%: Html.HiddenFor(model => model.Idcat) %>
        <%: Html.HiddenFor(model => model.idmarque) %>
        <%: Html.HiddenFor(model => model.modele) %>

        //Colonne to edit code

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>
<% } %>

This is my controller action :
[HttpPost]
public ActionResult editcar(Models.vehicule model)
{
        if (ModelState.IsValid)
        {
            entity.vehicule.AddObject(model);
            entity.ObjectStateManager.ChangeObjectState(model, System.Data.EntityState.Modified);
            entity.SaveChanges();
            return View("index", new { id = model.Idag });
        }
        else
            return View();
}

When I click on the Update button I get this error :

System.InvalidOperationException: The model item passed into the dictionary is of type '<> f__AnonymousType2 1 [System.String]' but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1 [J2V.Models.vehicule] '.

A: Generally an 'index' view's model is an IEnumerable<YourModel>.
But after updating, you are pushing an anonymous object into the 'index' view; (line: return View("index", new { id = model.Idag });) This might be the cause of the exception.
You may redirect to the index action:
if (ModelState.IsValid)
    {
        entity.vehicule.AddObject(model);
        entity.ObjectStateManager.ChangeObjectState(model, System.Data.EntityState.Modified);
        entity.SaveChanges();
        //return View("index", new { id = model.Idag });
        return RedirectToAction("index", new { id = model.Idag });
    }
    else
        return View();

Hope this helps...

redpajama_set_name: RedPajamaStackExchange


text:
Q: DBGp proxy error Handler response error: Error reading command: Don't understand command '[507]' Remote debugging using Xdebug DBGp proxy and PhpStorm:

*

*Ubuntu 22.10

*PHP 8.1

*Xdebug v3.1.2

*Xdebug DBGp proxy (0.4.2-dev)

./dbgpProxy
Xdebug DBGp proxy (0.4.2-dev)
Copyright 2020 by Derick Rethans
2023-02-13 07:16:48.394 [warn] [SSL] The 'certs/fullchain.pem' file could not be found, not enabling SSL listeners
2023-02-13 07:16:48.394 [info] [dbgpProxy] Proxy started
2023-02-13 07:16:48.395 [info] [server] Started server server on 127.0.0.1:9003
2023-02-13 07:16:48.395 [info] [server] Started client server on 127.0.0.1:9001

Xdebug settings:
zend_extension=xdebug.so
xdebug.mode=debug
xdebug.client_host=127.0.0.1
xdebug.client_port=9003
xdebug.log=/tmp/xdebug.log

SSH settings:
RemoteForward 9001 localhost:9001
LocalForward 9001 localhost:9001

Tools -> DBGp proxy -> Register IDE
2023-02-13 07:17:08.768 [info] [server] Start new client connection from 127.0.0.1:33682
2023-02-13 07:17:08.839 [info] [proxyinit] [POLYANIN] Added connection for IDE Key 'POLYANIN': 127.0.0.1:9001
2023-02-13 07:17:08.840 [info] [server] Closing client connection from 127.0.0.1:33682

The error:
2023-02-13 07:28:18.141 [info] [proxy-client] [POLYANIN] Found connection for IDE Key 'POLYANIN': 127.0.0.1:9001
2023-02-13 07:28:18.141 [info] [proxy-client] [POLYANIN] Connecting to 127.0.0.1:9001
2023-02-13 07:28:18.142 [info] [proxy-client] [POLYANIN] IDE connected
2023-02-13 07:28:18.142 [info] [server] Start new client connection from 127.0.0.1:33694
2023-02-13 07:28:18.142 [info] [proxy-client] [POLYANIN] Init forwarded, start pipe
2023-02-13 07:28:18.142 [warn] [server] Handler response error: Error reading command: Don't understand command '[507]'
2023-02-13 07:28:18.142 [info] [server] Closing client connection from 127.0.0.1:33694
2023-02-13 07:28:18.192 [info] [proxy-client] [POLYANIN] IDE closed connection

I put a breakpoint and refresh the page.

A: You cannot use the DBGp proxy this way, as it always sends the debug data to the host where the IDE registration with the key came from.
Since you are using a tunnel, it always comes from 127.0.0.1; this is why you get Found connection for IDE Key 'POLYANIN': 127.0.0.1:9001, and this is why you get the error message - the proxy tries to send the debug data to itself instead of PhpStorm.
There is an extremely ugly workaround - you can modify the proxy code so that it uses the IDE key as a port number to connect to:
https://intellij-support.jetbrains.com/hc/en-us/community/posts/360010264920-xdebug-multiple-developers-php-storm-dbgpproxy


text:
Q: LibGDX problems detecting collision, Android Studio I have my game almost ready, however, when I add the obstacle collision and set it to player alive false, the circle just keeps going like if the obstacle was not an enemy, how do I fix this? Here's the code in MainGame.java :
package com.circlecrashavoider;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Manifold;
import com.badlogic.gdx.physics.box2d.World;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.utils.viewport.FitViewport;
import com.circlecrashavoider.entities.FloorEntity;
import com.circlecrashavoider.entities.ObstacleEntity;
import com.circlecrashavoider.entities.PlayerEntity;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Created by Felipe on 2/22/2016.
 */

public class GameScreen extends BaseScreen {

    private Stage stage;

    private World world;

    private PlayerEntity player;

    private List<FloorEntity> floorList = new ArrayList<FloorEntity>();

    private List<ObstacleEntity> obstacleList = new ArrayList<ObstacleEntity>();

    public GameScreen(MainGame game) {
        super(game);
        stage = new Stage(new FitViewport(1024, 620));
        world = new World(new Vector2(0, -10), true);

        world.setContactListener(new ContactListener() {

            private boolean areCollided(Contact contact, Object userA, Object userB) {
                Object userDataA = contact.getFixtureA().getUserData();
                Object userDataB = contact.getFixtureB().getUserData();

                if (userDataA == null || userDataB == null) {
                    return false;
                }

                return (userDataA.equals(userA) && userDataB.equals(userB)) ||
                        (userDataA.equals(userB) && userDataB.equals(userA));
            }

            @Override
            public void beginContact(Contact contact) {
                if (areCollided(contact, "player", "floor")) {
                    player.setJumping(false);
                }

                if (areCollided(contact, "player", "obstacle")) {
                    if (player.isAlive()) {
                        player.setAlive(false);
                    }
                }
            }

            @Override
            public void endContact(Contact contact) {

            }

            @Override
            public void preSolve(Contact contact, Manifold oldManifold) {

            }

            @Override
            public void postSolve(Contact contact, ContactImpulse impulse) {

            }
        });
    }

    @Override
    public void show() {
        Texture playerTexture = game.getManager().get("player.png");
        Texture floorTexture = game.getManager().get("floor.png");
        Texture overfloorTexture = game.getManager().get("overfloor.png");
        Texture obstacleTexture = game.getManager().get("obstacle.png");

        player = new PlayerEntity(world, playerTexture, new Vector2(1, 2));

        floorList.add(new FloorEntity(world, floorTexture, overfloorTexture, 0, 1000, 1));
        obstacleList.add(new ObstacleEntity(world, obstacleTexture, 6, 1));
        stage.addActor(player);
        for (FloorEntity floor : floorList) {
            stage.addActor(floor);
        }
        for (ObstacleEntity obstacle : obstacleList) {
            stage.addActor(obstacle);
        }
    }

    @Override
    public void hide() {
        player.detach();
        player.remove();
            for (FloorEntity floor: floorList) {
                floor.detach();
                floor.remove();
            }
            for (ObstacleEntity obstacle: obstacleList) {
                obstacle.detach();
                obstacle.remove();
            }

    }

    @Override
    public void render(float delta) {
        Gdx.gl20.glClearColor(0.5f, 0.6f, 1, 3f);
        Gdx.gl20.glClear(GL20.GL_COLOR_BUFFER_BIT);

        stage.act();
        world.step(delta, 6 ,2);
        stage.draw();
    }

    @Override
    public void dispose() {
        stage.dispose();
        world.dispose();
    }
}

Here's the download link in case you need more information, It's the last thing I need to do to finish my game.
http://www.mediafire.com/download/992ys6adq4s6s4y/CircleCrashAvoider.7z


text:
Q: predicting X values from smooth.spline I have an existing smooth.spline object, and I wish to estimate X values for a set of new Y values. I see that predict.smooth.spline exists, but for predicting Y for new Xs.
Are there methods for predicting X from Y? (Apparently this is common in biomedical fields when working with standard curves for blood assay concentrations).
Thanks for any suggestions.


text:
Q: Organizing tensor into batches of dynamically shaped tensors I have the following situation:

*

*I want to deploy a face detector model using Tensorflow Serving: https://www.tensorflow.org/serving/.

*In Tensorflow Serving, there is a command line option called --enable_batching. This causes the model server to automatically batch the requests to maximize throughput. I want this to be enabled.

*My model takes in a set of images (called images), which is a tensor of shape (batch_size, 640, 480, 3).

*The model has two outputs: (number_of_faces, 4) and (number_of_faces,). The first output will be called faces. The last output, which we can call partitions is the index in the original batch for the corresponding face. For example, if I pass in a batch of 4 images and get 7 faces, then I might have this tensor as [0, 0, 1, 2, 2, 2, 3]. The first two faces correspond to the first image, the third face for the second image, the 3rd image has 3 faces, etc.

My issue is this:

*

*In order for the --enable_batching flag to work, the output from my model needs to have the 0th dimension the same as the input. That is, I need a tensor with the following shape: (batch_size, ...). I suppose this is so that the model server can know which grpc connection to send each output in the batch towards.

*What I want to do is to convert my output tensor from the face detector from this shape (number_of_faces, 4) to this shape (batch_size, None, 4). That is, an array of batches, where each batch can have a variable number of faces (e.g. one image in the batch may have no faces, and another might have 3).

What I tried:

*

*tf.dynamic_partition. On the surface, this function looks perfect. However, I ran into difficulties after realizing that the num_partitions parameter cannot be a tensor, only an integer:
tensorflow_serving_output = tf.dynamic_partition(faces, partitions, batch_size)
If the tf.dynamic_partition function were to accept tensor values for num_partition, then it seems that my problem would be solved. However, I am back to square one since this is not the case.
Thank you all for your help! Let me know if anything is unclear
P.S. Here is a visual representation of the intended process:

A: I ended up finding a solution to this using TensorArray and tf.while_loop:
def batch_reconstructor(tensor, partitions, batch_size):
    """
    Take a tensor of shape (batch_size, 4) and a 1-D partitions tensor as well as the scalar batch_size
    And reconstruct a TensorArray that preserves the original batching

    From the partitions, we can get the maximum amount of tensors within a batch. This will inform the padding we need to use.
    Params:
        - tensor: The tensor to convert to a batch
        - partitions: A list of batch indices. The tensor at position i corresponds to batch # partitions[i]
    """
    tfarr = tf.TensorArray(tf.int32, size=batch_size, infer_shape=False)

    _, _, count = tf.unique_with_counts(partitions)
    maximum_tensor_size = tf.cast(tf.reduce_max(count), tf.int32)

    padding_tensor_index = tf.cast(tf.gather(tf.shape(tensor), 0), tf.int32)

    padding_tensor = tf.expand_dims(tf.cast(tf.fill([4], -1), tf.float32), axis=0) # fill with [-1, -1, -1, -1]
    tensor = tf.concat([tensor, padding_tensor], axis=0)

    def cond(i, acc):
        return tf.less(i, batch_size)

    def body(i, acc):
        partition_indices = tf.reshape(tf.cast(tf.where(tf.equal(partitions, i)), tf.int32), [-1])

        partition_size = tf.gather(tf.shape(partition_indices), 0)

        # concat the partition_indices with padding_size * padding_tensor_index
        padding_size = tf.subtract(maximum_tensor_size, partition_size)
        padding_indices = tf.reshape(tf.fill([padding_size], padding_tensor_index), [-1])

        partition_indices = tf.concat([partition_indices, padding_indices], axis=0)

        return (tf.add(i, 1), acc.write(i, tf.gather(tensor, partition_indices)))

    _, reconstructed = tf.while_loop(
        cond,
        body,
        (tf.constant(0), tfarr),
        name='batch_reconstructor'
    )

    reconstructed = reconstructed.stack()
    return reconstructed


text:
Q: Некорректно работает flex-shrink на андроиде Добрый вечер.
Не могу понять в чем проблема. Не совсем корректно работает свойство flex-shrink на планшете с андроид и ios, не работает только для стандартных браузеров, в хроме все ок.
В блок шириной 25% от общей ширины экрана помещена строка, а в строку три ссылки. При адаптации страницы, что бы ничего не переходило на новуюс троку или за пределы блока было использовано:

 /
 /

.style {
 overflow: hidden;
 white-space: nowrap;
 text-overflow: ellipsis;
 width: 100%;
 display: -webkit-box;
 display: -webkit-flex;
 display: -ms-flexbox;
 display: flex;
}

и на первую ссылку из строки:
.user-name {
  flex-shrink: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: inline-block;
  vertical-align: middle;
}

На вторую и третью ссылки - ничего.
На ПК, телефоне, iPad отрабатывает так, т.е. сокращает первую часть текста так, что бы влезло все остальное (текст из двух других ссылок).

А на андроид выглядит так:

т.е. оно скрывает часть первой ссылки, но вторая и третя все равно накладываются.
Надеюсь, что понятно описала. Заранее спасибо всем.


text:
Q: How to add Flutter DropdownButtonFormField Beginner Flutter enthusiast here, just learning the widget system.
Wanted to implement autocomplete textfield using out of the box widgets (not plugins ok)
The DropdownButtonFormField is perfect for my use case but when I try using it, the compiler gives me a Method not found error.
Compiler message:
lib/expanding_text.dart:100:11: Error: Method not found: 'DropdownButtonFormField'.
          DropdownButtonFormField(),
          ^^^^^^^^^^^^^^^^^^^^^^^
lib/expanding_text.dart:100:11: Error: The method 'DropdownButtonFormField' isn't defined for the class '#lib1::_TripItemState'.
Try correcting the name to the name of an existing method, or defining a method named 'DropdownButtonFormField'.
          DropdownButtonFormField(),

Heres my code (the relevant part)
import 'package:flutter/material.dart';

...

@override
  Widget build(BuildContext context) {
      return Column(
        children: <Widget>[
          DropdownButtonFormField<String>(
             items: [DropdownMenuItem<String>(child:Text("test"))],
          ),

Looking at the docs it seems like I can freely add it to the widget tree without extra configuration.  But obviously I'm missing something here because of the error.
So to troubleshoot whats happening, is DropdownButtonFormField still in the material library?
Is there anything else Im missing?

A: The widget does exist in flutter/materials.dart.
import 'package:flutter/material.dart';

...

String _selectedValue;
List<String> listOfValue = ['1', '2', '3', '4', '5'];

@override
Widget build(BuildContext context) {
return DropdownButtonFormField(
        value: _selectedValue,
        hint: Text(
               'choose one',
                ),
        isExpanded: true,
        onChanged: (value) {
                 setState(() {
                    _selectedValue = value;
                 });
               },
        onSaved: (value) {
                 setState(() {
                    _selectedValue = value;
                 });
               },
        validator: (String value) {
             if (value.isEmpty) {
                   return "can't empty";
                } else {
                   return null;
                }
              },
        items: listOfValue
           .map((String val) {
                return DropdownMenuItem(
                   value: val,
                   child: Text(
                        val,
                         ),
                       );
                    }).toList(),
                 );
}

A: The widget does exist in flutter/materials.dart.
DropdownButtonFormField requires the items property to be defined in its constructor. You need to use it like so:
import 'package:flutter/material.dart';

...

@override
Widget build(BuildContext context) {
  return Column(children: <Widget>[
    DropdownButtonFormField(
      items: <DropdownMenuItem>[
        // Put widgets in the drop down menu here
      ],
    )
  ]);
}


text:
Q: How do I suppress C++ vtable generation for pure virtual classes using G++? Supressing C++ vtable generation can be done in MSVC using the __declspec(novtable) attribute. However, it seems that there is no equivalent attribute for the GNU C++ compiler. The fact is that leaving the vtables for pure virtual classes unnecessarily links in __cxa_abort() and many others, and I want to avoid this happening because I'm programming for an embedded system. So, what should I do?
struct ISomeInterface
{
    virtual void Func() = 0;
};

class CSomeClass : public ISomeInterface
{
    virtual void Func();
}

void CSomeClass::Func()
{
    //...
}

A: There is something that will achieve a similar result:  #pragma interface.
#pragma implementation can override this, however.
http://www.emerson.emory.edu/services/gcc/html/CPP_Interface.html

A: The compiler flag -fno-rtti stops run-time type information generation.
In my experience with C++ on embedded platforms, this has prevented vtable compiler errors from occurring, suggesting it prevents them from being created (and consequentially, virtual functions won't work).


text:
Q: Postman using Slack integration to notify for 3 failures and then first success Question: How can I set up Postman with Slack integrations to notify only for failures and then first success?
I had this configured in the past, but lost it recently when a collection was accidentally deleted.
Over 2019, I created monitors with Postman through the online dashboard with Slack integrations.
I believe during the setup there was an option under "Additional Preferences" to "Notify for 3 failures and then first success".
As of 2020, this option is not available.
Other seem to have used the same functionality (Example 1, Example 2), but I cannot see evidence of it in the official documentation, and official posts refer to workarounds like this.
Is it currently possible?


text:
Q: Magento2.3 SetTemplate is not working first time ajax I would like to add additional some field info in sales_order_create_index.xml
I used setTemplate:
<referenceBlock name="data">
        <action method="setTemplate">
            <argument name="template" xsi:type="string">Custom_Custom::order/create/data.phtml</argument>
        </action>

    </referenceBlock>

If I create order from sales > order > create order > select customer > go to create order page. It still get template in core magento.
Once I reload that page or reorder, it load correct my template.
Anyone know that problem


text:
Q: how to add a stoploss in mql5 I have a code that execute trading when 2 moving average crossover happen in mt5, the problem is I do not know how to code the stoploss which is the opposite of the crossover, let say i'm in a sell position with fast moving average is crossing below slow moving average , the position is kept open until new buy moving average crossover happen, then the sell position is closed with new buy position is open. anybody can help me?
'''
#include <Trade/Trade.mqh>
CTrade trade;
int OnInit() {
Print("OnInit");
return(INIT_SUCCEEDED);
}
void OnDeinit(const int reason){
}
void OnTick(){
  static datetime timestamp;
  datetime time = iTime(_Symbol, PERIOD_CURRENT, 0);
  if(timestamp != time) {
     timestamp = time ;

  static int handleSlowMa = iMA(_Symbol,PERIOD_CURRENT, 200, 0, MODE_SMA, PRICE_CLOSE);
  double slowMaArray[];
  CopyBuffer(handleSlowMa, 0,1,2,slowMaArray);
  ArraySetAsSeries(slowMaArray, true);

  int handleFastMa = iMA(_Symbol,PERIOD_CURRENT, 20, 0, MODE_SMA, PRICE_CLOSE);
  double fastMaArray[];
  CopyBuffer(handleFastMa, 0,1,2,fastMaArray);
  ArraySetAsSeries(fastMaArray, true);

  if(fastMaArray[0] > slowMaArray[0] && fastMaArray[1] < slowMaArray[1]) {
     Print("Fast Ma is now > slow ma");
     double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
     trade.Buy(0.1,_Symbol, ask, "This is a buy" );

  }

  if(fastMaArray[0] < slowMaArray[0] && fastMaArray[1] > slowMaArray[1]) {
     Print("Fast Ma is now < slow ma");
     double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
     trade.Sell(0.1,_Symbol, bid,"This is a sell" );
  }

  Comment("\nslowMaArray[0]: ",slowMaArray[0],
          "\nSlowMaArray[1]: ",slowMaArray[1],
          "\nfastMaArray[0]: ",fastMaArray[0],
          "\nfastMaArray[1]: ",fastMaArray[1]);

}
}
'''

A: you need first to make a void for loop to find position you will make two the first is for buy and the second is for sell
CLOSE BUY ORDERS
void CloseBuy() { for(int i=PositionsTotal()-1; i>=0; i--)
  {
   ulong PosTicket = PositionGetTicket(i);
   string symbol = PositionGetSymbol(i);
   long PosDirection = PositionGetInteger(POSITION_TYPE);
   if(PosDirection == POSITION_TYPE_BUY)
   if(Symbol()==symbol)
     { MyTrade.PositionClose(PosTicket); }
  } }

CLOSE SELL ORDERS
void CloseSell() { for(int i=PositionsTotal()-1; i>=0; i--)
  {
   ulong PosTicket = PositionGetTicket(i);
   string symbol = PositionGetSymbol(i);
   long PosDirection = PositionGetInteger(POSITION_TYPE);
   if(PosDirection == POSITION_TYPE_SELL)
   if(Symbol()==symbol)
     { MyTrade.PositionClose(PosTicket); }
  } }

then you need to edit your main code at ontick function
if(fastMaArray[0] > slowMaArray[0] && fastMaArray[1] < slowMaArray[1]) {
 Print("Fast Ma is now > slow ma");
 double ask = SymbolInfoDouble(_Symbol,SYMBOL_ASK);
 trade.Buy(0.1,_Symbol, ask, "This is a buy" ); }

else if(fastMaArray[0] < slowMaArray[0] && fastMaArray[1] > slowMaArray[1])
     { CloseBuy(); }

if(fastMaArray[0] < slowMaArray[0] && fastMaArray[1] > slowMaArray[1]) {
 Print("Fast Ma is now < slow ma");
 double bid = SymbolInfoDouble(_Symbol,SYMBOL_BID);
 trade.Sell(0.1,_Symbol, bid,"This is a sell" ); }

else if(fastMaArray[0] > slowMaArray[0] && fastMaArray[1] < slowMaArray[1])
     { CloseSell(); }


text:
Q: Cannot consume private NPM package hosted on GPR I have a private repo that, using Github Actions workflow, I have published as a private npm package on Github Package Registry. I want to consume this package in the scope of another private project of mine. But there is an issue. Upon importing the GPR hosted package as a dependency I get a 'module not found' error.

*

*Github Actions workflow successfully publishes private npm package to GPR.

*The published package appears under 'Package' tab at Github user landing.

*GPR_ACCESS_TOKEN is a PAT (ensuring that I can consume the package).

IMAGE: the error in question
.npmrc file at root of project consuming private package
@slackermorris:registry=https://npm.pkg.github.com/
//npm.pkg.github.com/:_authToken=XXXX-XXXX-XXXX-XXXX

Github Action responsible for republishing private npm package to Github Registry.
name: Node.js Package

on:

  push:

    branches:

      - master

  release:

    types: [created]

jobs:

  build:

    runs-on: ubuntu-latest

    steps:

      - uses: actions/checkout@v2

      - uses: actions/setup-node@v1

        with:

          node-version: 12

      - run: npm ci

      - run: npm test

        env:

          CI: true

  publish-gpr:

    needs: build

    runs-on: ubuntu-latest

    steps:

      - uses: actions/checkout@v2

      - uses: actions/setup-node@v1

        with:

          node-version: 12

          registry-url: https://npm.pkg.github.com

          scope: slackermorris

      - run: npm ci

      - run: npm publish

        env:

          NODE_AUTH_TOKEN: ${{secrets.GPR_ACCESS_TOKEN}}

package.json of the published npm package.
"name": "@slackermorris/bostock-metaball-animation",

  "version": "1.0.3",

  "main": "index.js",

  "author": "slackermorris",

  "license": "MIT",

  "publishConfig": {

    "registry": "https://npm.pkg.github.com"

  } ...

A: What you are trying should work, but I can confirm it does not. Better than putting your token in .npmrc is storing your Personal Access Token in a repo secret that is exported by the workflow. IE, create a repo secret named GPR_AUTH_TOKEN with the contents of your PAT. Then add this to your workflow:
env:
  GPR_AUTH_TOKEN: ${{ secrets.GPR_AUTH_TOKEN }}

Then have your .npmrc load the token via the env variable:
//npm.pkg.github.com/:_authToken=${GPR_AUTH_TOKEN}

That avoids exposing your PAT to everyone with repo access.
That solution works for me on node.js v16 but it doesn't work with node 14.
What works for every LTS version of Node.js is to configure .npmrc with this npm step in your workflow:
  - name: Configure NPM
    run: npm config set '//npm.pkg.github.com/:_authToken' "${{secrets.GPR_AUTH_TOKEN}}"

After that, the npm install works as expected.


text:
Q: robots.txt file for multi language website hi I'm trying to generate a robots.txt file for my website but I'm having an issue dealing with multi language URL.
I want to disallow this URL for instance
http://www.example.com/en/shop
http://www.example.com/ar/shop
http://www.example.com/fr/shop

so do I have to write
Disallow: /en/shop
Disallow: /ar/shop
Disallow: /fr/shop

or this is enough ?
Disallow: /*/shop

thank you


text:
Q: why is realm.classToTable count 0 when I get instance of realm object in Android I have created my own realm db and I set configuration to  new RealmConfiguration.Builder(this).name("mydb.realm").build();
realm = Realm.getInstance(realmConfiguration);
The classToTable count is 0 and count of rows in the table is also 0. Can someone let me know what am I missing. Thanks.

A: Did you created your models as subsclasses of RealmObject?
Follow sample to create some records in db:
Realm realm = Realm.getInstance(context);

// Define model
public class Dog extends RealmObject {
    private String name;
    private int age;

    // ... Generated getters and setters ...
}

// Create object
Dog dog = new Dog();
dog.setName("Rex");
dog.setAge("1");

// Persist
realm.beginTransaction();
realm.copyToRealm(dog);
realm.commitTransaction();


text:
Q: Choosing a Pivot in QuickSort I was reading about QuickSort and it appears that ideally, they used randomized algorithm for choosing a pivot with at least 25-75 split of the array.
Why can't they calculate the median value of the array and choose the most nearest value to median in every recursive call?
I think it would take the same amount of running time or maybe even better than randomized approach.

A: Because calculating median value takes at least linear time (in comparison to constant time required for random selection), and it's no trivial in linear time. So even though asymptotical performance becomes guaranteed, wall clock performance decreases. I believe it's more practical to guarantee performance in other ways, e.g. by using Introsort.

A: Using median of medians, a near median can be chosen, but the overhead is significant, effectively sorting groups of 5. Wiki article:
https://en.wikipedia.org/wiki/Median_of_medians
Note that median of medians can be implemented in place.
As for a random pivot, the code to calculate a random index takes a significant amount of the time during a partition step.
A simpler approach is to use the median of first, middle, last, to avoid worst case time for already sorted or reverse sorted data, and as answered by yeputons, using introsort which switches to heap sort (based on level of recursion) to avoid worst case time.


text:
Q: bash, getting the mime type of a file handle How would i get the mime type of a file-handle without saving it to disk?
What i mean is a file that is not saved to disk, rather: i extracted it from an archive and plan on piping it to another script.
Say i extracted the file like this:
tar -xOzf images.tar.gz images/logo.jpg | myscript

Now inside myscript I would like to check the mime type of the file before further processing it. How would it go about this?

A: as some people think my comment above is helpful i post it as an answer.
the file-command is able to determine a file's mime type on the fly/when being piped. It ist able to read a file from stdin - printing the file's --mime-type briefly/in a short manner when passing -b. Considering your example you probably want to extract a single file from an archive and dertermine its file/mime type.
$ tar -xOzf foo.tar.gz file_in_archive.txt | file -b --mime-type -
text/plain

so for a simple text file extracted from an archive to stdout it could look like the example above. hope that helped. regards


text:
Q: jQuery UI datepicker & dialog sends data to # when a date is selected jQuery UI datepicker y dialog
When a date is selcted in a datepicker that is in a dialog, the data is sent to #.  When a date is selected, only the text should be selected and the data should not be sent until the submit is clicked.
Is there a solution to this?

A: Look at this. It may be by the same reason and the solution can help you:

*

*jquery ui datepicker IE reload or jumps to the top of the page


text:
Q: Can point of inflection occur at a point where second derivative doesnot exist? I refered these questions
Definition of Point of Inflection
An inflection point where the second derivative doesn't exist?
What is inflection point?
 I couldnt understand the necessary conditions for point of inflection.My specific doubt is
  Can point of inflection occur at a point where the second derivative of a function is discontinuous?
In the image attached, the curves of the actual function, its second derivative and third derivative are given(from left to right correspondingly) Can the point x=b be an inflection point for the function.

A: The short answer is "yes."  An inflection point is a point where the tangent line crosses the graph of the function.  So if the tangent line is vertical at a point, then the first derivative doesn't exist and therefore the second doesn't exist.
Take $y=\sqrt[3]{x}$.  Then $(0,0)$ is an inflection point, but the second derivative is discontinuous there.


text:
Q: Question on a result of Artin and Tate This is a result of Artin and Tate found in Serge Lang's Algebra. (Page 166.)

Let $G$ be a finite group operating on a set $S$. For $w\in S$, denote $1\cdot w$ by $[w]$, so that we have the direct sum
  $$
\mathbb{Z}\langle S\rangle=\sum_{w\in S}\mathbb{Z}[w].
$$
  Define an action of $G$ on $\mathbb{Z}\langle S\rangle$ by defining $\sigma[w]=[\sigma w]$, and extending $\sigma$ to $\mathbb{Z}\langle S\rangle$ by linearity. Let $M$ be a subgroup of $\mathbb{Z}\langle S\rangle$ of rank $\#(S)$. Show that $M$ has a $\mathbb{Z}$-basis $\{y_w\}_{w\in S}$ such that $\sigma y_w=y_{\sigma w}$ for all $w\in S$.

I know this is an adaptation of a result in Artin and Tate's notes on Class Field Theory. I found proofs of similar ideas in Lang's Algebraic Number Theory (Theorem 1 of page 190), and in Nancy Childress's book here.
I tried reading through the proofs and the relevant lemmas, but have had difficulty deciphering them and putting them in the context of Lang's statement. Is there perhaps a dumbed down proof of the above statement more suited to using knowledge of basic groups, rings, and modules? Thanks.

A: I must be badly misunderstanding the statement, since the way I read it, it is completely wrong. It seems to be saying that every full rank subgroup of a permutation module over $\mathbb{Z}$ is itself isomorphic to a permutation module, which is not true.
Firstly, not every full rank subgroup is even a submodule in the first place. Examples abound: e.g. take the regular action of $G$ on itself (so $S=G$) and consider the submodule of $\mathbb{Z}[G]$ given by $\{\sum_{g\in G}a_g g: a_g\in \mathbb{Z}, a_1\in 2\mathbb{Z}\}$. This is a subgroup, but is certainly not preserved by the regular $G$-action.
Secondly, not every submodule is a permutation module. E.g. take $G=C_2$, the cyclic group of order 2, and consider the regular action. One can visualise the module $\mathbb{Z}[G]$ as a rectangular lattice on which the non-trivial element $g$ of $G$ acts by reflection in a diagonal (the obvious basis consists of $[1]$ and $[g]$). Now, consider the submodule spanned by $[1]+[g]$ and $[1]-[g]$. This is a direct sum of two one-dimensional modules over $\mathbb{Z}$, and is therefore not isomorphic to the original module, which is in contradiction to what the statement is claiming.
Edit: Ok, I had a look at the reference in Lang's Algebraic Number Theory, and there he does give a correct version of this statement: every $G$-stable full rank sublattice of a real permutation module has a full rank submodule isomorphic to a permutation module. But that's not at all what the present exercise is saying.


text:
Q: Standard terminology for the "quotient of a quotient" Let $n$ and $m$ be integers.  One can write
$$
n = mq_0 + r_0
$$ where $0\leq r_0 < m$; the $q_0$ term in the right-hand side is the "quotient". One could then write
$$
q_0 = mq_1 + r_1
$$ where $0\leq r_1 < m$.  What is the standard terminology for the $q_1$  term (the "quotient of the quotient")?  Proceeding inductively, if we define
$$
q_i = mq_{i+1} + r_i
$$ where $0\leq r_i < m$ for all $i\geq 0$, then what is the terminology for the terms $q_0,q_1,q_2,\ldots,$?
I am $not$ applying the Euclidean algorithm here.

A: It's the algorithm to write the digits of the number n in the numbersystem with base m I think. The $r_k$ are then the digits, but I do not know a name for the $q_k$. $q_0 = \lfloor n / m \rfloor$ ,$q_1 = \lfloor q_0 / m \rfloor$ ...
Example: if $m=10$ One could ask: if $n=1234321$ what is the name for the part $q_0=123432$ ? or for the part $q_2=1234$?
It's not exactly "the leading digits", the best I could name it were " $q_k$ is the floor-function of $n / m^{k+1}$ "

A: I don't think that
there is any standard term.
These are the quotients
in the Euclidean algorithm.
You might see terms such as
"first quotient",
"n-th quotient",
or
"final quotient",
but I think that
is about it.


text:
Q: Force QWidget Child to have its own Window Handle I am trying to create a small application using Qt. What I want to do is to display in a dock widget a 3D Interface using DirectX11, other widgets in the QMainWindow will have properties to modify the behavior of what is been displayed in DX11.
The problem I am facing is that when I add a QDockWidget to QMainWindow, the dockWidgetContents function windowHandle returns NULL.
I am using an example from Get HWND on windows with Qt5 (from WId) to get the HWND. But if the function return NULL it will go up and get the HWND of the QMainWindow.
Is there any way to force a QWidget to have its own window handle?
Thanks for any advice!

A: Yes. You have several options for that. See the topic Native Widgets vs Alien Widgets in the QWidget class documentation.

*

*Use the QT_USE_NATIVE_WINDOWS=1 in your environment.

*Set the Qt::AA_NativeWindows attribute on your application. All widgets will be native widgets.

*Set the Qt::WA_NativeWindow attribute on widgets: The widget itself and all of its ancestors will become native (unless Qt::WA_DontCreateNativeAncestors is set).

*Call QWidget::winId to enforce a native window (this implies 3).

*Set the Qt::WA_PaintOnScreen attribute to enforce a native window (this implies 3).


text:
Q: R plot legend with transparent background How to R plot legend with transparent background when using plot() function ?

A: Use: bg="transparent" in
legend()

Such as:
legend("right",bg="transparent",col=c(as.numeric(unique(df$group2))),cex=0.5)


text:
Q: Add tag before and after line in text file using php I have text file with  lines:
text1
text2
text3

I need to adding tag before and after text
output

text1

text2

text3

I'm using this script
$file = file_get_contents("test.txt");
$handle = fopen($file);
$output = '';
while (($line = fgets($handle)) !== false)     {
$output .= '
' . $line .'
' . "\n";
}
fclose($handle);
file_put_contents($output, $file);

I got this error:

Warning: fopen() expects at least 2     parameters, 1 given in on line 4
      Warning: fgets() expects parameter 1 to be resource, boolean given on line 7
      Warning: fclose() expects parameter 1 to be resource, boolean given in  line 10
      Warning: file_put_contents(): Filename cannot be empty in  line 11

A: In fopen(); function there is a parameter mode, that specifies the type of access you require to the stream, due to this you are getting warnings.. read more about f_open().
Here i have two methods for you to write in file
Method 1 : Using file_get_contents() and file_put_contents()
$file = 'test.txt';
// Open the file to get existing content
$current = file_get_contents($file);
$rows = explode("\n", $current);
$output= '';
foreach($rows  as $row)
{
    $output .= '
'.$row.'
'. "\n";
}
file_put_contents($file, $output);

Method :2 Is that your are trying to use
$file = 'test.txt';
$current = file_get_contents($file);
$handle = fopen($file,'r');
$output = '';
while (($line = fgets($handle)) !== false)
{
    $output .= '
'. $line .'
'."\n";
}
fclose($handle);
file_put_contents($file, $output);


text:
Q: RSpec + FactoryGirl should_receive failing I can't figure out why this RSpec test fails. Any advice? I'm new-ish to FactoryGirl, RSpec, and TDD in general.
Controller:
def update
  @vendor = current_user.vendors.find(params[:id])

  if @vendor.update_attributes(params[:vendor])
    redirect_to vendor_path(@vendor)
  else
    render 'edit'
  end
end

Test:
require 'spec_helper'

describe VendorsController do
  login_user

  before :each do
    @user = subject.current_user
    @vendor = FactoryGirl.create(:vendor, :user => @user)
  end

  [...]

  describe 'POST update' do
    def do_update
      post :update, :id => @vendor.id, :vendor => FactoryGirl.attributes_for(:vendor)
    end

    [...]

    it 'should update a given vendor' do
      do_update
      @vendor.should_receive(:update_attributes).with(FactoryGirl.attributes_for(:vendor))
    end
  end
end

Factory:
FactoryGirl.define do
  factory :vendor do
    name 'Widget Vendor'
    user
  end
end

The Failure:
Failures:

  1) VendorsController POST update should update a given vendor
     Failure/Error: @vendor.should_receive(:update_attributes).with(FactoryGirl.attributes_for(:vendor))
       (#<Vendor:0x007faeb75e77d0>).update_attributes({:name=>"Widget Vendor"})
           expected: 1 time
           received: 0 times
     # ./spec/controllers/vendors_controller_spec.rb:108:in `block (3 levels) in <top (required)>'

Update:
I'm a little closer, now. I changed the test to the following:
it 'should update a given vendor' do
  Vendor.any_instance.should_receive(:update_attributes).with(FactoryGirl.attributes_for(:vendor))
  do_update
end

And the new error is:
Failures:

  1) VendorsController POST update should update a given vendor
     Failure/Error: post :update, :id => @vendor.id, :vendor => FactoryGirl.attributes_for(:vendor)
       #<Vendor:0x007ff30d765900> received :update_attributes with unexpected arguments
         expected: ({:name=>"Widget Vendor"})
              got: ({"name"=>"Widget Vendor"})
     # ./app/controllers/vendors_controller.rb:33:in `update'
     # ./spec/controllers/vendors_controller_spec.rb:98:in `do_update'
     # ./spec/controllers/vendors_controller_spec.rb:108:in `block (3 levels) in <top (required)>'

Answer...?
Well, this worked. There has to be a better way of doing this, though:
Vendor.any_instance.should_receive(:update_attributes).with(JSON.parse(FactoryGirl.attributes_for(:vendor).to_json)).and_return(true)

A: I think you are doing it wrong.
The @vendor object in specs is another one that in your controller, so it doesn't receive "update_attributes" method.
You can try this (rspec 2.5+ probably):
Vendor.any_instance.should_receive(:update_attributes).with(FactoryGirl.attributes_for(:vendor))

Or you can check if object attributes has changed:
expect{
  do_update
}.to change(...)

A: I believe you need to set your expectations before posting the request; otherwise, by the time it hits your expectation the object has already been set. So move do_update after your should_receive line:
it 'should update a given vendor' do
  @vendor.should_receive(:update_attributes).with(FactoryGirl.attributes_for(:vendor))
  do_update
end

A: You can use the Hash stringify keys method in rails:
Vendor.any_instance.should_receive(:update_attributes).with(FactoryGirl.attributes_for(:vendor).stringify_keys)


text:
Q: Is throw by value and catch by reference the law of thumb? I am so confused and fed up with C++: As I have been taught "passing by reference or pointer" overcomes getting copies of parameters passed in a function.
So in an exception-handling scenario according to the law of thumb: throw by value, catch by reference.
Why Stroustrup in his "A Tour of C++" catches by value? eg:
void test()
{
    try {
        std::vector v(−27);
    }
    catch (std::length_error) {
        // handle negative size
    }
    catch (std::bad_alloc) {
        // handle memory exhaustion
    }
}

This example is copied from the book. Page 59. (Invariants).

A:
Why Stroustrup in his "A Tour of C++" catches by value?

Unless you want to copy the exception for some reason (e.g. store a custom exception type), you should always catch by const&. This might have been an oversight from Bjarne, or in that particular snippet it didn't really matter whether or not the exception was copied.
Related:

*

*"Always catch exceptions by reference"

*C++ catch blocks - catch exception by value or reference?

Why C++ is changing inconsistently? I mean from time to time everything changes. eg: in C++ 11:

There is no inconsistency here - static_assert merely became more flexible, as it doesn't force the user to provide an error message anymore. This is useful for cases where the boolean condition itself is self-explanatory and an error message would not add anything useful.


text:
Q: Sort array/list in Perl using comma or dot for string concatenation I have:
#!c:\Dwimperl\perl\bin\perl.exe

use strict;
use warnings;

# Define an array
my @letters = ('b', 'c', 'a', 'e', 'd');
print sort @letters , "\n";

Outputs: abcdePress any key to continue . . .
Why isn't there any line return?
I then tried using the period concatenation operator:
#!c:\Dwimperl\perl\bin\perl.exe

use strict;
use warnings;

# Define an array
my @letters = ('b', 'c', 'a', 'e', 'd');
print sort @letters . "\n";

Output: 5
Press any key to continue . . .
Why does the \n work here, but return the array length?
Any references to official documentation would help.

A: When you do
print sort @letters . "\n";

you are really evaluating @letters in a scalar context and appending a newline, and then sorting that array. Since the array is of length 5, you get the number 5.
Try it like this:
my @letters = ('b', 'c', 'a', 'e', 'd');
print sort(@letters . "\ntest");

And you'll output:
5
test

The behavior of sort is undefined in scalar context. So you cannot do:
my @letters = ('b', 'c', 'a', 'e', 'd');
print sort(@letters) . "\n";
# This doesn't produce any output

You probably want to do something like this:
my @letters = ('b', 'c', 'a', 'e', 'd');
print join(",", sort(@letters)) . "\n";

Output:
a,b,c,d,e

For the first scenario, you are appending \n to the list of letters, and then sorting it. So it ends up at the beginning. Here's an example:
my @letters = ('b', 'c', 'a', 'e', 'd');
print sort @letters , "\n", 1, 2, 3;

Outputs:
# It outputs a newline and then the characters:

123abcde

In general, it is useful to use parentheses to clear on what behavior you want to get.
my @letters = ('b', 'c', 'a', 'e', 'd');
print sort(@letters), "\ntest";

Outputs:
abcde
test


text:
Q: Proving $SAS$ provided other congruence criteria In his book Elementary Geometry from an Advanced Standpoint, E. E. Moise states the SAS congruence criterion as a postulate and prove ASA and SSS with it.
If one introduces ASA or SSS as a postulate (without stating SAS as a postulate), SAS can be proved as a theorem?


text:
Q: Store translation in a database? I have some categories for product.
As these categories can change or grow I think I'll store them in a database in order to manage them through an admin interface.
However, these categories must be translated in another language. (en/fr/maybe other...)
In that way, I would like to know your thought on this:

*

*Is it better to set these categories in the Category model (in an array) and translate it through a yml file

*Did I have to set up a catagory database with locale columns, for example like this:
id (category id) | en (english translation) | fr (french translation) | etc...

*Or Is there a better way to do this?

A: See http://guides.rubyonrails.org/i18n.html
What I suggest is if you're translating content that belongs to the model (e.g. attribute names) and that you will control if/when they change, go with a YAML file per locale.
For dynamic content, use a database.
As show in section 6.1 "Different backends" at http://guides.rubyonrails.org/i18n.html#using-different-backends you can mix both strategies : look for the translation in the database and if it isn't found, fall back onto the YAML files.


text:
Q: Need jsp form to submit query to specific path I'm trying to setup a simple form in a jsp that will put a search query in the URL submitted.
This is what I have so far:
<form action="search/" method="get" onsubmit="this.action+=this.q.value.trim();return true">
   <input type="text" id="q">
   <input type="submit" value="go">
</form>

This is in a jsp that's included on each page of my web app and it works when I'm at the root of the app. For example, if I initially load "http://localhost:8080/MyApp/" then type "123456" in the search form, it takes me to "http://localhost:8080/MyApp/search/123456", which is what I want. However, from that page, if I search again (for "654321" for example) it goes to "http://localhost:8080/MyApp/search/search/654321", which doesn't work for me. I need search/{query} to be appended to the root of the app's path no matter what page I may be on at the time.
I would like to avoid javascript if possible, I'm fine with JSTL though.
Any suggestions would be much appreciated!

A: Simply add a full path to your action, start it with /. Note it will depend on your application context, you could use :
<form action="${pageContext.request.contextPath}/search/"...

It will work in dev and also prod.
EDIT :
Path : search will try to load relative from current path so : http://domain.com/contact/search/
Path : /search will try to load relative from the domain so : http://domain.com/
With the context path above, it will work no matter if it change from dev to prod.
Hope this helps!


text:
Q: TypeOrm OneToOne relation causing unwanted embedding of columns I have 2 entities that have a OneToOne relation (User and CodUser) and where User has the JoinColumn. When TypeOrm syncs this pattern to the database it create the CodUser columns within the user, so it embeds the CodUser AND creates a separate table for the CodUser entity.
What I want is that the 2 entities are separate and the columns in the CodUser only appear in the CodUser table in my (Postgres) database.
I believe this is the exact pattern used by TypeOrm to demonstrate OneToOne relations but there seems to be something off.
user.entity.ts
@Entity()
export class User {
@PrimaryGeneratedColumn()
id: number;

@Column({ unique: true })
email: string;

@Column({ nullable: true })
avatar: string;

@Column()
password: string;

@Column({
    type: "text",
    array: true,
    nullable: false,
    default: `{${Role.Player}}`
})
roles: Role[];

@OneToOne((type) => CodUser, {
    cascade: true
})
@JoinColumn()
codUser: CodUser;

@Column({ default: 0 })
invalidLoginAttempts: number;

@Column({ nullable: true })
activationCode: string;

@Column({ nullable: false, default: false })
active: boolean;

@Column({ nullable: true })
lockedUntil: Date;

@Column({ nullable: true })
lastLoginAttemptAt: Date;

@OneToMany((type) => ChallangeUser, (challangeUser) => challangeUser.user)
challanges: ChallangeUser[];

@CreateDateColumn({ type: "timestamp" })
createdAt: Date;

@UpdateDateColumn({ type: "timestamp" })
updatedAt: Date;

constructor(email: string, username: string, platform: Platform, password: string) {
    this.email = email;
    this.codUser = new CodUser(username, platform);
    this.password = password;
}
}

cod-user.entity.ts
@Entity()
export class CodUser {
@PrimaryGeneratedColumn()
id: string;

@Column({ unique: true })
username: string;

@Column({ nullable: false })
platform: Platform;

@Column({ type: "jsonb", nullable: true })
recentWarzoneMatches: object[];

@Column({ nullable: true })
recentWarzoneMatchesSyncedAt: Date;

constructor(username: string, platform: Platform) {
    this.username = username;
    this.platform = platform;
}
}

Result:

Transaction while syncing:
query: START TRANSACTION
query: SELECT * FROM current_schema()
query: SELECT * FROM "information_schema"."tables" WHERE ("table_schema" = 'public' AND "table_name" = 'challange') OR ("table_schema" = 'public' AND "table_name" = 'challange_user') OR ("table_schema" = 'public' AND "table_name" = 'cod_user') OR ("table_schema" = 'public' AND "table_name" = 'user') OR ("table_schema" = 'public' AND "table_name" = 'user') OR ("table_schema" = 'public' AND "table_name" = 'challange') OR ("table_schema" = 'public' AND "table_name" = 'challange_user')
query: SELECT *, ('"' || "udt_schema" || '"."' || "udt_name" || '"')::"regtype" AS "regtype" FROM "information_schema"."columns" WHERE ("table_schema" = 'public' AND "table_name" = 'challange') OR ("table_schema" = 'public' AND "table_name" = 'challange_user') OR ("table_schema" = 'public' AND "table_name" =
'cod_user') OR ("table_schema" = 'public' AND "table_name" = 'user') OR ("table_schema" = 'public' AND "table_name" = 'user') OR ("table_schema" = 'public' AND "table_name" = 'challange') OR ("table_schema" = 'public' AND "table_name" = 'challange_user')
query: SELECT "ns"."nspname" AS "table_schema", "t"."relname" AS "table_name", "cnst"."conname" AS "constraint_name", pg_get_constraintdef("cnst"."oid") AS "expression", CASE "cnst"."contype" WHEN 'p' THEN 'PRIMARY' WHEN 'u' THEN 'UNIQUE' WHEN 'c' THEN 'CHECK' WHEN 'x' THEN 'EXCLUDE' END AS "constraint_type", "a"."attname" AS "column_name" FROM "pg_constraint" "cnst" INNER JOIN "pg_class" "t" ON "t"."oid" = "cnst"."conrelid" INNER JOIN "pg_namespace" "ns" ON "ns"."oid" = "cnst"."connamespace" LEFT JOIN "pg_attribute" "a" ON "a"."attrelid" = "cnst"."conrelid" AND "a"."attnum" = ANY ("cnst"."conkey") WHERE "t"."relkind" = 'r' AND (("ns"."nspname" = 'public' AND "t"."relname" = 'challange') OR ("ns"."nspname" = 'public' AND "t"."relname" = 'challange_user') OR ("ns"."nspname" = 'public' AND "t"."relname" = 'cod_user') OR ("ns"."nspname" = 'public' AND "t"."relname" = 'user') OR ("ns"."nspname" = 'public' AND "t"."relname" = 'user') OR ("ns"."nspname" = 'public' AND "t"."relname" = 'challange') OR ("ns"."nspname" = 'public' AND "t"."relname" = 'challange_user'))
query: SELECT "ns"."nspname" AS "table_schema", "t"."relname" AS "table_name", "i"."relname" AS "constraint_name", "a"."attname" AS "column_name", CASE "ix"."indisunique" WHEN 't' THEN 'TRUE' ELSE'FALSE' END AS "is_unique", pg_get_expr("ix"."indpred", "ix"."indrelid") AS "condition", "types"."typname" AS "type_name" FROM "pg_class" "t" INNER JOIN "pg_index" "ix" ON "ix"."indrelid" = "t"."oid" INNER JOIN "pg_attribute" "a" ON "a"."attrelid" = "t"."oid"  AND "a"."attnum" = ANY ("ix"."indkey") INNER JOIN "pg_namespace" "ns" ON "ns"."oid" = "t"."relnamespace" INNER JOIN "pg_class" "i" ON "i"."oid" = "ix"."indexrelid" INNER JOIN "pg_type" "types" ON "types"."oid" = "a"."atttypid" LEFT JOIN "pg_constraint" "cnst" ON "cnst"."conname" = "i"."relname" WHERE "t"."relkind" = 'r' AND "cnst"."contype" IS NULL AND (("ns"."nspname" = 'public' AND "t"."relname" = 'challange') OR ("ns"."nspname" = 'public' AND "t"."relname" = 'challange_user') OR ("ns"."nspname" = 'public' AND "t"."relname" = 'cod_user') OR ("ns"."nspname" = 'public' AND "t"."relname" = 'user') OR ("ns"."nspname" = 'public' AND "t"."relname" = 'user') OR ("ns"."nspname" = 'public' AND "t"."relname" = 'challange') OR ("ns"."nspname" = 'public' AND "t"."relname" = 'challange_user'))
query: SELECT "con"."conname" AS "constraint_name", "con"."nspname" AS "table_schema", "con"."relname" AS "table_name", "att2"."attname" AS "column_name", "ns"."nspname" AS "referenced_table_schema", "cl"."relname" AS "referenced_table_name", "att"."attname" AS "referenced_column_name", "con"."confdeltype" AS "on_delete", "con"."confupdtype" AS "on_update", "con"."condeferrable" AS "deferrable", "con"."condeferred" AS "deferred" FROM ( SELECT UNNEST ("con1"."conkey") AS "parent", UNNEST ("con1"."confkey") AS "child", "con1"."confrelid", "con1"."conrelid", "con1"."conname", "con1"."contype", "ns"."nspname", "cl"."relname", "con1"."condeferrable", CASE WHEN "con1"."condeferred" THEN 'INITIALLY DEFERRED' ELSE 'INITIALLY IMMEDIATE' END as condeferred, CASE "con1"."confdeltype" WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END as "confdeltype", CASE "con1"."confupdtype" WHEN 'a' THEN 'NO ACTION' WHEN 'r' THEN 'RESTRICT' WHEN 'c' THEN 'CASCADE' WHEN 'n' THEN 'SET NULL' WHEN 'd' THEN 'SET DEFAULT' END as "confupdtype" FROM "pg_class" "cl" INNER JOIN "pg_namespace" "ns" ON "cl"."relnamespace" = "ns"."oid" INNER JOIN "pg_constraint" "con1" ON "con1"."conrelid" = "cl"."oid" WHERE "con1"."contype" = 'f' AND (("ns"."nspname" = 'public' AND "cl"."relname" = 'challange') OR ("ns"."nspname" = 'public' AND "cl"."relname" = 'challange_user') OR ("ns"."nspname" = 'public' AND "cl"."relname" = 'cod_user') OR ("ns"."nspname" = 'public' AND "cl"."relname" = 'user') OR ("ns"."nspname" = 'public' AND "cl"."relname" = 'user') OR ("ns"."nspname" = 'public' AND "cl"."relname" = 'challange') OR ("ns"."nspname" = 'public' AND "cl"."relname" = 'challange_user')) ) "con" INNER JOIN "pg_attribute" "att" ON "att"."attrelid" = "con"."confrelid" AND "att"."attnum" = "con"."child" INNER JOIN "pg_class" "cl" ON "cl"."oid" = "con"."confrelid" INNER JOIN "pg_namespace" "ns" ON "cl"."relnamespace" = "ns"."oid" INNER JOIN "pg_attribute" "att2" ON "att2"."attrelid" = "con"."conrelid" AND "att2"."attnum" = "con"."parent"
query: SELECT * FROM "information_schema"."tables" WHERE "table_schema" = current_schema() AND "table_name" = 'typeorm_metadata'
query: ALTER TABLE "user" DROP CONSTRAINT "FK_c8521799e9a87cab5983c57ba1c"
query: ALTER TABLE "challange_user" DROP CONSTRAINT "FK_0c9f41f81c2f9cadd1154c90499"
query: ALTER TABLE "challange" DROP COLUMN "userLimit"
query: ALTER TABLE "user" DROP CONSTRAINT "UQ_c8521799e9a87cab5983c57ba1c"
query: ALTER TABLE "user" DROP COLUMN "custom_cod_user"
query: ALTER TABLE "user" DROP CONSTRAINT "UQ_78a916df40e02a9deb1c4b75edb"
query: ALTER TABLE "user" DROP COLUMN "username"
query: ALTER TABLE "user" DROP COLUMN "platform"
query: ALTER TABLE "user" DROP COLUMN "recentWarzoneMatches"
query: ALTER TABLE "user" DROP COLUMN "recentWarzoneMatchesSyncedAt"
query: ALTER TABLE "user" DROP COLUMN "roles"
query: ALTER TABLE "challange" DROP COLUMN "slots"
query: ALTER TABLE "challange_user" DROP COLUMN "isConfirmed"
query: ALTER TABLE "challange_user" DROP COLUMN "challangeId"
query: ALTER TABLE "challange" ADD "slots" integer NOT NULL DEFAULT -1
query: ALTER TABLE "challange_user" ADD "isConfirmed" boolean NOT NULL DEFAULT false
query: ALTER TABLE "challange_user" ADD "challangeId" uuid
query: ALTER TABLE "user" ADD "roles" text array NOT NULL DEFAULT '{player}'::text[]
query: ALTER TABLE "user" ADD "codUserId" integer
query: ALTER TABLE "user" ADD CONSTRAINT "UQ_4ee803ddc575ea07a96a0aa5f40" UNIQUE ("codUserId")
query: ALTER TABLE "user" ADD "username" character varying NOT NULL
query: ALTER TABLE "user" ADD CONSTRAINT "UQ_78a916df40e02a9deb1c4b75edb" UNIQUE ("username")
query: ALTER TABLE "user" ADD "platform" character varying NOT NULL
query: ALTER TABLE "user" ADD "recentWarzoneMatches" jsonb
query: ALTER TABLE "user" ADD "recentWarzoneMatchesSyncedAt" TIMESTAMP
query: ALTER TABLE "challange" ADD "userLimit" integer NOT NULL DEFAULT -1
query: ALTER TABLE "challange_user" ADD CONSTRAINT "FK_0c9f41f81c2f9cadd1154c90499" FOREIGN KEY ("challangeId") REFERENCES "challange"("id") ON DELETE NO ACTION ON UPDATE NO ACTION
query: ALTER TABLE "user" ADD CONSTRAINT "FK_4ee803ddc575ea07a96a0aa5f40" FOREIGN KEY ("codUserId") REFERENCES "cod_user"("id") ON DELETE NO ACTION ON UPDATE NO ACTION
query: COMMIT

A: Removing the /dist folder in my NestJS project resolved the issue, seems like it was a NestJS issue after all.


text:
Q: Uncaught type error: mychart.update is not a function I am building external buttons to toggle the visibility of data from chartjs, but it will only works when the screen size changed. So, I found that can use mychart.update() to solve the problem. But it get me the error that I stated in the title.
Here is my chart:
var myRadarChart = {
    type: 'radar',
    data: {
            labels: lbl,
            datasets: [
                {
                    label: 'Houses',
                    data: yh,
                    backgroundColor:['rgba(0, 123, 255, 0.5)'],
                    borderColor: ['rgba(0, 123, 255, 0.8)'],
                    hidden:false
                },
                {
                    label: 'Apartments',
                    data: ya,
                    backgroundColor:['rgba(40,167,69, 0.5)'],
                    borderColor: ['rgba(40,167,69, 0.8)'],
                    hidden:false
                },
                {
                    label: 'Rooms',
                    data: yr,
                    backgroundColor:['rgba(218, 17, 61,0.5)'],
                    borderColor: ['rgba(218,17,61,0.8)'],
                    hidden:false
                }
            ]

        },
    options: {
        legend:{
            display:true,
            onHover: function(event, legendItem) {
            document.getElementById("myRadarChart").style.cursor = 'pointer';},
        },
        maintainAspectRatio:false,
        scale: {
            angleLines: {
                display: true
                },
            ticks: {
                suggestedMin: 0,
                suggestedMax: 0
                }
            }
        }
    };
var ctx = document.getElementById('myRadarChart').getContext('2d');
new Chart(ctx, myRadarChart);

And how I trying to do is:
//Onclick
function getData(dontHide){
switch(dontHide){
        case 0:
            myRadarChart.data.datasets[0].hidden=false;
            myRadarChart.data.datasets[1].hidden=true;
            myRadarChart.data.datasets[2].hidden=true;
            myRadarChart.update();
            break;
        case 1:
            myRadarChart.data.datasets[0].hidden=true;
            myRadarChart.data.datasets[1].hidden=false;
            myRadarChart.data.datasets[2].hidden=true;
            myRadarChart.update();
            break;
        case 2:
            myRadarChart.data.datasets[0].hidden=true;
            myRadarChart.data.datasets[1].hidden=true;
            myRadarChart.data.datasets[2].hidden=false;
            myRadarChart.update();
            break;
    }
}

Or is there alternative ways to perform something like this?

A: Your issue is that you're trying to call the .update() method on your graph's config object, not your actual graph instance. As you can see, myRadarChart is just an object, it doesn't have a method called update() on it. However, the graph you create when doing new Chart(ctx, myRadarChart); does give you the .update() method.
To fix your issue, you'll need to first store the instance of your graph somewhere:
var radarGraph = new Chart(ctx, myRadarChart);

Then update the graph's data (rather than your config object directly):
radarGraph.data.datasets[0].hidden = false;
...

Then call the update method on your radarGraph object:
radarGraph.update();


text:
Q: Boolean Logic - Can B'(AD)' + A'C'D + AC be simplified any further? I think I hit a point where I am stuck.
Can B'(AD)' + A'C'D + AC any further?
Let's say it is simplified enough - I want to get rid of the addition via deMorgan's law. Is it okay to have the same variables twice? Using A'B' = (A+B)' law and (AB)' = A' + B' law.
I feel like it would get messy, but I want to get rid of the addition (OR operator)

A: If your goal is to simplify program logic, then maybe a binary decision diagram (BDD) for this function can help you. Here it is (using the optimal variable ordering):


text:
Q: Greatest common divisor 2
Find all integers m such that $0 < m < 1008$ and $\gcd(m, 2016-m) = 1$.

The following is my solution:
Note that $1 = \gcd(m, 2016-m) = \gcd(m, 2016)$.
Since $2016$ is even and divisible by $3, 7, 9, 21, 63$ and $\gcd(m, 2016) = 1$, so $m$ is odd and $m\neq 3k, 7l$, where $k, l\in \mathbb Z,$ and $k, l$ are odd numbers.
Since $0 < m< 1008,$ we deduce that $1\leq k\leq 335, \ 1\leq l\leq 143$ and $k, l$ are odd.
We set $$A = \{3k|\ k\in\mathbb Z,\ 1\leq k\leq 335,\ k \mbox{ odd}\}$$
and $$B = \{7l|\ l\in\mathbb Z,\ 1\leq l\leq 143,\ l \mbox{ odd}\}.$$
Then, we have $|(A\cup B)\setminus (A\cap B)| = 168 + 72 - 48 = 192.$
On the other hand, from $1$ to $1008$ we have $\frac{1007-1}{2} + 1 = 504$ odd numbers. Combining these data, we conclude that there are $504 -192 -24 = 288$ positive integers $m$.

A: Commenting on your solution process, I think you are making life a little more difficult than it needs to be in this instance by separating out odd numbers. You also end up with a wrong answer.
Here it makes more sense to simply take the three prime factors of $2016$ - $2,3,$ and $7$ - and count all the multiples of these numbers up to $1008$, and then by subtraction find how many numbers in the range are coprime to $2016$.

*

*It's true here that $\gcd(m, 2016{-}m) = \gcd(m, 2016)$, but as observed it might be worth another line of justification for a well-paved proof. For solving the challenge it's not so important.

*You correctly identify that we need to avoid multiples of $2,3,$ and $7$ in the range

*You miss that you have twice subtracted numbers that are multiples of $3\cdot 7 = 21$, so your solution comes out low.

*It's perhaps easier to leave $1008$ in the range because it will be eliminated anyway as not coprime to $2016$.

*As a hand-worked alternative method of getting the count, you could note that the numbers coprime to $(2,3,7)$ will repeat on a block of $2\cdot3\cdot 7=42$ and in fact that pattern is itself symmetric about $21$.


text:
Q: Switching links between multiple wars We have a big application having 13 modules. We want to create war file for each module and deploy the app as an EAR. We navigate to different pages through top menu which contains link for all modules. Now problem is that each module have their own context. In order to switch the context we are using an external.jsp

<%@ include file="/private/jsp/header.jsp"%>
<%
String link= request.getQueryString();
%>

<iframe id="ekawarframe" src="<%=link%>" width="100%" height="80%" scrolling="auto" frameborder="0">

and using urls in this format "/external.jsp?/app/newDerivativeTrade.do?method=loadNewDerivativeTrade&isFreight=false". Is there any other elegant way to navigate links between multiple wars.

A: Well, you can simply link to the other modules using link. The only problem is sharing the http session. Your application server may allow sharing the http session.

A: If you are using maven as a build tool you can add a dependency in ech module to a common war. This will then be merged with the module war.
You can then distribute the header jsp (and other common stuff like css, images and javascript) from a single common module and you do not need the iframe anymore.

A: You can create a key-Based session manager using Redis ou MongoDB.


text:
Q: LaTeX not compiling properly I'm using TeXshop, Natbib, Hyperef and two-column layout, and I am getting the following message:

\pdfendlink ended up in different
  nesting level than \pdfstartlink
\AtBegShi@Output ...ipout \box \AtBeginShipoutBox
                                                    \fi \fi

which prevents LaTeX from compiling. This document compiles without problem when it is 'onecolumn', the problem only starts when it is 'twocolumn'.
I've searched online for solutions, but most of them are from a few years ago, and identify the problem as being caused by a 'long reference'.
Examples of solutions 1, 2
I've narrowed down the source of the problem to be a section that occurs after a table that is two columns wide. The section that follows does not have any references, but when I include it, it stops compiling. I have not included code here as to replicate the problem I need to include my entire document; it only occurs when there is a certain spacing.
Another reference, suggesting that is an obscure bug. I cannot apply their suggestion as I cannot locate the problem reference. I have, just shoved in a lot of spaces and it does compile, however this not really a solution for a working document.

A: Having the same problem here and it popped-up from nowhere. Interestingly if I comment out the hyperref package it works.

A: I believe a common cause for this error is a citation that is split across two pages.  An easy test for this is to add some \vspace at the top of your document to force different page breaks.  This has happened to me a few times, and my final solution typically involves rewriting the text to ensure that the offending citation does not cross the page break.

A: Make a copy of your LaTeX source and start ripping the content out of it until you have the smallest possible example that still causes this error.
If that alone reveals the problem, post it here as an answer.
If it doesn't, append it to the question.

A: *

*Work on understanding the solutions.  LaTeX is a very technical thing, like programming, and if you want to use it you have to accept the fact that you're going to be stuck using your brain to think through solutions.

*The error itself is pretty descriptive.  Are your levels of nesting for your /begin{} and /end{} statements all lined up properly?  All the macros that you're using are being used correctly?  Review the documentation for the packages that you're using.

*Like programming, when you're not sure what's going on, recreate the error with the simplest possible code that you can use.  If that on its own does not already tell you the error (it frequently does!), then post that simplest possible code with your question so that we at least have some small chance to help.  Sadly, due to the complexity of LaTeX, things like package versions may also be quite relevant to the troubleshooting process.


text:
Q: http to https apache redirection .. Infinite Loop Environment: CentOS
Apache Version: Apache/2.2.15
I have been trying to force my website to be https but encounter Infinite redirects
<VirtualHost *:443>
ServerName example.com
ServerAlias example

SetEnv HTTPS on
ProxyPreserveHost On
ProxyPass / http://localhost/
ProxyPassReverse / http://localhost/

SSLEngine on
SSLCertificateFile /ssl/star_ecom_sanmar_com.crt
SSLCertificateKeyFile /ssl/star_ecom_sanmar_com.key
SSLCertificateChainFile /ssl/DigiCertCA.crt
SSLProxyEngine on

<VirtualHost *:80>
ServerName example.com localhost

ServerAlias example
DocumentRoot ......

DirectoryIndex index.shtml index.html index.jsp
AddType text/html .shtml
AddHandler server-parsed .shtml
AddType application/x-httpd-php .php .php4

CustomLog /var/log/httpd/access_log combined env=!dontlog
ErrorLog /var/log/httpd/error_log

RewriteEngine on
RewriteCond "%{HTTPS}" !="on"
RewriteRule ^/(.*)$ https://example.com/$1 [R=301,L]
....

Above rewrite rule is always executed even after redirection to https is done causing an infinite loop which makes me think that the value of {HTTPS} is never updated. same is the case with {SERVER_PORT} which is always 80 even when request is from https.
Below is output from php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">

<title>phpinfo()</title><meta name="ROBOTS" content="NOINDEX,NOFOLLOW,NOARCHIVE" />

PHP Variables

Variable	Value

_SERVER["dontlog"]	1

_SERVER["SCRIPT_URL"]	test.php

_SERVER["SCRIPT_URI"]	test.php

_SERVER["HTTP_HOST"]	example.com

_SERVER["HTTP_UPGRADE_INSECURE_REQUESTS"]	1

_SERVER["HTTP_USER_AGENT"]	Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36

_SERVER["HTTP_ACCEPT"]	text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8

_SERVER["HTTP_ACCEPT_ENCODING"]	gzip, deflate, sdch, br

_SERVER["HTTP_ACCEPT_LANGUAGE"]	en-US,en;q=0.8

_SERVER["HTTP_X_FORWARDED_FOR"]	::1

_SERVER["HTTP_X_FORWARDED_HOST"]	example.com

_SERVER["HTTP_X_FORWARDED_SERVER"]	example.com

_SERVER["HTTP_CONNECTION"]	Keep-Alive

_SERVER["PATH"]	/sbin:/usr/sbin:/bin:/usr/bin

_SERVER["SERVER_SIGNATURE"]	<address>Apache/2.2.15 (CentOS) Server at example.com Port 80</address>

_SERVER["SERVER_SOFTWARE"]	Apache/2.2.15 (CentOS)

_SERVER["SERVER_NAME"]	example.com

_SERVER["SERVER_ADDR"]	::1

_SERVER["SERVER_PORT"]	80

_SERVER["REMOTE_ADDR"]	::1

_SERVER["DOCUMENT_ROOT"]	.....

_SERVER["SERVER_ADMIN"]	root@localhost

_SERVER["SCRIPT_FILENAME"]	test.php

_SERVER["REMOTE_PORT"]	57954

_SERVER["GATEWAY_INTERFACE"]	CGI/1.1

_SERVER["SERVER_PROTOCOL"]	HTTP/1.1

_SERVER["REQUEST_METHOD"]	GET

_SERVER["QUERY_STRING"]	no value

_SERVER["REQUEST_URI"]	test.php

_SERVER["SCRIPT_NAME"]	test.php

_SERVER["PHP_SELF"]	test.php

_SERVER["REQUEST_TIME"]	1483559123

Please advise

A: Change this:
RewriteCond "%{HTTPS}" !="on"

To this:
RewriteCond %{HTTPS} off

And don't set it yourself with SetEnv, mod_rewrite takes care of it.
That redirect is in your <VirtualHost> for port 80 though so I don't see how it could be processed if coming in on https (the check shouldn't be even needed because of that) since the other virtual host would be processed in that case. Are you sure you don't have a .htaccess with some rules in that you've overlooked? Otherwise, please post your full virtual host blocks. And also clear your cache or try a different browser.

A: Fixed.. This was all because of a wrong configuration..
ProxyPass / http://localhost/
ProxyPassReverse / http://localhost/

was calling the port 80 VirtualHost internally (ServerName is localhost) and hence the redirect loop.
This was fixed by replacing the above with
ProxyPass / ajp://localhost:8409/
ProxyPassReverse / ajp://localhost:8409/

A: For me, this had to do with CloudFlare's "flexible" SSL/TSL encryption mode. Setting it to "full" resolved my redirect loop.


text:
Q: E-mail alias, bandwidth usage I had simple mail server and my question is about bandwidth usage of e-mail aliases.
So i had eq  danny@mysvr.com foward: danny@gmail.com
And question is mail demon do:
[MAIL] -> @mysvr.com /* recive e-mail "means read all data" and foward "resend" to @gmail.com */
{OR} :
[MAIL] -> @mysvr.com /* header send "please foward to @gmail.com connecion close" */
[MAIL] -> @gmail.com /* recive e-mail */
Please not R.T.F.M ;)

A: The whole mail is received and forwarded on. The mail transport protocol is called "Simple Mail Transport Protocol" for a reason.

A: If you have configured your mail server to forward all messages to another domain, the mail server would have to receive the whole message so it can pass it on.
This happens normally with email traffic anyway - your message passes through multiple SMTP servers until it is routed to its final destination (you can see each SMTP server an email passes through by examining the email headers). The message would just show as having transferred through another SMTP server (mysvr.com) before reaching its final destination (gmail.com).


text:
Q: Pentaho Data Integration rounds off decimal values after 16 digits I am trying to load a numeric value and I see that any number greater than 16 digits gets rounded off by PDI.
Whether I am using "Select values" step, or "Modified Javascript" or even "Generate rows" step - the value gets rounded off.
Like for example -
Input value - 346003617942512178
Output value - 346003617942512190
As you can see, the last 2 digits got rounded off.
Is there any setting in Pentaho, which needs to be changed so that this round off doesn't happen or atleast increase the 16 digit limit higher? I would like the data to load as is without any round offs but still being recognized as a Number and not a String.
Any help on this will be appreciated.

A: You can look this transformation BigNumber, where input value is same but output is different based on data type.


text:
Q: Never make public members virtual/abstract - really? Back in the 2000s a colleague of mine told me that it is an anti-pattern to make public methods virtual or abstract.
For example, he considered a class like this not well designed:
public abstract class PublicAbstractOrVirtual
{
  public abstract void Method1(string argument);

  public virtual void Method2(string argument)
  {
    if (argument == null) throw new ArgumentNullException(nameof(argument));
    // default implementation
  }
}

He stated that

*

*the developer of a derived class that implements Method1 and overrides Method2 has to repeat the argument validation.

*in case the developer of the base class decides to add something around the customizable part of Method1 or Method2 later, he cannot do it.

Instead my colleague proposed this approach:
public abstract class ProtectedAbstractOrVirtual
{
  public void Method1(string argument)
  {
    if (argument == null) throw new ArgumentNullException(nameof(argument));
    this.Method1Core(argument);
  }

  public void Method2(string argument)
  {
    if (argument == null) throw new ArgumentNullException(nameof(argument));
    this.Method2Core(argument);
  }

  protected abstract void Method1Core(string argument);

  protected virtual void Method2Core(string argument)
  {
    // default implementation
  }
}

He told me making public methods (or properties) virtual or abstract is as bad as making fields public. By wrapping fields into properties one can intercept any access to that fields later, if needed. The same applies to public virtual/abstract members: wrapping them the way as shown in the ProtectedAbstractOrVirtual class allows the base class developer to intercept any calls that go to the virtual/abstract methods.
But I don't see this as a design guideline. Even Microsoft doesn't follow it: just have a look at the Stream class to verify this.
What do you think of that guidline? Does it make any sense, or do you think it's overcomplicating the API?

A: Doing it the way your colleague suggests does provide more flexibility to the implementor of the base class. But with it also comes more complexity which is typically not justified by the presumed benefits.
Mind that the increased flexibility for the base class implementer comes at the expense of less flexibility to the overriding party. They get some imposed behavior that they may not particularly care for. To them things have just gotten more rigid. This can be justified and helpful but this all depends on the scenario.
The naming convention to implement this (that I know of) is to reserve the good name for the public interface and to prefix the internal method's name with "Do".
One useful case is when the action performed needs some setting up and some closing down. Like open a stream and close it after the overrider is done. In general, same sort of initialization and finalization. It is a valid pattern to use but it would be pointless to mandate its use in all abstract and virtual scenarios.

A: Saying

that it is an anti-pattern to make public methods virtual or abstract because of
  the developer of a derived class that implements Method1 and overrides Method2 has to repeat the argument validation

is mixing up cause and effect. It makes the assumption that every overrideable method requires a non-customizable argument validation. But it is quite the other way round:
If one wants to design a method in a way it provides some fixed argument validations in all derivations of the class (or - more general - a customizable and a non-customizable part), then it makes sense to make the entry point non-virtual, and instead provide a virtual or abstract method for the customizable part which is called internally.
But there are lots of examples where it makes perfect sense to have a public virtual method, since there is no fixed non-customizable part: look at standard methods like ToString or Equals or GetHashCode- would it improve the design of the object class to have these not public and virtual at the same time? I don't think so.
Or, in terms of your own code: when the code in the base class finally and intentionally looks like this
 public void Method1(string argument)
 {
    // nothing to validate here, all strings including null allowed
    this.Method1Core(argument);
 }

having this separation between Method1 and Method1Core only complicates things for no apparent reason.

A: In C++, this is called the non-virtual interface pattern (NVI).  (Once upon a time, it was called the Template Method.  That was confusing, but some of the older articles have that terminology.)  NVI is promoted by Herb Sutter, who has written about it at least a few times.  I think one of the earliest is here.
If I recall correctly, the premise is that a derived class should not change what the base class does but how it does it.
For example, a Shape might have a Move method to relocate the shape.  A concrete implementations (e.g., like Square and Circles) shouldn't directly override Move, because Shape defines what Moving means (at a conceptual level).  A Square might have difference implementation details than a Circle in terms of how the position is represented internally, so they will have to override some method to provide the Move functionality.
In simple examples, this often boils down to a public Move that just delegates all the work to a private virtual ReallyDoTheMove, so it seems like a lot of overhead for no benefit.
But this one-to-one correspondence is not a requirement.  For example, you could add an Animate method to Shape's public API, and it might implement that by calling ReallyDoTheMove in a loop.  You end up with two public non-virtual methods APIs that both rely on the one private abstract method.  Your Circles and Squares don't need to do any extra work, nor can the override Animate.
The base class defines the public interface used by consumers, and it defines an interface of primitive operations that it needs to implement those public methods.  The derived types are responsible for providing implementations of those primitive operations.
I'm not aware of any differences between C# and C++ that would change this aspect of class design.

A: tl;dr–  Argument-validation is a run-time check for the part of the method-signature that isn't checked at compile-time.  Prohibiting public abstract/virtual methods is a pattern for ensuring that the exact same code-validation is used, consistent with the requirement that the exact same compile-time checks apply to the same signature-group.

The rationale for not exposing abstract/virtual methods is that methods should always have the same signature, both formally and informally.
For example:
class A
{
    public virtual void Print(string? text)
    {
        if (String.IsNullOrEmpty(text)) { throw new InvalidArgumentException(); }
        Console.WriteLine(text);
    }
}
class B1 : A
{
    public override void Print(string? text)
    {
        if (String.IsNullOrEmpty(text)) { throw new InvalidArgumentException(); }
        Console.WriteLine(text);
    }
}
class B2 : A
{
    public override void Print(string? text)
    {
        if (text == null) { throw new NullArgumentException(); }
        if (text.Equals(String.Empty)) { throw new InvalidArgumentException(); }
        Console.WriteLine(text);
    }
}
class B3 : A
{
    public override void Print(string? text)
    {
        Console.WriteLine(text ?? "[null]");
    }
}

In the code above, string? text can't be null or empty ("").  Anyone calling .Print() should understand, by contract, that they're actually calling
public virtual void Print([non-null, non-empty]string text)

, leaving three possibilities for inheritors:

*

*Correctly duplicate the exact same code for validation.

*

*Example: B1.Print() duplicates A.Print()'s validation code.

*Correctly reproduce the same effective-signature, but with inconsistent behavior.

*

*Example: B2.Print() has the same effective-signature as A.Print(), but it has inconsistent behavior (returning a different type of exception for a null-argument).

*Incorrectly change the effective-signature in addition to inconsistent behavior.

*

*Example: B3.Print() accepts null/empty strings.

For example, say someone's trying to debug their code:
var list = new List<A>();
list.Add(new A());
list.Add(new B1());
list.Add(new B2());
list.Add(new B3());

foreach (A item in list)
{
    item.Print(null);
}

, where they improperly call .Print(null) four times.  It's the exact same error, but:

*

*They'll get 2 InvalidArgumentException's (from A.Print() and B1.Print()).

*They'll get 1 NullArgumentException (from B2.Print()).

*They'll not get an exception for the fourth mistake, which'll fail silently.

*They'll also get an effective Print("[null]") despite never having called Print("[null]") and having no reason to expect the method to produce this behavior from its code-contract.  (Yeah, it's not too hard to figure out what happened in this simple example, but in larger code projects, tracking down stuff like this can be fun!)

Summary of problems.
In short, the problems can include: code-duplication, inconsistent debug-feedback, silent-failures, and unexpected-behavior.
Ultimately inheritors have two options:

*

*Copy/paste the validation code from the base-method in every override (whether directly or through memorizing it and retyping it).  Require anyone changing any of them to copy/paste the new version everywhere else too.

*Have the code-base polluted with inconsistent debug-feedback, silent errors, and inconsistent behaviors.
Both options make headaches for maintenance.  Option (1) requires maintainers to be sure that they copy/paste any modifications into each virtual/override in the same family while Option (2) can result in all sorts of weird problems to untangle.

Better pattern.
class A
{
    public void Print(string? text)
    {
        if (String.IsNullOrEmpty(text)) { throw new InvalidArgumentException(); }
        this.Internal_Print(text);
    }
    protected virtual void Internal_Print(string? text)
    {
        Console.WriteLine(text);
    }
}
class B : A
{
    protected override void Internal_Print(string? text)
    {
        Console.WriteLine(text);
    }
}

This pattern prevents both the need and ability of inheritors to change the parameter-validation.  Now we don't have to deal with copy/pasting validation code and the inconsistent/unexpected behaviors that can come from doing anything other than copy/pasting validation code.

Discussion: Conceptual argument for locking the implicit part of a signature.
A method-signature effectively has two parts:

*

*An explicitly specified part, with compile-time validation.

*An implicitly specified part, with run-time validation.
The language forces inheritors to maintain consistency with the explicit part, but the implicit part isn't fully captured by the type-system.
So, coders can either:

*

*maintain consistency by copy/pasting the same validation code everywhere;

*maintain consistency by requiring methods to create correct types that precisely describe the expected argument space (e.g., using non-null types when null isn't allowed);

*break consistency by doing their own thing in each method;

*maintain consistency through a combination of (1) and (2) using the above pattern.

Note: Historical context of string? vs. string.
The above code uses string? for consistency with modern C#.  However, before C# fixed null-reference typing ambiguities, this same code would've been written as
public virtual void Print(string text)

, because the nullable-qualifier, ?, used to be implicitly assumed on all reference-types.
So if you're confused as to why we'd make the argument nullable only to then protest nullability, that's why: this is meant to reflect a historically common pattern, but written in more recent language.


text:
Q: Is there any limit to the number of Selenium RCs connected to a Selenium Hub? Does anybody have experience using 20/50/100 RCs connected to a single Selenium Hub? I'm thinking of a centralized hub that multiple team could use together.
I heard that after 20 RCs, performance goes down significantly.

A: My tests use 104 RCs which are connected to a single Hub. Hub is able to handle all the RCs and the system is stable. One thing that you should note is, how you pass the commands to the Hub.This determines how much RCs Hub is going to utilize. What we do in our grid is, we run multiple builds at the same time - all pointing to the same Hub. This would mean Hub is always kept busy.

A: I'm not sure where the "20" value is coming from.  I run with significantly more than that to power Mogotest and we run many more test sessions across various sites than most users of grid.  Granted older versions had some thread problems, but 1.0.8 should be pretty solid and the 2.0 releases have not exhibited any problems.
FWIW, I maintain the grid project and backport any known fix for any known load issues.  I also know of several others running large-scale grid installations without incident.

A: It boils down to how robust your h/w is. Though I can't say exact statistics yet suggest to keep it with in 20

A: Well there is not but yes very much close to 20 for good performance.


text:
Q: Set RGB background-color of an Excel cell with Apache POI i am trying copy cells from one row to the one below. To copy the comments and cellvalues works fine. Now if I set a background-color in Excel and want to just copy it to the new cell, it doesn't work. Either there is just no color after copying or the background is black.
I tried that:
style2.setFillBackgroundColor(cell_master_alt.getCellStyle().getFillBackgroundColor());
style2.setFillForegroundColor(cell_master_alt.getCellStyle().getFillForegroundColor());

style2.setFillPattern(CellStyle.SOLID_FOREGROUND);    or
style2.setFillPattern(cell_master_alt.getCellStyle().getFillPattern());

cell_master_neu.setCellStyle(style2);

After a few hours without any progress, I looked into the foreground- and background-color of the cell I want to copy. There I found RGB values. Now I want to make a new Cellstyle with that values, but that doesn't work as well.
First I try this:
style_new.setFillForegroundColor(new XSSFColor(new java.awt.Color(128,128,128)));

but there is an error message:
The method setFillForegroundColor(short) in the type CellStyle is not applicable for the arguments (XSSFColor)

What is wrong with that?
Thanks

A: In Apache POI cell styles can be applied to multiple cells due to the way Excel stores them in the binary format, thus it should suffice to just apply the cell style from one cell onto the other without any copying:
cell_master_neu.setCellStyle(cell_master_alt.getCellStyle());


text:
Q: JNBridge JMS Asynchronous batch failed, anyone know? I have seen on our BT 2013 Environment's event logs a lot of warnings like below

"The adapter "JNBridge JMS" raised an error message. Details "Asynchronous Batch Failed. HRESULT: C0C0162F" . "

This adapter is used to receive messages from AMQ.  Have you guys encountered this error? what was the cause? and what was the impact? I have found nothing on google searching for the issue.