text:
Q: How do I provoke a SQLExcetpion in DAO-Layer with JUnit I have a DAO-Layer which I want to test with JUnit. The test coverage is about 85%, so nearly every line of code is covered except the catch clauses for SQLException. I have no idea how I can provoke a SQLException for the snippet below:

The only conceivable solution for me is to reset the value of the final variable SELECT_ALL_ATTR to something like: SELLLLLECT * FROM ATTRIBUTES; by using java reflection. I know that I can easily test exceptions by using the Mock framework. But I don't want to introduce Mock tests just for exception testing since everything else is tested with JUnit.
Is there a way other than java reflection?

A: It's not easy to simulate a sql exception in your case because all dependences are initiated by the dao itself. Maybe you can pass a fake Connection which throws a SqlException in some method?

A: I wrote a little tool for this http://melati.org/throwing-jdbc-4.1/index.html

A: This is a great use case for a mock library. I use mockito. Assuming you want to test the behavior of the clients of your DAO, you just mock it:
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import junit.framework.Assert;
import org.junit.Test;
public class MockitoTest {
/** your dao, just putting some code here for an example */
class MyDAO {
    public List<SVCAttribute> selectAll(Connection con) throws DAOException {
        try {
            //your code..
        }catch(Exception ex) {
            throw new DAOException();
        }
        return new ArrayList<SVCAttribute>();
    }
}
@Test
public void testMe() throws Exception {
    MyDAO dao = mock(MyDAO.class);
    when(dao.selectAll(any(Connection.class))).thenThrow(DAOException.class);
    Connection con = getConnection();
    try {
        dao.selectAll(con);
        Assert.fail();
    }catch(Exception ex) {
        System.out.println("caught expected excetpion");
    }
}


text:
Q: Как создать дополнительные команды для бота телелеграмм? В боте есть стандартный список команд, но надо расширить функционал. поэтому решил добавить команду \other_commands. Но как сделать, чтоб стандартные команды удалялись, а новые появлялись при нажатии на эту команду?
Попытался реализовать как то так, но догадываюсь что это не правильно, тк стандартные команды регистрируются в функции main при запуске.
async def set_commands(bot: Bot):
    commands = [
        types.BotCommand(command='/add', description='Добавить услугу'),
        types.BotCommand(command='/other_commands', description='Доп. меню'),
        types.BotCommand(command='/cancel', description='Отменить действие'),
    ]
    await bot.set_my_commands(commands)

async def set_add_commands(bot: Bot):
    commands = [
        types.BotCommand(command="/all_services", description="Все виды услуг"),
        types.BotCommand(command="/something", description="Что-то еще"),
    ]
    await bot.set_my_commands(commands)

def register_commands(dp: Dispatcher):
    '''При отлове команды \other_commands должна запускаться функция other_commands которая и должна удалять старые команды и добовлять новые'''
    dp.register_message_handler(other_commands, commands='other_commands', state='*')

async def other_commands(dp):
    await bot.delete_my_commands()
    await set_add_commands(bot)

async def main(dp):
    register_commands(dp)
    await set_commands(bot)

if __name__ == '__main__':
    executor.start_polling(dp, on_startup=main, skip_updates=True)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get winning odds from elo ratings in a league Consider that I have a basketball game (so there are no draws) and I have 2 teams with elo ratings already set ( not interested in points margin for this). If the elo ratings for the teams are e1 and e2 then I can calculate the winning chances of  team 1 via this algorithm:
Apologies for the code format below, e is equal to 10 to the power of (e2-e1)/400.
e = Math.pow(10, (e2 - e1) / 400);
odds = 1 / ( 1 + e);

All works as expected with the odds being a value between 0 and 1 and I can easily get the odds of the team 2 as 1-odds (not interested here in any influence of a home advantange either).
I now have a whole league with K (let's say 10) teams, each has its own elo rating(all ratings averaging out to 1200). The league is a simple round robin format with each team playing each other once at home and once away.
How can I calculate the odds of each team winning the league?


text:
Q: How to mock dynamodb promise support using jest? There are similar questions but all of them uses some kind of library ( which does not work in my case).How do i make i work for promise return by dynamodb query
here is my code to be tested
  const isUrl = require('is-url');
const AWS = require('aws-sdk');
const { nanoid } = require('nanoid/async');
const express = require('express');

const router = express.Router();
const dynamoDb = new AWS.DynamoDB.DocumentClient();

// URL from users

router.post('/', async (req, res) => {
  // urlId contains converted short url characters generated by nanoid

  const urlId = await nanoid(8);
  const { longUrl } = req.body;

  // Veryfying url Format using isUrl, this return a boolean
  const checkUrl = isUrl(longUrl);
  if (checkUrl === false) {
    return res.status(400).json({ error: 'Invalid URL, please try again!!!' });
  }

  const originalUrl = longUrl;
  const userType = 'anonymous'; // user type for anonymous users
  const tableName = 'table-name'; // table name for storing url's

  const anonymousUrlCheckParams = {
    TableName: tableName,
    Key: {
      userId: userType,
      originalUrl,
    },
  };

  const paramsForTransaction = {
    TransactItems: [
      {
        Put: {
          TableName: tableName,
          Item: {
            userId: userType,
            originalUrl,
            convertedUrl: `https://url/${urlId}`,
          },
        },
      },

      {
        Put: {
          TableName: tableName,
          Item: {
            userId: urlId,
            originalUrl,
          },
          ConditionExpression: 'attribute_not_exists(userId)',
        },
      },
    ],
  };

  try {
    const dynamoDbGetResults = await dynamoDb
      .get(anonymousUrlCheckParams)
      .promise();
    if (
      Object.keys(dynamoDbGetResults).length === 0 &&
      dynamoDbGetResults.constructor === Object
    ) {
      await dynamoDb.transactWrite(paramsForTransaction).promise();
      return res.status(201).json({
        convertedUrl: `https://trimify.awssensei.tk/${urlId}`,
      });
    }
    return res.status(201).json({
      convertedUrl: dynamoDbGetResults.Item.convertedUrl,
    });
  } catch (err) {
    return res
      .status(500)
      .json({ error: 'Unknown Server Error, Please Trimify Again!' });
  }
});

module.exports = router;
my test code
describe('Test for Authenticated Url', () => {
  beforeEach(() => {
    jest.resetModules();
  });
  test('should return converted url for authenticated user', async () => {
    const mockedDocumentClient = {
      get: jest.fn(),
      transactWrite: jest.fn(),
    };

    const mockedDynamoDB = {
      DocumentClient: jest.fn(() => mockedDocumentClient),
    };
    jest.doMock('aws-sdk', () => ({ DynamoDB: mockedDynamoDB }));

    mockedDocumentClient.get.mockImplementation((params, callback) => {
      const data = {
        Item: {
          convertedUrl: 'xyz',
        },
      };
      callback(null, data);
    });
    mockedDocumentClient.transactWrite.mockImplementation(
      (params, callback) => {
        callback(null);
      }
    );

    const app = require('../app');
    const response = await request(app).post('/auth-ops/convert').send({
      longUrl: 'https://google.com',
      userId: 'google-oauth2|110198332436292901252',
    });
    expect(response.body).toMatchObject({ convertedUrl: 'xyz' });
    expect(response.statusCode).toBe(201);
  });
test('should send 201 when it is new Url', async () => {
    const mockedDocumentClient = {
      get: jest.fn(),
      transactWrite: jest.fn(),
    };

    const mockedDynamoDB = {
      DocumentClient: jest.fn(() => mockedDocumentClient),
    };
    jest.doMock('aws-sdk', () => ({ DynamoDB: mockedDynamoDB }));

    mockedDocumentClient.get.mockImplementation((params, callback) => {
      const data = {};
      callback(null, data);
    });
    mockedDocumentClient.transactWrite.mockImplementation(
      (params, callback) => {
        callback(null);
      }
    );

    const app = require('../app');
    const response = await request(app).post('/auth-ops/convert').send({
      longUrl: 'https://google.com',
      userId: 'google-oauth2|110198332436292901252',
    });
    expect(response.body).not.toBe(undefined);
    expect(response.statusCode).toBe(201);
  });
});

A: i removed the express specific code and create an example using your logic, i added 3 comments, "CASE A", "CASE B" and "CASE C", which co-relates to all branches in your code (e.g. ifs or returns), we will use that in our test case
let AWS = require("aws-sdk");

let dynamoDb = new AWS.DynamoDB.DocumentClient({ apiVersion: "2012-08-10" });

async function main() {
  try {
    const dynamoDbGetResults = await dynamoDb.get("some-loginUrlCheckParams").promise();
    // CASE A
    if (Object.keys(dynamoDbGetResults).length === 0 && dynamoDbGetResults.constructor === Object) {
      let urlId = await dynamoDb.transactWrite("some-paramsForTransaction").promise();
      return {
        convertedUrl: `https://my-url/${urlId}`,
      };
    }
    // CASE B
    return {
      convertedUrl: dynamoDbGetResults.Item.convertedUrl,
    };
  } catch (err) {
    // CASE C
    return { error: "Unknown Server Error, Please Trimify Again!", message: err.message };
  }
}

module.exports = { main };

from here, we would need to have access to .get and .transactWrite per test, so we can mock the values returned in that specific case
to achieve that, you can take advantage of how jest mock and hoist variables starting with mock* works
creating an api to manipulate the returned value per test case:
let AWS = require("aws-sdk");

let { main } = require("./main");

let mockDocumentClient = {
  get: {
    promise: jest.fn()
  },
  transactWrite: {
    promise: jest.fn()
  },
};

jest.mock("aws-sdk", () => {
  return {
    DynamoDB: {
      DocumentClient: jest.fn().mockImplementation(() => {
        return {
          get: () => mockDocumentClient.get,
          transactWrite: () => mockDocumentClient.transactWrite,
        };
      }),
    },
  };
});

describe("Test for Authenticated Url", () => {
  it("returns CASE A", async () => {
    mockDocumentClient.get.promise.mockReturnValueOnce({})
    mockDocumentClient.transactWrite.promise.mockReturnValueOnce("test-urlId")
    let test = await main();
    expect(test).toEqual({ convertedUrl: 'https://my-url/test-urlId' })
  });

  it("returns CASE B", async () => {
    mockDocumentClient.get.promise.mockReturnValueOnce({
      Item: {
        convertedUrl: "test-converted-url"
      }
    })
    let test = await main();
    expect(test).toEqual({ convertedUrl: 'test-converted-url' })
  });

  it("returns CASE C", async () => {
    mockDocumentClient.get.promise.mockImplementationOnce(() => {
      throw new Error("test-error")
    })
    let test = await main();
    expect(test).toEqual({ error: 'Unknown Server Error, Please Trimify Again!', message: "test-error" })
  });
});

as you can see, we lazy load mockDocumentClient into our jest.mock (Jest will only call mockDocumentClient when the function of get: () => is executed), enabling us to pass the same mock variable to our test cases and manipulate the returned value
achieving 100% test coverage in that snippet:

i highly recommend you to review these two articles, they will explain it in more detail from Jest perspective:
https://jestjs.io/docs/es6-class-mocks#calling-jestmock-with-the-module-factory-parameter
https://blog.bam.tech/developer-news/fix-jest-mock-cannot-access-before-initialization-error

A: you should reproduce dynamodb signature with mock (my example is just general, idk all details of you dynamo import)
jest.mock('dynamodb', () => {
  get: async (data) => jest.fn()
})


text:
Q: XHTML, XML или html? С html разобрался, но прочитал статью про XML и XHTML, пишут что это более лучший язык для сайтов и что он заменит html! Я что не тот язык выучил?

A:
С html разобрался

Это хорошо. Теперь разберитесь с CSS. И тогда вы сможете создать свою первую страничку.

прочитал статью про XML и XHTML

Это ещё лучше. Как однажды сказал русский полководец Александр Васильевич Суворов: "Ученье — свет, а неученье — тьма".

про XML и XHTML, пишут что это более лучший язык для сайтов

Неправду пишут (хотя, есть моменты, где можно и поспорить). Но не лучшие точно, а скорее немного разные языки.

и что он заменит html

По крайней мере в ближайшее время точно не заменит. А что будет дальше, то поживём - увидим. Возможно, что в будущем не будет ни того, ни другого, и ничего из перечисленного, а что-то совершенно новое. Время покажет.

Я что не тот язык выучил?

А это зависит от того, что вы планируете создавать и для какой цели изучаете тот или иной язык. Главное, и в первую очередь, это знать русский язык, потому как он один из самых сложных языков во всём мире.
Желаю удачи в "грызении" гранита науки!

ps

То, что вы читали, устарело примерно 15 лет назад. – andreymal

Ну не сказать. Смотря что читали и о чем. Например, с XML я работал как 15 лет назад, так и сегодня работаю.


text:
Q: Change Swagger UI's "Schemas" to "Models"? Swagger & Swagger UI use "Schemas" and "Models" interchangeably. I'd like to refer to them as Models on my Swagger UI instance (rather than Schemas), but can't find where to make this change.
I've attached 2 images that show where I'm referring to. I'd like to erase all references of "Schemas" from the page, and replace them with "Model", similar to how it appears on many of Swagger's test sites (example: petstore.swagger.io) that they've created.
Image 1
Image 2

A:
Swagger & Swagger UI use "Schemas" and "Models" interchangeably.

Just to clarify - Swagger UI uses "Schema" when rendering OpenAPI 3 definitions, and "Model" when rendering OpenAPI 2.0 definitions. With this in mind, "Model" is sort of an outdated term.

If you still want to see the "Model" label in Swagger UI regardless of your OpenAPI version, you'll have to fork Swagger UI, change the label in the code, and build and use your own version. (And rebuild it whenever you want to use a newer Swagger UI release.)
The lines you need to change are:

*

*src/core/components/model-example.jsx
{isOAS3 ? "Schema" : "Model" }

change to
"Model"

*src/core/components/models.jsx
{isOAS3 ? "Schemas" : "Models"}

change to
"Models"


text:
Q: Как правильно работать с абстрактными классами в Qt? Как работать с несколькими классами в Qt? Я не понимаю как работать с абстрактными классами виджетов в Qt.
Мне нужно написать простое приложение, которое состоит из одного QLabel и QLineEdit.
Задача - прикрепить к QLineEdit QValidator для того, что бы отсечь цифры при вводе.
Но компилятор ругается на то, что не может выделить объект абстрактного класса QValidator.
Как решить эту проблему, что я делаю не так?
И еще один вопрос, возможно не много не по теме. До текущего момента я писал такие же небольшие приложения с одним базовым классом, стараясь запихнуть в реализацию класса как можно больше. То есть, для базового класса все виджеты и сигналы определялись еще в конструкторе и в заголовочном файле.
Когда же я писал этот код, в конструктор абстрактного класса виджеты засунуть не получилось, а связать его с другим базовым классом унаследованным от QWidget как с отцовским классом, тоже не выходит.
Как корректней писать приложения, реализовывать все в одном классе или в нескольких и если да то как их правильно разносить между собой?
main.cpp
#include "mainwidget.h"
#include "namevalidator.h"
#include <QApplication>
#include <QLabel>
#include <QLineEdit>
#include <QVBoxLayout>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    mainWidget w;

    QLabel *lblText = new QLabel("&Name (The digits will not be accepted!)");
    QLineEdit *lineText = new QLineEdit;
    NameValidator *nmVal = new NameValidator(lineText);

    lineText->setValidator(nmVal);
    lblText->setBuddy(lineText);

    //Layout setup
    QVBoxLayout *vBox = new QVBoxLayout;
    vBox->addWidget(lblText);
    vBox->addWidget(lineText);
    w.setLayout(vBox);
    w.show();

    w.show();

    return a.exec();
}

mainwidget.cpp
#include "mainwidget.h"

mainWidget::mainWidget(QWidget *parent)
    : QWidget(parent)
{
    spBox = new QSpinBox;
    spBox->setRange(1, 100);
    spBox->setSuffix(" MB");
    spBox->setButtonSymbols(QSpinBox::PlusMinus);
    spBox->setWrapping(true);
    spBox->show();
    spBox->resize(50, 30);

    dtBox = new QDateTimeEdit(QDateTime::currentDateTime());

    vBox = new QVBoxLayout;
    vBox->addWidget(spBox);
    vBox->addWidget(dtBox);

    setLayout(vBox);
    resize(200, 40);
}

mainWidget::~mainWidget()
{

}

mainwidget.h
#ifndef MAINWIDGET_H
#define MAINWIDGET_H

#include <QWidget>
#include <QSpinBox>
#include <QDateTimeEdit>
#include <QVBoxLayout>

class mainWidget : public QWidget
{
    Q_OBJECT

public:
    mainWidget(QWidget *parent = 0);
    ~mainWidget();

private:
    QSpinBox *spBox;
    QDateTimeEdit *dtBox;
    QVBoxLayout *vBox;
};

#endif // MAINWIDGET_H

namevalidator.h
#ifndef NAMEVALIDATOR_H
#define NAMEVALIDATOR_H

#include <QValidator>
#include <QString>
#include <QRegExp>

class NameValidator : public QValidator
{
public:
    NameValidator(QObject *parent);

    virtual State validate(QString str, int& pos) const
    {
        QRegExp rxp = QRegExp("[0-9]");
        if (str.contains(rxp)) {
            return Invalid;
        }

        return Acceptable;
    }
};

#endif // NAMEVALIDATOR_H

namevalidator.cpp
#include "namevalidator.h"

NameValidator::NameValidator(QObject *parent)
    : QValidator(parent)
{
}

A: Абстрактные классы (не только в QT) нужны, чтобы унаследовать свой класс от них, следуя их логике. Абстрактные классы для того и нужны, чтобы "подсказать" каким должен быть ваш класс и описывает схему вызовов функций, которые вам еще предстоит описать в классе наследнике. Если вы создали унаследованный класс от абстрактого, в нем должны быть описаны все абстрактные функции родителя, а то класс так и останется абстрактным (в частности ваш класс NameValidator). А создать объект абстрактного класса невозможно согласно синтаксису языка и это правильно!
В классе NameValidator потребуется описать все абстрактные методы QValidator

Пихать все в один класс неправильно, есть даже такой "антипаттерн" вроде. Чтобы "разносить" между собой разные классы программисты C++ традиционно использовали членами класса указатели на объекты друг-друга. В QT появилось такое замечательное средство как сигналы и слоты, с помощью них вообще прекрасно получается классы "разносить".


text:
Q: leakage of memory in java http://www.ibm.com/developerworks/rational/library/05/0816_GuptaPalanki/#javaexample
The Author across the code says that there is memory leakage.
public class LeakExample {
    static Vector myVector = new Vector();
    static HashSet pendingRequests = new HashSet();

    public void slowlyLeakingVector(int iter, int count) {
        for (int i=0; i<iter; i++) {
            for (int n=0; n<count; n++) {
                myVector.add(Integer.toString(n+i));
            }
            for (int n=count-1; n>0; n--) {
                // Oops, it should be n>=0
                myVector.removeElementAt(n);
            }
        }
    }

How does this code has memory leak and while the below does not have. What makes both different.
public void noLeak(int size) {
        HashSet tmpStore = new HashSet();
        for (int i=0; i<size; ++i) {
            String leakingUnit = new String("Object: " + i);
            tmpStore.add(leakingUnit);
        }
        // Though highest memory allocation happens in this
        // function, but all these objects get garbage
        // collected at the end of this method, so no leak.
    }

A: In your first example, not all the elements of the vector are removed (as is shown by the comment in the code). And since myVector is a static member variable, it stays there for as long as the app is running, and will grow over time with each call to slowlyLeakingVector().
In the second example, tmpStore is a local variable, which will be garbage collected every time after returning from noLeak().

A: Every time the first code is run, n elements are added, and (n-1) are removed (the element at 0 is not) so the vector slowly stores elements that will never be used. And as the vector is static, it will exist until the JVM is shut down, leaking memory.
In the second example, the tmpStore can be garbage collected at the end of each call, so no leak.

A: The key here is
for (int n=count-1; n>0; n--) {
    // Oops, it should be n>=0
    myVector.removeElementAt(n);
}

Last element never gets removed as n is never 0 inside the loop, ie removeElementAt(0) never runs. This leads to the elements slowly accumulating in the vector.


text:
Q: Serializing responses in Jersey+Jackson I am trying to understand whether it is possible to serialize a java Map to a Json response from Jersey.
Here is my service :
@Singleton
@Path("/")
public class ApiServiceResource {
    @Inject
    ISeedingUpdateService seedingUpdateService;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/map")
    public List<String> getMap() {
        return newArrayList(seedingUpdateService.toString());
    }
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("/pojo")
    public TemplateMessage getTemplateMessage(@PathParam("param") String param) {
        return new TemplateMessage(param, seedingUpdateService.toString());
    }

    @XmlRootElement
    public static class TemplateMessage {
        public Map<String,String > param;
        public TemplateMessage() {
        }
        public TemplateMessage(String param1, String param2) {
            this.param = newHashMap();
            this.param.put(param1,param2);
        }
    }
}

The getMap method fails since it cannot serialize the Map -->
SEVERE: The registered message body writers compatible with the MIME media type are:
application/json ->
  com.sun.jersey.json.impl.provider.entity.JSONJAXBElementProvider$App
  com.sun.jersey.json.impl.provider.entity.JSONArrayProvider$App
  com.sun.jersey.json.impl.provider.entity.JSONObjectProvider$App
  com.sun.jersey.json.impl.provider.entity.JSONRootElementProvider$App
  com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$App
*/* ->

And the second method works just fine the POJO is serialized with the Map inside.
Is there something that i am missing ?
By the way the app is configured in Guice , so here is the guice configuration :
@Override
protected void configureServlets() {
    bind(ApiServiceResource.class);
    /* bind jackson converters for JAXB/JSON serialization */
    bind(MessageBodyReader.class).to(JacksonJsonProvider.class);
    bind(MessageBodyWriter.class).to(JacksonJsonProvider.class);
    Map<String,String> parameters = newHashMap();
    parameters.put("com.sun.jersey.config.property.packages", "com.delver.update.api");
    serve("/rest/*").with(GuiceContainer.class, parameters);
}

A: Instead of binding MessageBodyWriter (since you already have more than one) you could try what we do in our app, we bind the Jackson writer and exception mappers in Guice through:
bind(forName("com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider")).in(Scopes.SINGLETON);
bind(forName("com.fasterxml.jackson.jaxrs.json.JsonParseExceptionMapper")).in(Scopes.SINGLETON);
bind(forName("com.fasterxml.jackson.jaxrs.json.JsonMappingExceptionMapper")).in(Scopes.SINGLETON);


text:
Q: Spritekit- DidBeginContact not being called I noticed this issue has happened to a lot of people.  I made sure to have the self.physicsWorld.contactDelegate = self
in the didMove function but it still doesn't work.  Here is my code:
class PoolTableScene: SKScene, SKPhysicsContactDelegate {

  struct PhysicsCatagory {

    static let None : UInt32 = 0 //0
    static let OrangeBall : UInt32 = 0b1 //1
    static let BlueBall : UInt32 = 0b10 //2
    static let PokeBall : UInt32 = 0b100 //3
    static let Border : UInt32 = 0b1000 //4
    static let All : UInt32 = UInt32.max

  }

  let ballPoke = SKSpriteNode(imageNamed:"pokeBall")
  let ballBlue = SKSpriteNode(imageNamed:"blueBall")
  let ballOrange = SKSpriteNode(imageNamed: "orangeBall")
  //var lastTouch: CGPoint? = nil

  override func didMove(to view: SKView) {

    self.physicsWorld.contactDelegate = self

    self.physicsWorld.gravity = CGVector(dx: 0, dy: -9.8)

    //used to set gravity

    //creates body for sprite that will lock the objects to a specific area
    let sceneBody = SKPhysicsBody(edgeLoopFrom: self.frame)
    sceneBody.friction = 0 //This will make the ball bounce naturally off the edges of the scenBody
    self.physicsBody = sceneBody // make physics only affect whats in sceneBody - NEED PHYSICS BODY UNLESS IT WON'T BE AFFECTED BY PHYSICS
    self.physicsBody?.categoryBitMask = PhysicsCatagory.Border
    self.physicsBody?.collisionBitMask = PhysicsCatagory.BlueBall | PhysicsCatagory.OrangeBall | PhysicsCatagory.PokeBall
    self.physicsBody?.contactTestBitMask = PhysicsCatagory.None

    ballPoke.name = "ballPoke"
    ballPoke.size = CGSize(width: 50, height: 50)
    ballPoke.anchorPoint = CGPoint(x:0.5, y:0.5)
    ballPoke.position = CGPoint(x: self.frame.size.width*0.25, y:self.frame.size.height/2)
    ballPoke.zPosition = 100
    ballPoke.physicsBody = SKPhysicsBody(circleOfRadius: 25)//need this so the ball can be affected by physics
    ballPoke.physicsBody?.affectedByGravity = true //ball will be affected by gravity determined by the scene's physics
    ballPoke.physicsBody?.restitution = 1 // sets bounciness of ball
    ballPoke.physicsBody?.linearDamping = 0 //used to set how air resistence will affect ball
    ballPoke.physicsBody?.categoryBitMask = PhysicsCatagory.PokeBall
    ballPoke.physicsBody?.collisionBitMask = PhysicsCatagory.BlueBall | PhysicsCatagory.Border
    ballPoke.physicsBody?.contactTestBitMask = PhysicsCatagory.OrangeBall

    self.addChild(ballPoke)

    ballBlue.name = "ballBlue"
    ballBlue.size = CGSize(width: 50, height: 50)
    ballBlue.anchorPoint = CGPoint(x:0.5, y:0.5)
    ballBlue.position = CGPoint(x: self.frame.size.width*0.50, y:self.frame.size.height/3)
    ballBlue.zPosition = 100
    ballBlue.physicsBody = SKPhysicsBody(circleOfRadius: 25)//need this so the ball can be affected by physics
    ballBlue.physicsBody?.affectedByGravity = true //ball will be affected by gravity determined by the scene's physics
    ballBlue.physicsBody?.restitution = 1 // sets bounciness of ball
    ballBlue.physicsBody?.linearDamping = 0 //used to set how air resistence will affect ball
    ballBlue.physicsBody?.categoryBitMask = PhysicsCatagory.BlueBall
    ballBlue.physicsBody?.collisionBitMask = PhysicsCatagory.OrangeBall | PhysicsCatagory.PokeBall | PhysicsCatagory.Border
    ballBlue.physicsBody?.contactTestBitMask = PhysicsCatagory.None

    self.addChild(ballBlue)

    ballOrange.name = "ballOrange"
    ballOrange.size = CGSize(width: 50, height: 50)
    ballOrange.anchorPoint = CGPoint(x:0.5, y:0.5)
    ballOrange.position = CGPoint(x: self.frame.size.width*0.75, y:self.frame.size.height/2)
    ballOrange.zPosition = 100
    ballOrange.physicsBody = SKPhysicsBody(circleOfRadius: 25)//need this so the ball can be affected by physics
    ballOrange.physicsBody?.affectedByGravity = true //ball will be affected by gravity determined by the scene's physics
    ballOrange.physicsBody?.restitution = 1 // sets bounciness of ball
    ballOrange.physicsBody?.linearDamping = 0 //used to set how air resistence will affect ball
    ballOrange.physicsBody?.categoryBitMask = PhysicsCatagory.OrangeBall
    ballOrange.physicsBody?.collisionBitMask = PhysicsCatagory.BlueBall | PhysicsCatagory.Border
    ballOrange.physicsBody?.contactTestBitMask = PhysicsCatagory.PokeBall

    self.addChild(ballOrange)

  }

  override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    //Finds the position where user touches screen
    for touch: AnyObject in touches {

      let positionOfTouch = touch.location(in: self)

      //drags ball to where user touches screen
      let dragBallAction = SKAction.move(to: CGPoint(x: positionOfTouch.x, y: positionOfTouch.y), duration: 0.5)
      ballOrange.run(dragBallAction)

    }

  }

  func didBeginContact(contact: SKPhysicsContact) {

    print("contact")

    var contactBody1: SKPhysicsBody
    var contactBody2: SKPhysicsBody

    if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {

      contactBody1 = contact.bodyA
      contactBody2 = contact.bodyB
    }
    else// else almost never gets called but still add it to function

    {
      contactBody1 = contact.bodyB
      contactBody2 = contact.bodyA
    }

    //this uses the catagories set up in above struct (1 = Square, 2 = Ball)
    if ((contactBody1.categoryBitMask == 1) && (contactBody2.categoryBitMask == 3)) {

      //if the ball contact the square, remove the ball
      contactBody2.node!.removeFromParent()

    }

  }

}

A: I had that same problem and because I'm not too familiar with how ContactA and ContactB works, I gave each object a name and check if those two objects collide like so.
func didMoveToView(view: SKView) {

       objectA = self.childNodeWithName("ObjectA") as! SKSpriteNode!
       objectB = self.childNodeWithName("ObjectB") as! SKSpriteNode!
}

 func didBeginContact(contact: SKPhysicsContact) {

        let contactA: SKPhysicsBody = contact.bodyA
        let contactB: SKPhysicsBody = contact.bodyB

        let nodeA = contactA.node as! SKSpriteNode
        let nodeB = contactB.node as! SKSpriteNode

        if nodeA.name == "ObjectA" && nodeB.name == "ObjectB" {

               //do something
        }

    }

A: Read my answer on this question SpriteKit - Making certain SpriteNodes NOT collide without disabling their physics bodies which describes the difference between collisions and contacts.
Also try implementing my checkPhysics() function (source is in the same answer) which will analyse your scene and list which nodes collide with which other nodes and also which nodes notify when contacting other nodes.
The output will be something like this for a physicsDemo I have with 4 SKSPriteNodes called shape_blueSquare, shape_redCircle, shape_purpleSquare, shape_greenRect & shape_yellowTriangle and a border around the screen called "Screen_edge".
Optional("shape_blueSquare") collides with Optional("Screen_edge")
Optional("shape_blueSquare") collides with Optional("shape_redCircle")
Optional("shape_blueSquare") collides with Optional("shape_purpleSquare")
Optional("shape_blueSquare") collides with Optional("shape_greenRect")
Optional("shape_redCircle") collides with Optional("Screen_edge")
Optional("shape_redCircle") collides with Optional("shape_blueSquare")
Optional("shape_redCircle") notifies when contacting Optional("shape_purpleSquare")
Optional("shape_redCircle") collides with Optional("shape_greenRect")
Optional("shape_redCircle") notifies when contacting Optional("shape_greenRect")
Optional("shape_purpleSquare") collides with Optional("Screen_edge")
Optional("shape_purpleSquare") collides with Optional("shape_greenRect")
Category for Optional("shape_greenRect") does not appear to be set correctly as 4294967295
ptional("shape_greenRect") collides with Optional("Screen_edge")
Optional("shape_yellowTriangle") collides with Optional("Screen_edge")
Optional("shape_yellowTriangle") notifies when contacting Optional("shape_redCircle")
Optional("shape_yellowTriangle") collides with Optional("shape_greenRect")
Optional("shape_yellowTriangle") notifies when contacting Optional("shape_greenRect")

A: the property that detects collision is contact test bit mask that is why its just passing through i think you have collision bit mask and contact test bit mask confused with each other
contact test is what detects contact while collision bit mask allows bodies to pass through each other


text:
Q: C# save System.Drawing.Graphics to .png I tried with the graphics.Save();
Graphics newImage = Graphics.FromImage(bmp2);
newImage.DrawImage(bmp, 87, 37, 0, 0);
newImage.Save();

but when i try to set the file name like in the Image.Save(@"HereGoesName.PNG"); method i get an error saying "No overload for the method 'Save' takes 1 arguments)"
and everywhere i searched says to do the following
 Bitmap bitmap = new Bitmap(Convert.ToInt32(1024), Convert.ToInt32(1024), System.Drawing.Imaging.PixelFormat.Format32bppArgb);
 Graphics g = Graphics.FromImage(bitmap);
 bitmap.Save(@"HereGoesName.PNG", ImageFormat.Png);

From what i understand this is to create a graphics from a bitmap in here and i am trying to do the oposite.

A: You need to call Save on the bitmap, not the graphics:
Graphics newImage = Graphics.FromImage(bmp2);
newImage.DrawImage(bmp, 87, 37, 0, 0);
bmp2.Save("HereGoesName.PNG", ImageFormat.Png);

A: This is simple: Your line Graphics newImage = Graphics.FromImage(bmp2); creates a graphics object referring to bmp2 image.
All drawing actions draw direct on your bmp2 Bitmap
So you can simply save your modified image with:
bmp2.Save(@"foo.png", ImageFormat.Png);


text:
Q: Strange dates in plotting graph in Julia I get some strange result when I try plotting a DataFrame.
When I plot the starting graph it works great.
using DataFrames, XLSX, StatsPlots, Indicators

df = DataFrame(XLSX.readtable("Demo-sv.xlsx", "Blad3")...)
df[!, :Closeprice] .= Float64.(df.Closeprice)

Example of the data
1×2 DataFrame
│ Row │ Date       │ Closeprice │
│     │ Any        │ Float64    │
├─────┼────────────┼────────────┤
│ 1   │ 2019-05-03 │ 169.96     │

Then I plot the data
@df df plot(df.Date, df.Closeprice)

But when I try to add a new plot (a simple moving average (sma())), I get some really strange result. The dates isn't correct anymore, and the graph looks weird. I don't know if my new plot is somehow overwriting the original even if it should add to the existing plot?
I have tried to use both functions down below to add the new plot, but both gives the same result.
plot!(sma(df.Closeprice, n=200))
plot!(sma(sort(df, :Date).Closeprice, n=200))

But I have gotten the same result, where the graph just looks strange. And I don't know what is causing this problem.

A: The reason is because you are plotting your new plot vs the date starting from Date(1) which is 0001-01-01.
You need to plot plot!(df.Date, sma(df.Closeprice, n=200)).
By the way, calling the entry Date is not best practice, as Date is already the name of the DataType.


text:
Q: Updating connection string to LDAP with NHibernate and Oracle I've inherited an app that uses NHibernate and FluentNibernate to connect to an Oracle database. Unfortunately, I have no experience with NHibernate. The current connection string is like so:
Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=hostname)(PORT=0000)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=servicename)));User Id={username};Password={password};

but now needs to switch over to LDAP (see the last code snippet).
My question, is it possible to make a change only to the web.config with an LDAP connection or will I need to add the Oracle.ManagedDataAccess and make some code changes?
It is my understanding that OracleClientConfiguration has been deprecated based on this page hence the part of the question about a new nuget package. Another note, there isn't a hibernate.cfg.xml file within the project (which I think is ok?) but wondering if this project isn't using the best practices for NHibernate. Any other hints or tips would be appreciated.
C# code:
private ISessionFactory GetSessionFactory()
{
      var connectionString = LoginHelper.GetConnectionString(ConnectionStringSetting, LoginInfoSetting);

      var iSessionFactory
         = Fluently
            .Configure()
            .Database(OracleClientConfiguration.Oracle10.ConnectionString(connectionString))
            .Mappings(e => e.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly()))
            .BuildSessionFactory();

      return iSessionFactory;
}

Web.config (there no other references to NHibernate in the Web.config. There are some references to dependentAssembly in other dll.config files):
<configuration>
   <configSections>
      <section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
   <configSections>
<configuration>

What I (think I) need in the Web.config is something like so:
<oracle.dataaccess.client> <!-- or <oracle.manageddataaccess.client>? -->
  <version number="*">
      <LDAPsettings>
         <LDAPsetting name="DIRECTORY_SERVERS" value="" />
         <LDAPsetting name="DIRECTORY_SERVER_TYPE" value="" />
         <LDAPsetting name="DEFAULT_ADMIN_CONTEXT" value="" />
      </LDAPsettings>
      <settings>
         <setting name="NAMES.DIRECTORY_PATH" value="" />
         <setting name="LDAP_ADMIN" value="" />
      </settings>
   </version>
</oracle.dataaccess.client>

EDIT 1:
Contents of ldap.ora file:
DIRECTORY_SERVERS=(ldap:XXX)
DEFAULT_ADMIN_CONTEXT="dc=Oracle,dc=com"
DIRECTORY_SERVER_TYPE=ad

A: Here is what I did in order to get this to work...
In the Oracle folder structure, navigate to the Network folder.
Add the following files (should be able to copy and paste another folder down called Sample):

*

*sqlnet.ora

*ldap.ora

*tnsnames.ora

sqlnet.ora (the key here was adding LDAP to the beginning of the list):
SQLNET.AUTHENTICATION_SERVICES= (NTS)
NAMES.DIRECTORY_PATH= (LDAP, TNSNAMES, EZCONNECT)

ldap.ora:
DIRECTORY_SERVERS=(ldap:XXX:XXX)
DEFAULT_ADMIN_CONTEXT="dc=oracle,dc=com"
DIRECTORY_SERVER_TYPE=XX

tnsnames.ora:
No change was required; left as default

Connection string:
<add name="connection" connectionString="Data Source=YourDataSource"/>
<!-- might need to add a username/password -->

A: According documentation it should be this:
<LDAPsettings>
  <LDAPsetting name="DIRECTORY_TYPE" value="AD" />
  <LDAPsetting name="DEFAULT_ADMIN_CONTEXT" value="dc=Oracle,dc=com"/>
</LDAPsettings>

Or use
<settings>
  <setting name="TNS_ADMIN" value="C:\oracle\work"/>
</settings>

and specify LDAP settings in C:\oracle\work\ldap.ora file (in conjunction with C:\oracle\work\sqlnet.ora file).
I don't think it is still valid but have a look at ODP.NET Managed library does resolve alias, but 32-bit library does
You can modify the config file with a simple text editor or use the config tool OraProvCfg.exe. Would be like this:
OraProvCfg.exe /action:config /product:odpm /frameworkversion:v4.0.30319 /providerpath:C:\oracle\product\12.1\Client_x64\odp.net\managed\common\Oracle.ManagedDataAccess.dll /set:settings\TNS_ADMIN:C:\oracle\network\admin

OraProvCfg.exe /action:config /product:odpm /frameworkversion:v4.0.30319 /providerpath:C:\oracle\product\12.1\Client_x64\odp.net\managed\common\Oracle.ManagedDataAccess.dll /set:LDAPsettings\DIRECTORY_TYPE:ad

Note, you have a OraProvCfg.exe for 32-bit (x86) and for 64-bit. Run the one which matches to your application, (or simply run both).


text:
Q: C++ Reverse sequence of elements in a vector Hello I'm still new to C++ and I am writing a program to reverse the elements in a vector. I don't get any errors running the program but when I run it and I enter the numbers my program prints " Printing ... end of print" then it just closes on its own. I sure it may be a simple mistake.
using namespace std;

vector<int> reverse_a(const vector<int>&veca)
{
vector<int> vecb;
//size_t as the index type
size_t i = veca.size();
while ( i > 0 )
    vecb.push_back(veca[--i]);
return vecb;
}

void print(const vector<int> vec)
{
     cout << "printing " << endl;
     for (size_t i = 0; i < vec.size(); ++i)
         cout << vec[i] << ",";
     cout << "\n" << "\n end of print.\n";
}

int main(void)
{
    vector<int>veca;
    vector<int>vecb;
    int input;
    while(cin >> input)
              veca.push_back(input);

    reverse_a(veca);
    print(vecb);

}

A: Sort of off topic, but can't be explained in a comment. Aderis's answer is correct and πάντα ῥεῖ brings up an alternative for OP.
As with most intro to programming problems, the standard Library has done all of the work already. There is no need for any function because it already exists, in a somewhat twisted form:
std::copy(veca.rbegin(), veca.rend(), std::back_inserter(vecb));

std::copy does just what it sounds like it does: it copies. You specify where to start, where to stop, and where to put the results.
In this case we want to copy from veca, but we want to copy backwards, so rather than calling begin like we normally would, we call rbegin to get one of those reverse iterator thingys πάντα ῥεῖ was talking about. To define the end, we use rend which, rather than tearing things limb from limb marks the end of the reverse range of veca. Typically this is one before the beginning, veca[-1], if such a thing existed.
std::back_inserter tells std::copy how to place the the data from veca in vecb, at the back.
One could be tempted to skip all of this reverse nonsense and
std::copy(veca.begin(), veca.end(), std::front_inserter(vecb));

but no. For one thing, it would be hilariously slow. Consider veca = {1,2,3,4,5}.  You'd insert 1 at the beginning of vecb, then copy it to the second slot to make room for 2. Then move 2 and 1 over one slot each to fit in 3. You'd get the nice reverse ordering, but the shuffling would be be murderous. The second reason you can't do it is because vector does not implement the push_front function required to make this work, again because it would be brutally slow.
Caveat:
This approach is simple, but slow. The back_inserter may force resizing of the vector's internal array, but this can be mitigated by preallocating vecb's storage.

A: It's just a simple mistake. You are forgetting to set vecb to the result of the reverse_a function in main. Instead of reverse_a(veca);, you should have vecb = reverse_a(veca);. The way you currently have it, vecb never gets set and therefore has a length of zero and nothing prints.


text:
Q: Symfony/Twig how to render a Route set by anotation? Let's say I have this code in a controller:
<?php

namespace Foo\BarBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration as Mvc;

/**
 * @Mvc\Route("/foo/bar")
 */
class TestController extends Controller
    /**
     * @Mvc\Route("/test/{id}", requirements={"id" = "[0-9]{1,6}"})
     * @Mvc\Template
     *
     * @return view
     */
    public function testAction($id)
    {
        return array('test' => $id);
    }
}

How can I link to this route in a twig template? Usually I can just call
{{ path('route_name', {'paramkey': 'paramvalue'}) }}

But here I have no name to call. Same thing, how would I call it in a controller (for a redirect)?
Thanks.

A: When you omit the name it's being autogenerated for you.
The autogenerated name is a lowercase concatenation of bundle + controller + action. For example, if you have:

*

*Bundle AppBundle

*Controller MyController

*Action: testAction()
the name would be app_my_test.
You can list all routes using Terminal:
php app/console router:debug

All routes' names, including those autogenerated, will be there.
Hope this helps...


text:
Q: Dynamic memory allocation for node in linked list Why when i have to declare a pointer to a node (head) I also have to allocate memory with malloc or calloc for it? I saw that the code that generate a list (not imported here) works well also without allocate memory for it and just declaring node *head.
typedef struct str_node{
    int data;
    struct str_node *next;
}node;

int main(){

    node *head;

    head = (node*) malloc(sizeof(node));
    head = NULL;

And why when I allocate memory like above i have to write (node*)? Isn't it already allocated to a struct node since I'm doing it on head? What is the meaning of that line of code exactly? Moreover when I write head = NULL am I set the address of the pointer head to NULL or what?

A: This code snippet
node *head;

head = (node*) malloc(sizeof(node));
head = NULL;

produces a memory leak.
At first a memory for an object of the type node was allocated and its address was assigned to the pointer head
head = (node*) malloc(sizeof(node));

and then at once the value of the pointer was overwritten.
head = NULL;

As a result the address of the allocated memory was lost and the allocated memory can not be freed.
The code snippet does not make any sense. It will be enough to write
node *head = NULL;

In this case you will initially have an empty list.

And why when I allocate memory like above i have to write (node*)?

The function malloc  returns a pointer of the type void *. A pointer of the type void * can be assigned to a pointer of any other object type. So in C the casting is redundant.
In C++ you have explicitly to cast a pointer of the type void * to the type of the object pointer to which the pointer of the type void * is assigned.

Moreover when I write head = NULL am I set the address of the pointer
head to NULL or what?

You did not set the address of the pointer itself. The pointer was allocated by the compiler and has the automatic storage duration. You set the value of the variable head that has the type node * to NULL.

A: In C, pointers are values, just like integers. When you write:
int a;
a = 3;

you store the value 3 into the variable a.
When you write:
int* p;
p = NULL;

you store the value NULL into the variable p. There is nothing special about pointers. The assignment does not in any way depend on the value of p, i.e. what it might or might not point at. (In this case, it points at nothing, but that's irrelevant.)
malloc returns a pointer to a memory region, which as discussed above is a value. The pointer has no intrinsic metadata; malloc does not require any information beyond the size of the memory region. In particuar, it does not know (or care) what the memory region will be used for. Once that value is produced, you can deal with it as you see fit, for example:
int* p;
p = malloc(sizeof *p);

Since p is declared as a pointer to an int, it is expected that the memory pointed at by p can hold an int. (It doesn't, yet, but it could.) But you can pass around the pointer (as a value) without it having any effect on the integer (if any) stored in the memory pointed to. For example, after
int* q = p;

q and p point at the same memory.
If you find any of this confusing, it is probably because you are expecting a pointer to be something other than a simple value. However, they are simple values and you need a mental model which is based on that simple reality.

A: Malloc is used to allocate a block of memory of the specified size i.e. in this case it is (sizeof(node)) which is an 'item' in the linked list. This can be used to allow your linked list to grow.
(node*) is used to allocate the type of memory.
Example from GeeksForGeeks
I recommend reading this https://www.geeksforgeeks.org/dynamic-memory-allocation-in-c-using-malloc-calloc-free-and-realloc/
It will explain some of the fundamentals.
Finally to answer this "Why when i have to declare a pointer to a node (head) I also have to allocate memory with malloc or calloc for it?".
A pointer points the compiler towards a memory address so when you declare a section of memory using malloc you need to point towards the start of that memory so you can access it (Hence why you need to specify the size so you know how far to read/write).


text:
Q: The complement of a cartesian product and the product topology I tried to prove that for topological spaces $X_{\alpha}, \alpha \in A$ for the product space $\prod_{\alpha} X_{\alpha}$ with the usual product topology if $A_{\alpha} \subseteq X_{\alpha}$ for all $\alpha \in A$, then
$$
 \overline{ \prod_{\alpha} A_{\alpha} } = \prod_{\alpha} \overline{ A_{\alpha} }
$$
where $\overline A_{\alpha}$ denotes the closure of $A_{\alpha}$. My proof relies on the axiom of choice, I will append it. But meanwhile there came another issue up my mind. Showing that $\prod_{\alpha} \overline{A_{\alpha}}$ is closed by establishing that its complement is open. But that means that it is a union of sets $\prod_{\alpha} U_{\alpha}$ with $U_{\alpha} \ne X_{\alpha}$ for only finitely many open subsets $U_{\alpha}$ of $X_{\alpha}$, more formally
$$
 \left[ \prod_{\alpha} \overline A_{\alpha} \right]^C = \bigcup_{i \in I} B_i
$$
where each $B_i = \prod_{\alpha} U^{(i)}_{\alpha}$ with $U_{\alpha}^{(i)} \ne X_{\alpha}$ for just finitely many $\alpha$. A first idea might be
$$
  \left[ \prod_{\alpha} \overline A_{\alpha} \right]^C = \bigcup_{J \subseteq A, J \mbox{ finite}} B_J
$$
where $B_J = \prod_{\alpha} U_{\alpha}$ with $U_{\alpha} = \overline{A_{\alpha}}^C$ if $\alpha \in J$ and $U_{\alpha} = X_{\alpha}$ otherwise. But I think this is not working for if
$$
 x \in \prod_{\alpha} \overline{A_{\alpha}}^C
$$
(i.e. $x \notin \overline A_{\alpha}$ for all $\alpha \in A$, might be expressed as $x \in B_J$ with $J = A$) then $x \notin \prod_{\alpha} \overline{A_{\alpha}}$, but it is not in any $B_J$ for $J$ a finite subset of $A$. So my question, is there any way to write
$$
 \prod_{\alpha} \overline A_{\alpha}
$$
as a union of open sets in the product topology? (surely it must be the case, but is there a way to explicitly give a formula for that)
For completeness, my proof of
$$
\overline{ \prod_{\alpha} A_{\alpha} } = \prod_{\alpha} \overline{ A_{\alpha} }.
$$
Let $x \in \prod_{\alpha} \overline A_{\alpha}$ and let $U$ be an open basis set around $x$, i.e.
$$
 U = \prod_{\alpha} U_{\alpha}
$$
with finitely many open subsets $U_{\alpha} \ne X_{\alpha}$ and the rest $U_{\alpha} = X_{\alpha}$ and $x \in U$. Then because $x_{\alpha} \in U_{\alpha}$
for all $\alpha \in A$ and $x_{\alpha} \in \overline{A_{\alpha}}$ it is $U_{\alpha} \cap A_{\alpha} \ne \emptyset$ for all $\alpha \in A$. Therefore by the axiom of choice the set
$$
 \prod_{\alpha} (U_{\alpha} \cap A_{\alpha})
$$
is nonempty and so
$$
 U \cap \prod_{\alpha} A_{\alpha} = \prod_{\alpha} U_{\alpha} \cap \prod_{\alpha} A_{\alpha} = \prod_{\alpha} (U_{\alpha} \cap A_{\alpha})
$$
is nonempty too, and therefore $\overline{ \prod_{\alpha} A_{\alpha} } = \prod_{\alpha} \overline{ A_{\alpha} }$.

A: If we denote projections by
\begin{align}
p_\alpha\colon \prod_\beta X_\beta&\to X_\alpha\\
x&\mapsto x_\alpha,
\end{align}
then
$$\prod_\alpha\overline{A_\alpha}=\bigcap_\alpha p_\alpha^{-1}[\overline{A_\alpha}],$$
which shows that it is closed and hence already proves
$$\prod_\alpha\overline{A_\alpha}\supset\overline{\prod_\alpha A_\alpha}.$$
Taking complements we obtain
$$\prod_\alpha X_\alpha\setminus\prod_\alpha\overline{A_\alpha}=\bigcup_\alpha p_\alpha^{-1}[X_\alpha\setminus\overline{A_\alpha}],$$
which explicitly writes the complement as a union of sets which are elements of the usual subbasis of the product.


text:
Q: Using unnest_tokens() to split a column by a specific character? I'm working with a column of vectors of urls formatted as a string with each url separated by a comma:
column_with_urls
["url.a, url.b, url.c"]
["url.d, url.e, url.f"]
I would like to use the tidytext::unnest_tokens() R function to separate these out into one url per line (although I'm open to other preferably R based solutions). I've read the docs here but I can't tell if it's possible/advisable to enter a single character to split on.
My thought is something like unnest_tokens(url, column_with_urls, by = ','). Is there a way to specify that kind of argument and/or a better way to solve this problem?
My desired output is a dataframe with one url per row like this (and all other data for the original rows copied over to each row):
url
url.a
url.b
url.c
...
Thanks in advance.

A: The unnest_tokens function has an option for you to split on a regex pattern.  Below is the example syntax to split on a comma using this option (you could also use it for more complex patterns).
Note that this will convert the class of your input data to a tibble
my_df = data.frame(id=1:2, urls=c("url.a, url.b, url.c",
                                  "url.d, url.e, url.f"))
tidytext::unnest_tokens(my_df, out, urls, token = 'regex', pattern=",")
# # A tibble: 6 × 2
#     id    out
#   <int>  <chr>
# 1     1  url.a
# 2     1  url.b
# 3     1  url.c
# 4     2  url.d
# 5     2  url.e
# 6     2  url.f


text:
Q: Can't transform Linq to IEnumerable I have this method on my DAL class:
public IEnumerable<Pedidos> Pedidos_Listar()
    {
        using (var context = new OhmioEntities())
        {
            var _ped =
                from Pedidos in context.Pedidos
                where Pedidos.ID_Cliente == 1
                select new {Pedidos.ID_Pedido, Pedidos.Fecha, Pedidos.Clientes};
            return _ped.ToList();
        }
    }

And VS give this error:
    Error   3   No se puede convertir implícitamente el
tipo 'System.Collections.Generic.List<AnonymousType#1>'
en 'System.Collections.Generic.IEnumerable<Ohmio.ModelLayer.Pedidos>'.
Ya existe una conversión explícita (compruebe si le falta una conversión)

What i'm I doing wrong here?Thanks
EDIT
More info: Pedidos is defined as POCOs db class
So This work just fine:
public IEnumerable<Pedidos> Pedidos_Listar()
        {
            using (var context = new OhmioEntities())
            {
                return context.Pedidos.ToList();
            }
        }

But i need to use linq to select just some field and a where clause.
When I try this as suggested:
public IEnumerable<Pedidos> Pedidos_Listar()
        {
            using (var context = new OhmioEntities())
            {
                var _ped =
                    from Pedidos in context.Pedidos
                    where Pedidos.ID_Cliente == 1
                    select new Pedidos {Pedidos.ID_Pedido, Pedidos.Fecha, Pedidos.Clientes};
                return _ped.ToList();
            }
        }

I get this error:
    Can't inicialize type 'Ohmio.ModelLayer.Pedidos' with a colection inicializer because
don't implement 'System.Collections.IEnumerable' (Manual translate)

I'm i missing something here? Thanks!

A: You are creating a list of anonymous objects.If you want a strongly-typed collection change your code like this:
 var _ped = from p in context.Pedidos
            where p.ID_Cliente == 1
            select new Pedidos
            {
                ID_Pedido = p.ID_Pedido,
                Fecha = p.Fecha,
                Clientes = p.Clientes
            };

A: You're not returning the type you said you would. You're returning an anonymous type. Fix this by projecting into the known type:
public IEnumerable<Pedidos> Pedidos_Listar()
    {
        using (var context = new OhmioEntities())
        {
            var _ped =
                from Pedidos in context.Pedidos
                where Pedidos.ID_Cliente == 1
                select new Pedidos {Id = Pedidos.ID_Pedido, Fecha = Pedidos.Fecha, Clientes = Pedidos.Clientes};
            return _ped.ToList();
        }
    }

Or if you don't need the projection and are returning the EF model directly:
public IEnumerable<Pedidos> Pedidos_Listar()
    {
        using (var context = new OhmioEntities())
        {
            var _ped =
                from Pedidos in context.Pedidos
                where Pedidos.ID_Cliente == 1
                select Pedidos;
            return _ped.ToList();
        }
    }

Or simply:
public IEnumerable<Pedidos> Pedidos_Listar()
    {
        using (var context = new OhmioEntities())
        {
            return context.Pedidos.Where(p => p.ID_Cliente == 1);
        }
    }

A: I think you are looking for this:
select Pedidos;

Instead of this:
select new {Pedidos.ID_Pedido, Pedidos.Fecha, Pedidos.Clientes};

If this is Linq-to-entites, you can't project to an entity class, so this wouldn't work:
select new Pedidos { ... }

However, you can project to a new class like
select new PedidosCustomClass { ... }

A: Your select is selecting a new anonymous type, but you're trying to return that anonymous type as instances of Pedidos. You need to change your select to create instances of Pedidos, instead.

A: You're attempting to return an collection of anonymous objects.
You'll need to name your object in your select to Pedidos:
select new Pedidos { ID_Pedido = Pedidos.Id_Pedido,
                     Fecha     = Pedidos.Fecha,
                     Clientes  = Pedidos.Clientes };

A: You are creating a list of anonymous objects and then trying to return it as list of Pedidos. the compiler doesn't know how to do the casting. You can either change it to:
public IEnumerable<Pedidos> Pedidos_Listar()
{
    using (var context = new OhmioEntities())
    {
        var _ped =
            from Pedidos in context.Pedidos
            where Pedidos.ID_Cliente == 1
            select new Pedidos;
        return _ped.ToList();
    }
}

Or you will have to do the maping/casting yourself. Something like this will work:
public IEnumerable<Pedidos> Pedidos_Listar()
{
    using (var context = new OhmioEntities())
    {
        var _ped =
            from P in context.Pedidos
            where P.ID_Cliente == 1
            select new Pedidos { ID_Pedido = P.ID_Pedido,
                                 Fecha = P.Fecha,
                                 Clientes = P.Clientes};
        return _ped.ToList();
    }
}

A: Cause of the original error you got already explained by @Selman22. But the solution causes another error because you can't create mapped entity (your POCOs db class) in LINQ-to-entity query. To workaround this, try to initialize the entity in client side (outside LINQ-to-entity query) :
public IEnumerable<Pedidos> Pedidos_Listar()
{
    using (var context = new OhmioEntities())
    {
        var _ped =
            (
                from Pedidos in context.Pedidos
                where Pedidos.ID_Cliente == 1
                select new {Pedidos.ID_Pedido, Pedidos.Fecha, Pedidos.Clientes}
            ).ToList();
        return _ped.Select(o => new Pedidos
                                {
                                    ID_Pedido = p.ID_Pedido,
                                    Fecha = p.Fecha,
                                    Clientes = p.Clientes
                                });
    }
}

A: Why do you want to instanciate new Pedidos?
Try simply this:
public IEnumerable<Pedidos> Pedidos_Listar()
{
    using (var context = new OhmioEntities())
    {
        return context.Pedidos
            .Where(p => p.ID_Cliente == 1)
            .AsEnumerable();
    }
}


text:
Q: How to write the following code with less lines So i have 2
 's with 3
's on each. I want to change the color of a specified
 on the second
 when I hover over a specified
 on the first
. And when I do not hover the element, I want the format to change back to normal. Here is my code:

So my question is, how can I perform the above with less code? Ive tried some toggle/add,remove methods but I could not get it to work. The code above does work, but I feel like it can be performed with less lines of code. Thank you.

A: You could use .index since your class names are all the same besides the number and add/remove a class:
JS
$(".a").find("li").hover(function(){
   var index = $(this).index()+1;
    $(".b"+index).addClass("active")
}, function(){
    $(".b").find("li").removeClass("active")
});

CSS
.active{
   color: red;
   font-size: 19px;
}

FIDDLE
UPDATE
I saw your comment about the class names just being an example, I adjusted my code still using .index() this way the class name of li is irrelevant and it will highlight the corresponding li in the same position of ul.b UPDATE I switched to James Gaunt's suggestion of eq() AND StevenL's to use .toggleCLass. I like both of those better than using nth-of-type() and a hover out function:
$(".a").find("li").hover(function(){
   var index = $(this).index();
   $(".b").find("li").eq(index).toggleClass("active");
});

NEW FIDDLE

A: at lease, you can 'extract code' for css and 'make the chain call' for js:
origin js
$(".a1").mouseover(function(){
    $(".b1").css({"color":"red","font-size":"19px"});
});
$(".a1").mouseout(function(){
    $(".b1").css({"color":"#045491","font-size":"16px"});
});

to new js:
$(".a1").mouseover(..).mouseout(...);

change your origin css code:
mouse_over_style = {"color":"red","font-size":"19px"}
mouse_out_style = {"color":"#045491","font-size":"16px"}

then change your js to:
$('.b1').mouseover(mouse_over_style).mouseout(mouse_out_style)


text:
Q: Azure AD - Multi-Tenant with Daemon Service and Authorization Code Grant flow, can a target tenant generate a client_secret? I am working with Azure AD through OAuth 2.0 protocol and also creating a Service/ Dameon application to handle the authentication process for Microsoft Graph SDK. For the service/daemon, I make a HttpWebRequest and pass along the client_id and client_secret to generate an access_token where I then can supply to the Microsoft Graph SDK.
I also have successfully created a corresponding service principal to the target tenant, in which an admin has granted permissions to the application using the authorization code grant flow. The application then shows in Overview -> Quick tasks -> Find an enterprise app, within the (portal.azure.com).
My question is there an approach where I can leverage the service/daemon approach while also allowing an admin from the target tenant to authorize the application, that would allow the target tenant to create a client_secret to pass which would be unique to that tenant?

A: Short answer is no. When an admin consents your multi-tenant app:

*

*A Service Principal is created for it in their tenant

*Permissions requested by the app are granted in that tenant

This means your app can now authenticate with its client credentials (id + secret) against their tenant as well. So the same keys work in all approved tenants.
What that means is your app is free to get an access token for any of them at any given time, no matter who is signed in. So it puts some responsibility to your app to keep data separated.
If you get an access token from https://login.microsoftonline.com/company.com/oauth2/token, the resulting token will contain that tenant's identifier. And APIs like the Microsoft Graph API will only give you data for that tenant with that token. So your app must make sure to only use a token that has a tenant id equal to the user's tenant id claim.

A: I would say that juunas' answer is 99% correct.  The short answer is basically no, and the considerations he mentions are also solid.
But I believe that this would be technically possible under certain considerations.  When the admin consents to your daemon service, a service principal is created in your customer's tenant. Service principals do allow addition of credentials that can be used as client secrets on a per-tenant basis. The thing is, there's not really a way to add a credential to a service principal programmatically from your app. You would have to get an administrator to run some script to add the new credential to their tenant's service principal.
Even if you went through all this, you would need to make sure that your service is also isolated on a customer/tenant basis.  Security-wise, it's sort of pointless to create per-tenant client secrets if your singular daemon has access to all of the secrets.


text:
Q: Algorithm to make fewest triangles given points in 3d With a set of points in 3d. How would one go about finding the fewest set of triangles connecting those points; creating a set of triangles all sharing at least two of their sides? (like a square sheet with bumps in it made of triangles)
example points for a 5x100x500 area:
points = [
    # Constant Points
    (0  , 0  , 0  ),
    (0  , 100, 0  ),
    (5  , 100, 500),
    (1  , 50 , 100),
    (2  , 60 , 200),
    (3  , 75 , 300),
    (4  , 80 , 400),
    (5  , 0  , 499),
]

Here's what the points plotted would look like with the axes normalized:

A: I think Delaunay Triangulation might give you what you require:
http://en.wikipedia.org/wiki/Delaunay_triangulation


text:
Q: Cant reverse an array of integers using nested for loops I have searcher over internet for the answers. Most of them are using temp for reversing the integers. But I want to do it by using nested for loops. Maybe you can find this question useless. But I need help. So please... Help me!!
public static void main(String[] args) {
    int[] list1= {1, 2, 3, 4};
    int[] list2 = {7, 8, 9, 0};
    int[] list3 = revv(list1);
    int[] list4 = revv(list2);
    System.out.println(list4);
    System.out.println(list3);

}

public static int[] revv(int[] arr) {
    int[] arr2 = null;

    for(int i = 0; i < 4; i++){
        for(int j = arr.length; j>= 0; j--){
            arr[j] = arr2[i];
        }
    }
    return arr2;

}

A: Your method should look like the following. there is no need for a nested loop here.
public static int[] revv(int[] arr) {
    int[] arr2 = new int[arr.length];

    for (int i = 0 ; i < arr.length ; i++) {
        arr2[i] = arr[arr.length - i - 1];
    }

    return arr2;
}

Advice
To print an array, use Arrays#toString()
System.out.println(Arrays.toString(list3));


text:
Q: IBM Cloud Code Engine: How to overwrite environment variable in cron-invoked job run? When working with jobs in IBM Cloud Code Engine, I would submit a jobrun for the actual invocation. For the jobrun I can specify environment variables to be passed into the runtime environment (--env FOO=BAR).
How can I do the same when using a cron subscription to trigger the job, i.e., to set FOO=BAR?

A: I believe the correct flag to pass to the CLI is the --ext or --extension.
% ibmcloud ce subscription cron create --
NAME:
  create - Create a cron event subscription.

USAGE:
  create --name CRON_SOURCE_NAME  --destination DESTINATION_REF [options...]

OPTIONS:
  --destination, -d value         Required. The name of the resource that will receive events.
  --name, -n value                Required. The name of the cron event subscription. Use a name that is unique within the project.
  --content-type, --ct value      The media type of the 'data' or 'data-base64' option. Examples include 'application/json',
                                  'application/x-www-form-urlencoded', 'text/html', and 'text/plain'.
  --data, --da value              The data to send to the destination.
  --data-base64, --db value       The base64-encoded data to send to the destination.
  --destination-type, --dt value  The type of the 'destination'. Valid values are 'app' and 'job'. (default: "app")
  --extension, --ext value        Set CloudEvents extensions to send to the destination. Must be in NAME=VALUE format. This option can be
                                  specified multiple times.  (accepts multiple inputs)

For example:
% ibmcloud ce subscription cron create -d application-5c -n sample-cron-sub --ext FOO=BAR
Creating cron event subscription 'sample-cron-sub'...
Run 'ibmcloud ce subscription cron get -n sample-cron-sub' to check the cron event subscription status.

% ibmcloud ce subscription cron get -n sample-cron-sub
Getting cron event subscription 'sample-cron-sub'...
OK

Name:          sample-cron-sub
ID:            xxxx
Project Name:  susan-project
Project ID:    xxxx
Age:           3m16s
Created:       2022-06-06T11:17:17-07:00

Destination Type:  app
Destination:       application-5c
Schedule:          * * * * *
Time Zone:         UTC
Ready:             true

CloudEvents Extensions:
  Name  Value
  FOO   BAR

Events:
  Type    Reason                       Age                    Source                 Messages
  Normal  PingSourceSkipped            3m17s                  pingsource-controller  PingSource is not ready
  Normal  PingSourceDeploymentUpdated  3m17s (x2 over 3m17s)  pingsource-controller  PingSource adapter deployment updated
  Normal  PingSourceSynchronized       3m17s                  pingsource-controller  PingSource adapter is synchronized

After looking at this a bit more it appears that the name=value pairs you pass in to an event subscription prepend the string 'CE_' to the name.
Therefore, to allow for this in the running job, you would need to prepend the environment variable in the job with the CE_.  For example:
When I create the jobdefinition I add the environment variable like this:
CE_FOO=BAR
Then, when I create the event subscription, for the --ext flag, I use the original suggestion: --ext FOO=BAR
I believe since the FOO variable in the event subscription automatically gets the prepended CE_ to the FOO variable it should work.
Please let me know if this does not work or I misunderstood you.


text:
Q: Mail.app mail list reply address Mail.app allows to send emails from multiple mailboxes by enumerating them in comma-delimited format in:
Preferences-Accounts-Account Information-Email Addresses = test@bar.com,test@foo.com

This feature allows you to seamlessly reply from test@foo.com whenever email was sent to this email by hitting 'Reply' button.
However when test@foo.com receives messages from some mail list list@lists.foo.com, and a message is sent to that list rather then mail address, 'Reply' will pick just a first available mail address, which would be test@bar.com.
Is there a way to specify that replies to list@lists.foo.com should be sent through test@foo.com?

A: While replying you can turn on the Reply-To header which will let you set this. You can do that by either going to the View menu and turning on Reply-To or you can do it right from within the message itself, which is easier.

Alternatively you can try changing the default preferences via the command line. Chances are the Mail defaults won't have a Reply-To header defined, but you can add the key-pair with this:
defaults write com.apple.mail UserHeaders '{"Reply-To" = "theemail@goes.here"; }'

or
defaults write com.apple.mail UserHeaders '{"Reply-To" = "theemail@goes.here"; "Bcc" = "another@address.here"; }'

If that doesn't work and you're like me and want to reverse those changes to keep preferences clean, you can edit the .plist file and remove them. The .plist can be found at:
/Users/<username>/Library/Containers/com.apple.mail/Data/Library/Preferences/com.apple.mail

I haven't tested the command line approach, but it should work because I looked this up and used that approach on a work machine once.
Hope this helps!


text:
Q: Mosfets characteristics suitable for 5V I want to use a N Mosfet for switching a device from a microcontroller (5V current and 5V signal), and a P Mosfet for giving a signal to the same microcontroller (5V signal , 12V input). (Device current draw in the order of few 100s of milliamps.
I'm having trouble in finding the specs that make the components suitable for those specific tasks. I had the following problems.
Problem 1 - With N Mosfet, this layout won't work because there is a big drop in the mosfet, and the load gets something like 2.8V.

simulate this circuit – Schematic created using CircuitLab
If I give it instead 12V, there is no longer a big drop, and it works like I intended.
Before I requested this particular component from an online seller, I tested in its simulator (MultiSIM BLUE) and even with a load of 1 Ohm, the voltage out is 4.78V.
I don't know if this is acceptable for a simulator or if I should complaint about it.

The particular Mosfet is this one.
http://eu.mouser.com/Search/ProductDetail.aspx?R=FQD7N10LTM
I solved this issue by connecting the load directly to 5V and it's ground to the mosfet and that way it works as I intended.

simulate this circuit
Anyway I would like to ask why does this happen, and how the input voltage makes a difference, and which mosfet I could buy that would solve this problem.
Problem 2 - With the P Mosfet, if I give it 5V in the source and I give it 0V in gate, it won't "open" or at least not fully, so I can't get 5V on the drain. If I use 12V instead it works as intended. Notice that I want to use the P Mosfet giving 12V in the gate to "close it" so it "passes" 5V but I'm not even in that phase, since I can't even make it work with 0V.
As for the N Mosfet, I tested the behaviour in simulator, and it worked as I intended.

This is the particular mosfet:
http://eu.mouser.com/Search/ProductDetail.aspx?R=FQB8P10TM
Now, if I do the same thing as I did for the N Mosfet, and change the load position in the circuit, the mosfet now conducts, but I only get 1.1V.
If I connect it to 12V, I get 7.70V.
So, basically, I want to work with Mosfets as logic gates but they just won't work with 5V as I intended.
My two final questions are:
How do I choose the two Mosfets for this tasks?
I the behaviour of the simulator?
Why the N Mosfet works ok I the other configuration?
If I complain to Mouser, will/should they give me replacements?
Notice that I'm talking about "Logic" but I think that I don't even have to use Logic Level Mosfets because I'm switching with the same voltage level for gate and input.
Anyway, the N Mosfet is Logic Level.
So, one more questions: is there a need of Logic Level Mosfet for some of these situations?
Post note: I talk throughout the text about using 12V for testing, it's just because that value is one that I happen to have around, and I noticed that it makes a difference for both of these mosfets.

A: A MOSFET is turned on by applying voltage between the Gate and Source. In order to fully turn on, that voltage must be well above the MOSFET's 'threshold voltage' (Gate-Source voltage that just starts to turn it on). 'Logic Level' MOSFETs are fully turned on with ~4.5V, so they can be controlled by 5V CMOS logic.
In your first circuit the Gate is shorted to the Drain, so a Gate-Source voltage sufficient to turn it on will also be the Drain-Source voltage drop. This is why you only get 2.8V at the the load (the other 2.2V is the required Gate-Source turn-on voltage). Connecting the load to +5V and the MOSFET Source to negative works because now the Gate can receive the full +5V.
To switch the high side of the load you either need to raise the Gate voltage above +5V, or invert the circuit and use a P Channel MOSFET as you did in your last example. The PMOSFET works on negative voltage, so you need to apply 0V on the Gate to turn it on, and +5V to turn it off. If you want to turn it on with a high logic level then you need to invert the signal before applying it to the Gate.
The FQB8P10TM is not a Logic Level MOSFET. Though the simulator shows it managing to turn on with only -5V, this does not take into account variations due to production spread. An individual unit may have a Gate threshold voltage as high as 4.0V, which is not high enough to ensure that it will fully turn on.
For a better idea of how Gate threshold voltage relates to turn-on voltage, look at the Gate-Source Voltage vs Drain Current transfer graph. Here you can see that below 5V the FET is just starting to turn on, and at 4.5V cannot even pass 100mA with 40V on the Drain. And Remember that this is only a 'typical' curve - it may be shifted to the right by ~1V for a unit with 4.0V threshhold voltage.


text:
Q: Can't specify Lambda alias or version for SNS subscription I've set up an SNS subscription to start up a lambda function when it get's triggered and it's all working fine, but the issue is that I can't seem to specify a version or alias of the lambda to call. Here's a screenshot of my settings:

And I followed along Using Amazon SNS for System-to-System Messaging with an AWS Lambda Function as a Subscriber - Amazon Simple Notification Service to get setup but in step 6 it talks about the "Version or Alias drop-down box", but I can't find that anywhere.
Any help appreciated.

A: So I figured out how to point the SNS to trigger a specific alias of a lambda function. In the Lambda function after you've connected up your SNS trigger you should see it in the trigger list in the designer in the lambda view as pictured below:

Hit the X on that to clear it. Next up switch to whatever alias you want to connect the SNS to. Then on the left hand list of triggers in the designer, select SNS. It should get added and tell you that configuration is required, as seen below:

Click on Configuration required and you will be brought to a Configure triggers view down the bottom. Then simply select the SNS topic you're interested in and click Add in the bottom right.
It's a bit of a round about way of getting it done, but it works!

A: In my experience with SQS, the same happens when you add a Lambda trigger to a queue; you can't set the alias or version number. However, when you add the SQS queue as a source for the Lambda to trigger on, from the Lambda console, it does work. You first select the alias or version in Lambda and after that add the source trigger. I expect the same is true for SNS.
The console is a bit asymmetrical in this sense. Hope this will be fixed soon.


text:
Q: To view all the tables in a database server Can anyone please help me with the query to list all the tables in all the databases in a single server?.
Thanks in advance.

A: Use sp_MSforeachdb to iterate through all databases and INFORMATION_SCHEMA.TABLES to query the tables in each:
sp_MSforeachdb 'USE [?]; SELECT * FROM INFORMATION_SCHEMA.TABLES'

A: AS stated here  by
Try with dynamic query
You need a query for each database against sys.tables.
select 'master' as DatabaseName,
       T.name collate database_default as TableName
from master.sys.tables as T
union all
select 'tempdb' as DatabaseName,
       T.name collate database_default as TableName
from tempdb.sys.tables as T
union all
select 'model' as DatabaseName,
       T.name collate database_default as TableName
from model.sys.tables as T
union all
select 'msdb' as DatabaseName,
       T.name collate database_default as TableName
from msdb.sys.tables as T

You can use sys.databases to build and execute the query dynamically.
declare @SQL nvarchar(max)

set @SQL = (select 'union all
select '''+D.name+''' as DatabaseName,
       T.name collate database_default as TableName
from '+quotename(D.name)+'.sys.tables as T
'
from sys.databases as D
for xml path(''), type).value('substring((./text())[1], 13)', 'nvarchar(max)')

--print @SQL
exec (@SQL)

A: IF OBJECT_ID('tempdb.dbo.#tbl') IS NOT NULL
    DROP TABLE #tbl

CREATE TABLE #tbl (
      database_id SYSNAME
    , tbl_name SYSNAME
    , sch_name SYSNAME
    , [rows] INT
)

DECLARE @SQL NVARCHAR(MAX)

SELECT @SQL = STUFF((
    SELECT '
    USE [' + d.name + ']
    INSERT INTO #tbl
    SELECT DB_NAME(), o.name, s.name, p.[rows]
    FROM sys.objects o
    JOIN sys.schemas s ON o.[schema_id] = s.[schema_id]
    LEFT JOIN (
        SELECT p.[object_id], [rows] = SUM(p.[rows])
        FROM sys.partitions p
        WHERE p.index_id < 2
        GROUP BY p.[object_id]
    ) p ON p.[object_id] = o.[object_id]
    WHERE o.[type] = ''U''
        AND o.is_ms_shipped = 0;'
    FROM sys.databases d
    WHERE d.[state] = 0
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')

EXEC sys.sp_executesql @SQL

SELECT * FROM #tbl


text:
Q: apache2 error Could not open configuration file /etc/apache2/conf.d/: No such file or directory I have just upgraded my Ubuntu 13.10 and apache2 is not working. When I try to start the apache2 server it is printing following errors:
 * Starting web server apache2
 * The apache2 configtest failed.
Output of config test was:
apache2: Syntax error on line 263 of /etc/apache2/apache2.conf: Could not open configuration file /etc/apache2/conf.d/: No such file or directory
Action 'configtest' failed.

A: When creating symbolic links make sure to use absolute paths
Instead of:
ln -s ./conf-available/mysite.conf ./conf-enabled/mysite.conf

You should use :
ln -s /etc/apache2/conf-available/mysite.conf /etc/apache2/conf-enabled/mysite.conf

A: Perform a mkdir -p /etc/apache2/conf.d/. So the folder conf.d is created. Your apache2.conf file includes all files in this folder into the configuratin, and if this folder doesn't exist it run into an error. See:
user@host:~$ grep conf.d /etc/apache2/apache2.conf
Include conf.d/

A: For me there was and invalid shortcut inside the sites-enabled folder. Once I deleted that I could easily restart/reload apache.

A: It was the same for me. After I created the conf.d folder still Apache 2 won't start. I was able to solve like this:

Replacing this line
LockFile ${APACHE_LOCK_DIR}/accept.lock

with this one
Mutex file:${APACHE_LOCK_DIR} default

in /etc/apache2/apache2.conf solved the problem.

(source)

A: Here is my full answer to the error :

*

*Restarting web server apache2                                         [fail]

*

*The apache2 configtest failed.
  Output of config test was:
  apache2: Syntax error on line 214 of /etc/apache2/apache2.conf: Could not open c                                                                             onfiguration file /etc/apache2/httpd.conf: No such file or directory
  Action 'configtest' failed.
  The Apache error log may have more information.

*

*Run command sudo mkdir conf.d

*Run command sudo touch httpd.conf

*Run command sudo vi apache2.confand replace

LockFile ${APACHE_LOCK_DIR}/accept.lock

by

Mutex file:${APACHE_LOCK_DIR} default

*Save and restart apache

Many thanks to all for you very good advice
Best regards
Dunbo

A: I also had this same problem with apache.
apache2: Syntax error on line 220 of /etc/apache2/apache2.conf: Could not open file configuration /etc/apache2/sites-enabled/000-default.conf: No such file or directory
Any consideration we are in the /etc/apache2
I solved this:
1- Knowing sites-enabled/000-default.conf is a link that points to site-available/000-default.conf, I went to check the content of sites-availables file;
And to my surprise, 000-default.conf is replaced by 000-default.conf ~ (because of gedit which always creates a backup)
2- Automatically I copy the file
$ sudo cp -v-default.conf 000 ~ 000-default.conf
3- Restart apache2
$ sudo /etc/init.d/apache2 restart
4- My server is started

A: Please use the below commands
sudo mkdir /etc/apache2/conf.d

Reinstall the packages.
Create symbolic links
ln -s /etc/websvn/apache.conf /etc/apache2/conf-available/websvn.conf

Enable the websvn configuration using below command.
sudo a2enconf websvn.conf

Enable the dav and dav_svn modules
sudo a2enmod dav
sudo a2enmod dav_svn
sudo service apache2 reload

A: I know this is an old thread, but I ran into this today and had forgotten how I fixed it a few years ago.
In addition to replacing:
LockFile ${APACHE_LOCK_DIR}/accept.lock

with
Mutex file:${APACHE_LOCK_DIR} default

in the /etc/apache2/apache2.conf file, I also had to manually create the httpd.conf file in the /etc/apache2/ directory.


text:
Q: How to run CICS on Java EE server other than websphere? I am wondering if / how I could get rid of websphere Java EE server to run an application that uses CICS to connect COBOL programs (mainly for easyness of use and to use open-source software).
CICS seems to be part of Java EE, but for instance, I can't find anyway of installing the connectors provided by IBM in Glashfish or TomEE.
Did anyone managed to run such application outside of WAS?

A: From the CICS Transaction Gateway family of products, the z/OS and Multiplatforms flavours include JCA resource adapters for Java EE-certified application servers.
Users of Java EE application servers other than those levels of WebSphere Application Server explicitly supported, need to successfully deploy the provided Install Veritifion Test (IVT) EAR file in order for support entitlement with that application server. Further details are available in the product information centers, starting with the Java EE application servers topic.
For more information on the CICS TG family of products, refer to the IBM Redbook Solution Guide: Flexible, High-Performing, Security-Rich, and Scalable Connectivity with CICS Transaction Gateway Products, available at: ibm.biz/cicstg-sg


text:
Q: Detecting when TCP connection fails to open or is terminated I am reading and writing to TCP socket via a duplex handle h.
In the client:
sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
connect sock $ addrAddress addr
h <- getSocketHandle conn

In the server:
sock <- socket (addrFamily addr) (addrSocketType addr) (addrProtocol addr)
setSocketOption sock ReuseAddr 1
withFdSocket sock setCloseOnExecIfNeeded
bind sock $ addrAddress addr
listen sock 1024
forever $ do
  (conn, _) <- accept sock
  h <- getSocketHandle conn
  forkFinally (server h) (const $ hClose h)

where:
getSocketHandle :: Socket -> IO Handle
getSocketHandle conn = do
  h <- socketToHandle conn ReadWriteMode
  hSetBinaryMode h True
  hSetNewlineMode h NewlineMode {inputNL = CRLF, outputNL = CRLF}
  hSetBuffering h LineBuffering
  return h

When both the client and the server are available, it all works fine, but when the TCP connection terminates, e.g. because the client or the server exit, nothing happens - hGetLine/hPutStrLn just block the thread.
How can I make them throw exception?
Similarly, if the client fails to connect (e.g. because of the server not responding), connect also just blocks.
I suspect I should somehow set the timeouts on the socket, but experimenting with socket options didn't change much - I tried SO_LINGER, SO_KEEPALIVE, SO_USER_TIMEOUT doesn't seem to be supported by the system (it blocks when I try to get it), SO_RCVTIMEO / SO_SNDTIMEO don't seem to be supported by Network.Socket - at least that's what the docs say...
For connect/hPutStrLn I could use timeout from System.Timeout (it seems a hack, but it will work), but for hGetLine/hGet it won't work - it can just wait for user input, so it should only throw exception when the connection terminates.
I should probably just read the network programming - I was hoping to figure it out quickly... Any help is really appreciated.
EDIT: It seems like I should be using lower level send/sendAll and recv, do buffering and cutting to lines in my code (or read byte by byte - probably it would be buffered anyway as set in listen) and treat 0 length returns by recv as disconnection. Isn't there a way to make it work via handle with higher level functions?

A: Thanks to the suggestion of K. A. Buhr, I figured out that the issue was not related to handle/socket, and the exceptions are indeed thrown correctly.
Minimal client/server setup that is working: https://gist.github.com/epoberezkin/d6063c0d8f6e95d9e606652565113413
It's based on the example in Network.Socket package, but handles multiple resolved addresses and uses handles to read/write socket.
The real issue was due to incorrectly handling exceptions in some cases, specifically instead of something like:
race (send h) (receive h) `finally` disconnected

I did
race (send h) (receive h) >> disconnected


text:
Q: Encryption in JS and Decryption in PHP (RSA) I use the library "JSEncrypt" for JS
HTML & JS & AJAX to PHP (send encrypted text to php file for decryted)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>RSA js - php</title>
    <script type="text/javascript" src="https://passport.cnblogs.com/scripts/jsencrypt.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body>

<script>

var encrypt = new JSEncrypt();
const servPubKeyPem = '-----BEGIN PUBLIC KEY-----\
MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEApa35WYXLyAIoIikbTU7J\
qQyltZX+zj8ea2bwCcs0rVcpSqMsYYWElQhvGXwSG1Dnd1jY3kNoqOvxb0oRToPj\
wLtx4xLh/RrH5eb9Xhssmo+KYhHFPu/FDBeAy4RQyP/Rv4CIIjWscj3aCiBDPrrM\
S6olwPtCRPsszG4TuUe29pW60JNCnU/1o+7rfjOCecdJpvVvqRW2vN4yxgkjAsf6\
UYyrnd9NXCaElG7X3jYKX84PSBTfttIHUthu+u37FLFUoKOZwqO4Lv0OfacevFCJ\
T4OoMnibeiygSVu8y94MtODp2SMCJ2OteKz8/11uzU27T4x9odS/DrevBebY2V5I\
94cpjyHVzJvNxqrwQ7nNOk0Y7rPvLvKfIGXXD708LRqMNpYZwj9Wu4aOXaxC6myW\
lguGT+OX3TfFzQ1dLyslGTiuy9f41AOJiK+PUnTZh84UALtnSnS62bM39+OaWHZc\
xlI7lHDK8mYxgzp9Us6WvLRBH15j3sSNV+GWCLOIk8Y6UIV/RYMCUNdVahiVqOH8\
0vevhdGZQHTLKmNdaiqCOI9R0hZLbFLzkph/kNnFKRlI0MoYn8Tqg2BRIPFYizPf\
eK+y4nmvJhmiMq3ZzUmVApt2deufZIJmNfqmnDyMKOICnYxcH0zJCrKmBmlM9u1i\
PMIXYCIshW2D3E1ACCPOw3ECAwEAAQ==\
-----END PUBLIC KEY-----'
    encrypt.setPublicKey(servPubKeyPem);
    var encryptedText = encrypt.encrypt('Hello my friend!');

    $.ajax({
        type: "POST",
        url: 'test.php',
        data: {'encryptedText' : encryptedText},
        success: function(data) {

        }
    });
</script>

</body>
</html>

PHP:
<?php

    $encryptedText = $_POST['encryptedText'];

    $priKeyPem = file_get_contents('../php/priKey.pem');

    $priKey = openssl_pkey_get_private($priKeyPem); //PriKey - PrivateKey - (he is work)
  openssl_private_decrypt($encryptedText, $decryptedText, $priKey);

    # but $decryptedText == null ...

?>

I need to encrypt the text in JS pass the encrypted text in PHP and in PHP decrypt it, but in PHP I get "null"... Please help :/


text:
Q: How to Revive Wired Internet and Setup Wireless? I'm trying to salvage a laptop long-abandoned by its owner and, just recently, given to me. Things were so messed-up that I just had to wipe the slate clean by replacing everything with Ubuntu 13.04.
In its post-installation state, it couldn't use wireless Internet, only wired. I checked the "Software and Updates" window's "Additional Drivers" tab to find this:
- Broadcom Corporation: BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller
This device is not working.
    (-) Using Broadcom 802.11 Linux STA wireless driver source from bcmwl-kernel-source (proprietary)
    ( ) Do not use the device
- Unknown: Unknown
This device is not working.
    ( ) Using Non-free firmware for Linux kernel drivers from linux-firmware-nonfree (proprietary)
    ( ) Continue using a manually installed driver
    (-) Do not use the device

As can be seen, I had the Broadcom driver installed.
The problem is that the installation has frozen at  80%. I'm thinking that the installation might need some information online to continue, but the laptop has lost its ability to sense the wired Internet it is already connected to. How can I make it re-sense the wired Internet?
Here is the current data on the laptop's state:
Ifconfig
lo  Link encap:Local Loopback
    inet addr:127.0.0.1  Mask:255.0.0.0
    inet6 addr: ::1/128 Scope:Host
    UP LOOPBACK RUNNING  MTU:65536  Metric:1
    RX packets:3291 errors:0 dropped:0 overruns:0 frame:0
    TX packets:3291 errors:0 dropped:0 overruns:0 carrier:0 collisions:0 txqueuelen:0
    RX bytes:267301 (267.3 KB)  TX bytes:267301 (267.3 KB)

sudo lshw -C network
  *-network:0 UNCLAIMED
description: Ethernet controller
product: BCM4401-B0 100Base-TX
vendor: Broadcom Corporation
physical id: 0
bus info: pci@0000:03:00.0
version: 02
width: 32 bits
clock: 33MHz
capabilities: pm cap_list
configuration: latency=64
resources: memory:dfdfc000-dfdfdfff
  *-network:1
description: Network controller
product: BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller
vendor: Broadcom Corporation
physical id: 3
bus info: pci@0000:03:03.0
version: 02
width: 32 bits
clock: 33MHz
capabilities: bus_master
configuration: driver=wl latency=64
resources: irq:17 memory:dfdfe000-dfdfffff

lspci
00:00.0 Host bridge: Intel Corporation Mobile 915GM/PM/GMS/910GML Express Processor to DRAM Controller (rev 03)
00:02.0 VGA compatible controller: Intel Corporation Mobile 915GM/GMS/910GML Express Graphics Controller (rev 03)
00:02.1 Display controller: Intel Corporation Mobile 915GM/GMS/910GML Express Graphics Controller (rev 03)
00:1d.0 USB controller: Intel Corporation 82801FB/FBM/FR/FW/FRW (ICH6 Family) USB UHCI #1 (rev 03)
00:1d.1 USB controller: Intel Corporation 82801FB/FBM/FR/FW/FRW (ICH6 Family) USB UHCI #2 (rev 03)
00:1d.2 USB controller: Intel Corporation 82801FB/FBM/FR/FW/FRW (ICH6 Family) USB UHCI #3 (rev 03)
00:1d.3 USB controller: Intel Corporation 82801FB/FBM/FR/FW/FRW (ICH6 Family) USB UHCI #4 (rev 03)
00:1d.7 USB controller: Intel Corporation 82801FB/FBM/FR/FW/FRW (ICH6 Family) USB2 EHCI Controller (rev 03)
00:1e.0 PCI bridge: Intel Corporation 82801 Mobile PCI Bridge (rev d3)
00:1e.2 Multimedia audio controller: Intel Corporation 82801FB/FBM/FR/FW/FRW (ICH6 Family) AC'97 Audio Controller (rev 03)
00:1e.3 Modem: Intel Corporation 82801FB/FBM/FR/FW/FRW (ICH6 Family) AC'97 Modem Controller (rev 03)
00:1f.0 ISA bridge: Intel Corporation 82801FBM (ICH6M) LPC Interface Bridge (rev 03)
00:1f.2 IDE interface: Intel Corporation 82801FBM (ICH6M) SATA Controller (rev 03)
03:00.0 Ethernet controller: Broadcom Corporation BCM4401-B0 100Base-TX (rev 02)   03:01.0 CardBus bridge: Ricoh Co Ltd RL5c476 II (rev b3)
03:01.1 FireWire (IEEE 1394): Ricoh Co Ltd R5C552 IEEE 1394 Controller (rev 08)
03:01.2 SD Host controller: Ricoh Co Ltd R5C822 SD/SDIO/MMC/MS/MSPro Host Adapter (rev 17)
03:03.0 Network controller: Broadcom Corporation BCM4318 [AirForce One 54g] 802.11g Wireless LAN Controller (rev 02)

As to the second device, I am not sure what it is, but the "Continue using..." seems to imply that the driver is already there ready to be used, so I am thinking of choosing the second option after the first problem is resolved. Would you guys agree?

A: Installation of the Broadcom STA wireless driver adds a blacklist for the module ssb which is also used by the driver b44 used by your ethernet card. If you load the driver b44:
sudo modprobe b44

I suspect your ethernet will come to life. If, after you do this, your wireless is still working as expected, undo the ssb blacklist:
gksudo gedit /etc/modprobe.d/blacklist-bcm43.conf

Comment out the ssb line:
#blacklist ssb

Proofread, save and close gedit. You should be all set.


text:
Q: gdb of simple hello world program not working as expected on Mac 10.13.6 I was just intending to explore the features of gdb by following:
https://www.youtube.com/watch?v=PorfLSr3DDI&t=212s
While trying to replicate the steps as in the movie above, I got slightly different output:
When I ran
gdb a.out

, I got this:
GNU gdb (GDB) 8.2.1
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html> 5 user  staff   160 May  8 22:46 .
This is free software: you are free to change and redistribute it.wxr-xr-x    1 user  staff  8432 May  8 22:46 a.out
There is NO WARRANTY, to the extent permitted by law.
Type "show copying" and "show warranty" for details.world.c
This GDB was configured as "x86_64-apple-darwin17.7.0".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
    <http://www.gnu.org/software/gdb/documentation/>.
Users-MBP:codecompre_tooltest user$
For help, type "help".ooltest user$
Type "apropos word" to search for commands related to "word"...
Reading symbols from a.out...
warning: dsym file UUID doesn't match the one in /Users/user/Documents/codecompre_tooltest/a.out
(no debugging symbols found)...done.
(gdb) start
Temporary breakpoint 1 at 0x100000f04
Starting program: /Users/user/Documents/codecompre_tooltest/a.out
[New Thread 0x1703 of process 1645]
[New Thread 0x1903 of process 1645]
[New Thread 0x1a03 of process 1645]

[3]+  Stopped                 gdb a.out

Why is this so, and how can I solve this?
NOTE: I have followed all the steps in:

*

*http://panks.me/posts/2013/11/install-gdb-on-os-x-mavericks-from-source/

*https://gist.github.com/kpy3/27014703672ad6d54c00dfc06e45f1ae


text:
Q: Why reputation is regained when we delete a downvoted question or answer? What is the consideration in regaining the lost reputation after deleting the downvoted question or answer. Is it an advantage to those asking poor questions or answering very poorly?

A: It would probably seem unfair to most users if deleting a question or answer didn't eliminate negative reputation changes from downvotes, but still did eliminate positive reputation changes from upvotes.
It's for consistency and fairness that the system gives back reputation from a downvoted post, just like it takes back reputation gained from an upvoted post. (And of course, some posts have both upvotes and downvotes, and both recalculations occur.)
As for why users should lose positive reputation changes from posts they have deleted:

*

*If you choose to delete a post, you're choosing to deprive the community of whatever continued benefit would be associated with keeping it. That doesn't mean you should never delete an upvoted post--sometimes you should, and there's even a badge for deleting a post with a score of 3 or higher to encourage people to be willing to do this. But it's only fair to lose the reputation if you're taking away what you gave people in exchange for it. (Though of course it's a more complex exchange, since the primary benefit of posting, even socially, is usually not reputation.)

*If a moderator deletes a post or high rep users vote to delete it, then it's either considered improper content (for example, it might be a great comment that doesn't try to answer a question, posted as an answer), or no longer of value (for example, a closed question with low views after closing that doesn't seem to contribute anything). In these cases, both negative and positive reputation associated with the post can be considered incidental to its temporary existence. For example, if you post a comment as an answer and it's converted to a comment, it's right that you shouldn't keep any positive or negative reputation from it, since it should have been a comment, now it is a comment, and comments don't generate reputation.

*If your answer is deleted because the question it answered was deleted, then you can keep your reputation if the answer meets certain requirements that indicate it likely gave substantial value to the community while it was around. This blog post explains that the requirements are that it existed for 60 days and had a score of 3 or greater.
If you've created a post that's been downvoted, but you've considered whether or not the post is good and you think it is, then please do not delete it. However, as ben is uǝq backwards says, removing a post of yours that doesn't provide anything of value is a good thing. Stack Exchange sites are wikis, they are extensively editable, and once a bad post no longer exists to be an eyesore, distract from good posts, or give bad advice, there's no reason its author should have to continue shouldering the burden of the negative reputation that was associated with it.