text:
Q: Single page javascript framework For a project I need to make a modular system for a 1 page only - multi pane - information homepage. Each pane gets his data from a (different) remote json API. These panes need to be modular so they can be exchanged between multiple setups.
Is there a javascript framework that I can use or extend to start with? Up until now I have found http://scaleapp.org that looks promising.

A: Many frameworks, like you said.

*

*dojo

*sencha touch

*jquery mobile

The items above are for smart phones and are based on HTML5.
The project "Scaleapp" seems very interesting.

A: If you are looking to implement something substantial, I would recommend study a bit more on other concerns in large scale javascript applications.

*

*How you should organize the code structure

*How to create a hierarchy of functional modules

*How to make UI components self contained

*How to do routing, bookmarking, history handling

*How to manage JS scripts and dependencies

*How to optimize, obfuscate for deployment

*How to make your components unit testable

*How to deal with styling, localization aspects

I have shared experience I gained in some large scale projects in a reference architecture at http://boilerplatejs.org. It addresses all above concerns and provides a sample implementation for someone to start with.

A: You can look at Pajerjs.   It uses Knockout.js and other frameworks.


text:
Q: Resource level authorization with Signalr Should Signalr groups be created with resource level IDs?  For example dispatchedTrucks-123, and dispatchedTrucks-456?  So that way when someone tries to connected to a group, I can check to see if they have access?
Let's say there are two companies: Company1 (Id 123) and Company2 (Id 456), each company has employees, and each company dispatches their trucks.
If I'm creating a Signalr hub, is it best practice to create a dispatchedTrucks group per companyId, then check to see if that people has access to that company before adding them to the group?
public async Task AddToGroup(string groupName)
{
    var companyId = Context.QueryString["companyId"];

    if (HasAccessToCompany(companyId)){
      await Groups.AddToGroupAsync(Context.ConnectionId, $`{groupName}-{companyId}`);
    } else {
      // What's the Signalr equivalent of a 403?
    }
}

So later in the application I can broadcast to an entire group, so the only people who receive the message is those who have access to that companyId.
  var companyId = Context.QueryString["companyId"];
  await Clients.Group($`{groupName}-{companyId}`).addDispatchedTruck(name, message);

The RESTful equivalent of what I'm trying to accomplish is:
UserA works for Company1 (Id 123).
UserB works for Company2 (Id 456).
UserA is only authorized to make a GET request to /company/123/dispatched-trucks
UserB is only authorized to make a GET request to /company/456/dispatched-trucks
If UserA tries to call Company2's resources, a 403 is returned.
If UserB tries to call Company1's resources, a 403 is returned.

redpajama_set_name: RedPajamaStackExchange


text:
Q: SFINAE in a template class I'm trying to figure out if Clang 3.4 allows something that is ill formed while MSVS2015 is more precise or if it's just a matter of changing the synax.
I wrote the following code:
Header
template<typename T>
class Foo
{
public:
  template<typename U> using for_bar = typename std::enable_if<std::is_same<U,Bar>::value>;
  template<typename U> using for_baz = typename std::enable_if<!std::is_same<U,Bar>::value>;

  template<typename U = T> typename for_bar<U>::type postUpdate();
  template<typename U = T> typename for_baz<U>::type postUpdate();
};

Source
template<typename T>
template<typename U> typename Foo<T>::template for_baz<U>::type Foo<T>::postUpdate()
{
  // code
}

template<typename T>
template<typename U> typename Foo<T>::template for_bar<U>::type Foo<T>::postUpdate()
{
  // code
}

This compiles and works fine on Clang 3.4 (OSX 10.8.5). Basically SFINAE is used directly on the class template using a template of template method.
But the code refuses to work on MSVC2015 with the following error:
error C2244: 'Foo<T>::postUpdate': unable to match function definition to an existing declaration
note: see declaration of 'Foo<T>::postUpdate'
note: definition
note: 'for_baz<U>::type Foo<T>::postUpdate(void)'
note: existing declarations
note: 'enable_if<!std::is_same<U,Baz>::value,void>::type Foo<T>::postUpdate(void)'
note: 'enable_if<std::is_same<U,Baz>::value,void>::type Foo<T>::postUpdate(void)'

I'm totally not practical with MSVC diagnostics so I don't know what to look for, according to the error I would think that SFINAE is not working as intended but I'm not sure, since this works fine on another compiler.
EDIT:
Actually if the method is defined inline then the code seems to compile correctly so there must be something related to the definition which is not correctly matched to the declaration.


text:
Q: Refracted code gives error code 500 while original works fine I am trying to refract my code so it can pass on code climate, code climate insists I refract duplicate code which i did but said refracted code gives an error 500 while original works fine, this is my code

// data structure as dummy database
class BookAMeal {
  constructor() {
    this.mealOptionList = [];
    this.menuList = [];
    this.orderList = [];
  }

  mealFormat(data) {
    this.mealOptionData = {
      id: data.mealId,
      name: data.mealOptionName,
      price: parseInt(data.mealOptionPrice, 10),
    };
    return this.mealOptionData;
  }

  totalPriceMenu(optionOneArray, optionTwoArray) {
    this.total = 0;
    optionOneArray.forEach((optionOne) => {
      optionTwoArray.forEach((optionTwo) => {
        if (optionOne === optionTwo.name) {
          this.total += optionTwo.price;
        }
      });
    });
    return this.total;
  }

  totalPriceOrders(optionOneArray, optionTwoArray) {
    this.total = 0;
    optionOneArray.forEach((optionOne) => {
      optionTwoArray.forEach((optionTwo) => {
        if (optionOne === optionTwo.name) {
          this.total += optionTwo.total;
        }
      });
    });
    return this.total;
  }

  menuFormat(data) {
    this.menuOptions = data.menuOptions.split(' ');
    this.menuData = {
      date: new Date(),
      id: data.menuId,
      name: data.menuName,
      mealOptions: this.menuOptions,
      total: this.totalPriceMenu(this.menuOptions, this.mealOptionList),
    };
    return this.menuData;
  }

  orderFormat(data) {
    this.orderMenus = data.menuList.split(' ');
    this.orderData = {
      id: data.orderId,
      customer: data.customerName,
      menu: this.orderMenus,
      total: this.totalPriceOrders(this.orderMenus, this.menuList),
    };
    return this.orderData;
  }
}

const data = new BookAMeal();
export default data;

// meals controller for POST route that works fine with both mocha and POSTMAN after refracting
import data from '../models';
import services from '../services';
// @ts-ignore
import bookAMeal from './index';

bookAMeal.addOneMealOption = async (req, res) => {
  services.createOne(res, data.mealOptionList, data.mealFormat(req.body),
    'Success! Meal option created', req.body.mealOptionName, req.body.mealOptionPrice,
    (/^[A-Za-z]+$/).test(req.body.mealOptionName), (/^[0-9]+$/).test(req.body.mealOptionPrice),
    'Meal option name', 'Meal option price', services.mustBeNumbersErr('Meal option price'));
};

export default bookAMeal.addOneMealOption;

// menu controller for POST route that gives error 500 during testing with mocha and POSTMAN when refracted like above meals controller
import data from '../models';
import services from '../services';
// @ts-ignore
import bookAMeal from './index';

bookAMeal.setMenu = async (req, res) => {
  services.createOne(res, data.menuList, data.menuFormat(req.body),
    'Success! Menu created', req.body.menuName, req.body.menuOptions,
    (/^[A-Za-z]+$/).test(req.body.menuName), (/^[A-Za-z\s]+$/).test(req.body.menuOptions),
    'Menu name', 'Menu options', services.stringToArrayErr('Menu options'));

// commented code below passes with both mocha and POSTMAN but needs to be refracted to pass code climate
  /*
    const testSetMenu = services.testItem(req.body.menuName, req.body.menuOptions, (/^[A-Za-z]+$/).test(req.body.menuName), (/^[A-Za-z\s]+$/).test(req.body.menuOptions));
    if (testSetMenu) {
      services.createOneRes(res, data.menuList, data.menuFormat(req.body), 'Success! Menu created');
      return;
    }
    services.processErr(req.body.menuName, req.body.menuOptions, 'Menu name', 'Menu options', services.stringToArrayErr('Menu options'), res);
    */
};

export default bookAMeal.setMenu;

// services that is called by all controllers including the above 2
class Services {
  async getAll(dataRes, dataMessage, array) {
    this.data = array;
    dataRes.status(200).send({
      message: dataMessage,
      data: this.data,
    });
  }

  findOne(dataParams, arrayData) {
    this.findItem = arrayData.find(item => item.id === parseInt(dataParams.id, 10));
    return this.findItem;
  }

  testItem(dataOne, dataTwo, dataOneTest, dataTwoTest) {
    this.testResult = (dataOne && dataTwo && dataOneTest && dataTwoTest) === true;
    return this.testResult;
  }

  async createOneRes(dataRes, arrayData, dataFormat, dataMessage) {
    this.createdItem = await dataFormat;
    this.createdItem.id = arrayData.length;
    await arrayData.push(this.createdItem);
    dataRes.status(201).send({
      message: dataMessage,
      data: this.createdItem,
    });
  }

  async createOne(dataRes, arrayData, dataFormat, dataMessage, dataOne,
    dataTwo, dataOneTest, dataTwoTest, nameOne, nameTwo, dataTwoTestRes) {
    this.testCreate = this.testItem(dataOne, dataTwo, dataOneTest, dataTwoTest);
    if (this.testCreate) {
      this.createOneRes(dataRes, arrayData, dataFormat, dataMessage);
      return;
    }
    this.processErr(dataOne, dataTwo, nameOne, nameTwo, dataTwoTestRes, dataRes);
  }

  async updateOne(dataRes, arrayData, dataFormat, dataMessage, updateId) {
    this.updatedItem = await dataFormat;
    this.updatedItem = updateId;
    await arrayData.splice(updateId, 1, this.updatedItem);
    dataRes.status(200).send({
      message: dataMessage,
      data: this.updatedItem,
    });
  }

  async deleteOne(dataRes, arrayData, deleteId) {
    this.id = deleteId;
    await arrayData.splice(this.id, 1);
    dataRes.status(204).send({});
  }

  requiredNameErr(name) {
    this.message = {
      message: `Fail! ${name} is required`,
    };
    return this.message;
  }

  mustBeLettersErr(name) {
    this.message = {
      message: `Fail! ${name} must be letters`,
    };
    return this.message;
  }

  mustBeNumbersErr(price) {
    this.message = {
      message: `Fail! ${price} must be numbers`,
    };
    return this.message;
  }

  stringToArrayErr(name) {
    this.message = {
      message: `Fail! ${name} must be letters and seperated by spaces`,
    };
    return this.message;
  }

  sendErr400(message, dataRes) {
    this.error = dataRes.status(400).send(message);
    return this.error;
  }

  processErr(dataOne, dataTwo, nameOne, nameTwo, dataTwoTestRes, resData) {
    if (!dataOne) {
      this.sendErr400(this.requiredNameErr(nameOne), resData);
      return;
    }
    if ((/^[A-Za-z]+$/).test(dataOne) === false) {
      this.sendErr400(this.mustBeLettersErr(nameOne), resData);
      return;
    }
    if (!dataTwo) {
      this.sendErr400(this.requiredNameErr(nameTwo), resData);
      return;
    }
    this.sendErr400(dataTwoTestRes, resData);
  }
}

const services = new Services();

export default services;

// exported data seeding for tests
import chai, {
  expect,
} from 'chai';
import chaiHttp from 'chai-http';
import app from '../index';

import data from '../models';

class Data {
  async meals() {
    this.testId = 0;
    this.secondTestId = 0;
    this.thirdTestId = 0;

    this.testDataOne = {
      mealId: data.mealOptionList.length,
      mealOptionName: 'Dodo',
      mealOptionPrice: 100,
    };
    this.testDataTwo = {
      mealId: data.mealOptionList.length,
      mealOptionName: 'Rice',
      mealOptionPrice: 1000,
    };
    this.testDataThree = {
      mealId: data.mealOptionList.length,
      mealOptionName: 'Beans',
      mealOptionPrice: 10000,
    };

    this.addMealOne = await data.mealFormat(this.testDataOne);
    this.addMealTwo = await data.mealFormat(this.testDataTwo);
    this.addMealThree = await data.mealFormat(this.testDataThree);
    this.testDataList = [this.addMealOne, this.addMealTwo, this.addMealThree];
    await data.mealOptionList.push(...this.testDataList);
    this.testId += this.addMealOne.id;
    this.secondTestId += this.addMealTwo.id;
    this.thirdTestId += this.addMealThree.id;
  }

  async menus() {
    this.testId = 0;
    this.secondTestId = 0;
    this.thirdTestId = 0;

    this.testDataFour = {
      menuId: data.menuList.length,
      menuName: 'Launch',
      menuOptions: 'Rice Dodo',
    };
    this.testDataFive = {
      menuId: data.menuList.length,
      menuName: 'Dinner',
      menuOptions: 'Rice Beans',
    };
    this.testDataSix = {
      menuId: data.menuList.length,
      menuName: 'Breakfast',
      menuOptions: 'Beans Dodo',
    };

    this.addOne = await data.menuFormat(this.testDataFour);
    this.addTwo = await data.menuFormat(this.testDataFive);
    this.addThree = await data.menuFormat(this.testDataSix);
    this.testDataListTwo = [this.addOne, this.addTwo, this.addThree];
    await data.menuList.push(...this.testDataListTwo);
    this.testId += this.addOne.id;
    this.secondTestId += this.addTwo.id;
    this.thirdTestId += this.addThree.id;
  }

  async orders() {
    this.testId = 0;
    this.secondTestId = 0;
    this.thirdTestId = 0;

    this.testDataSeven = {
      orderId: data.orderList.length,
      customerName: 'Okezie',
      menuList: 'Breakfast Lunch',
    };
    this.testDataEight = {
      orderId: data.orderList.length,
      customerName: 'Frank',
      menuList: 'Breakfast Dinner',
    };
    this.testDataNine = {
      orderId: data.orderList.length,
      customerName: 'Obiedere',
      menuList: 'Lunch Dinner',
    };

    this.addFour = await data.orderFormat(this.testDataSeven);
    this.addFive = await data.orderFormat(this.testDataEight);
    this.addSix = await data.orderFormat(this.testDataNine);
    this.testDataListThree = [this.addFour, this.addFive, this.addSix];
    await data.orderList.push(...this.testDataListThree);
    this.testId += this.addFour.id;
    this.secondTestId += this.addFive.id;
    this.thirdTestId += this.addSix.id;
  }
}

const dataSetup = new Data();

export {
  expect,
  chai,
  chaiHttp,
  app,
  dataSetup,
};

// tests for meals controller that passes both mocha and POSTMAN
import {
  expect,
  chai,
  chaiHttp,
  app,
  dataSetup,
} from './index';

chai.use(chaiHttp);

describe('Test endpoint at "/v1/meals" to create a meal option with POST', () => {
  before(() => {
    dataSetup.meals();
    dataSetup.menus();
    dataSetup.orders();
  });
  it('should create a meal option at "/v1/meal" with post if all request data are valid', async () => {
    const testData = {
      mealOptionName: 'Dodo',
      mealOptionPrice: 10,
    };
    const response = await chai.request(app).post('/v1/meals').send(testData);
    expect(response).to.have.status(201);
    expect(response.body).to.be.an('object');
    expect(response.body).to.have.property('data');
    expect(response.body).to.have.property('message').equal('Success! Meal option created');
    expect(response.body.data).to.have.property('id');
    expect(response.body.data).to.have.property('name').equal(testData.mealOptionName);
    expect(response.body.data).to.have.property('price').equal(testData.mealOptionPrice);
  });

  it('should not create a meal option at "/v1/meals" with POST if meal option name in request does not exist', async () => {
    const testData = {
      mealOptionPrice: 10,
    };
    const response = await chai.request(app).post('/v1/meals').send(testData);
    expect(response).to.have.status(400);
    expect(response.body).to.be.an('object');
    expect(response.body).to.have.property('message').equal('Fail! Meal option name is required');
  });

  it('should not create a meal option at "/v1/meals" with POST if meal option name in request is an empty string', async () => {
    const testData = {
      mealOptionName: '',
      mealOptionPrice: 10,
    };
    const response = await chai.request(app).post('/v1/meals').send(testData);
    expect(response).to.have.status(400);
    expect(response.body).to.be.an('object');
    expect(response.body).to.have.property('message').equal('Fail! Meal option name is required');
  });

  it('should not create a meal option at "/v1/meals" with POST if meal option name in request are not letters', async () => {
    const testData = {
      mealOptionName: '0(}fieidfjd',
      mealOptionPrice: 10,
    };
    const response = await chai.request(app).post('/v1/meals').send(testData);
    expect(response).to.have.status(400);
    expect(response.body).to.be.an('object');
    expect(response.body).to.have.property('message').equal('Fail! Meal option name must be letters');
  });

  it('should not create a meal option at "/v1/meals" with POST if meal option price in request does not exist', async () => {
    const testData = {
      mealOptionName: 'Dodo',
    };
    const response = await chai.request(app).post('/v1/meals').send(testData);
    expect(response).to.have.status(400);
    expect(response.body).to.be.an('object');
    expect(response.body).to.have.property('message').equal('Fail! Meal option price is required');
  });

  it('should not create a meal option at "/v1/meals" with POST if meal option price in request is an empty string', async () => {
    const testData = {
      mealOptionName: 'Dodo',
      mealOptionPrice: '',
    };
    const response = await chai.request(app).post('/v1/meals').send(testData);
    expect(response).to.have.status(400);
    expect(response.body).to.be.an('object');
    expect(response.body).to.have.property('message').equal('Fail! Meal option price is required');
  });

  it('should not create a meal option at "/v1/meals" with POST if meal option price in request is NOT a number', async () => {
    const testData = {
      mealOptionName: 'Dodo',
      mealOptionPrice: 'p0{f(jf]',
    };
    const response = await chai.request(app).post('/v1/meals').send(testData);
    expect(response).to.have.status(400);
    expect(response.body).to.be.an('object');
    expect(response.body).to.have.property('message').equal('Fail! Meal option price must be numbers');
  });
});

// tests for menu controller that fails mocha at 'menu options does not exist' but passes with POSTMAN
import {
  expect,
  chai,
  chaiHttp,
  app,
  dataSetup,
} from './index';

chai.use(chaiHttp);

describe('Test endpoint at "/v1/menus" to set menus with POST', () => {
  before(() => {
    dataSetup.meals();
    dataSetup.menus();
    dataSetup.orders();
  });

  it('should set a menu at "/v1/menus" with post if all request data are valid', async () => {
    const testData = {
      menuName: 'Launch',
      menuOptions: 'Dodo Rice',
    };
    const response = await chai.request(app).post('/v1/menus').send(testData);
    expect(response).to.have.status(201);
    expect(response).to.be.an('object');
    expect(response.body).to.have.property('data');
    expect(response.body).to.have.property('message').equal('Success! Menu created');
    expect(response.body.data).to.have.property('id');
    expect(response.body.data).to.have.property('name').equal(testData.menuName);
    expect(response.body.data).to.have.property('total');
  });

  it('should not create a menu at "/v1/menus" with POST if menu name in request does not exist', async () => {
    const testData = {
      menuOptions: 'Dodo Beans',
    };
    const response = await chai.request(app).post('/v1/menus').send(testData);
    expect(response).to.have.status(400);
    expect(response.body).to.be.an('object');
    expect(response.body).to.have.property('message').equal('Fail! Menu name is required');
  });

  it('should not create a menu at "/v1/menus" with POST if menu name in request is an empty string', async () => {
    const testData = {
      menuName: '',
      menuOptions: 'Dodo Beans',
    };
    const response = await chai.request(app).post('/v1/menus').send(testData);
    expect(response).to.have.status(400);
    expect(response.body).to.be.an('object');
    expect(response.body).to.have.property('message').equal('Fail! Menu name is required');
  });

  it('should not create a menu at "/v1/menus" with POST if menu name in request are not letters', async () => {
    const testData = {
      menuName: '}04[}(odyr',
      menuOptions: 'Dodo Beans',
    };
    const response = await chai.request(app).post('/v1/menus').send(testData);
    expect(response).to.have.status(400);
    expect(response.body).to.be.an('object');
    expect(response.body).to.have.property('message').equal('Fail! Menu name must be letters');
  });

  it('should not create a menu at "/v1/menus" with POST if menu options in request does not exist', async () => {
    const testData = {
      menuName: 'Launch',
    };
    const response = await chai.request(app).post('/v1/menus').send(testData);
    expect(response).to.have.status(400);
    expect(response.body).to.be.an('object');
    expect(response.body).to.have.property('message').equal('Fail! Menu options is required');
  });

  it('should not create a menu at "/v1/menus" with POST if menu options in request is an empty string', async () => {
    const testData = {
      menuName: 'Launch',
      menuOptions: '',
    };
    const response = await chai.request(app).post('/v1/menus').send(testData);
    expect(response).to.have.status(400);
    expect(response.body).to.be.an('object');
    expect(response.body).to.have.property('message').equal('Fail! Menu options is required');
  });

  it('should not create a menu at "/v1/menus" with POST if menu options in request are not letters', async () => {
    const testData = {
      menuName: 'Launch',
      menuOptions: '90{f]f9d()',
    };
    const response = await chai.request(app).post('/v1/menus').send(testData);
    expect(response).to.have.status(400);
    expect(response.body).to.be.an('object');
    expect(response.body).to.have.property('message').equal('Fail! Menu options must be letters and seperated by spaces');
  });
});

this is the error I get `$ npm test test/setMenu.js

Book-A-Meal@1.0.0 test C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal
  mocha --require @babel/register --require @babel/polyfill --exit "test/setMenu.js"

App is live and listening on port 3000!
  Test endpoint at "/v1/menus" to set menus with POST
    √ should set a menu at "/v1/menus" with post if all request data are valid (222ms)
    √ should not create a menu at "/v1/menus" with POST if menu name in request does not exist
    √ should not create a menu at "/v1/menus" with POST if menu name in request is an empty string
    √ should not create a menu at "/v1/menus" with POST if menu name in request are not letters
TypeError: Cannot read property 'split' of undefined
    at BookAMeal.split [as menuFormat] (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\models/index.js:42:41)
    at menuFormat (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\controllers/setMenus.js:7:47)
    at handleReturn (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express-promise-router\lib\express-promise-router.js:24:27)
    at C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express-promise-router\lib\express-promise-router.js:56:9
    at handleReturn (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express-promise-router\lib\express-promise-router.js:24:27)
    at C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express-promise-router\lib\express-promise-router.js:56:9
    at Layer.handle [as handle_request] (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express\lib\router\index.js:275:10)
    at Function.handle (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express\lib\router\index.js:174:3)
    at router (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express\lib\router\index.js:47:12)
    at Layer.handle [as handle_request] (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express\lib\router\index.js:317:13)
    at C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express\lib\router\index.js:335:12)
    at next (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\express\lib\router\index.js:275:10)
    at C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\body-parser\lib\read.js:130:5
    at invokeCallback (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\raw-body\index.js:224:16)
    at done (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\raw-body\index.js:213:7)
    at IncomingMessage.onEnd (C:\Users\okezie\Desktop\WEB DEV\ALCwithForLoop\Project\BookAMeal-App\Book-A-Meal\node_modules\raw-body\index.js:273:7)
    at IncomingMessage.emit (events.js:182:13)
    at endReadableNT (_stream_readable.js:1094:12)
    at process._tickCallback (internal/process/next_tick.js:63:19)
    1) should not create a menu at "/v1/menus" with POST if menu options in request does not exist
    √ should not create a menu at "/v1/menus" with POST if menu options in request is an empty string
    √ should not create a menu at "/v1/menus" with POST if menu options in request are not letters
6 passing (490ms)
  1 failing
1) Test endpoint at "/v1/menus" to set menus with POST
       should not create a menu at "/v1/menus" with POST if menu options in request does not exist:
  AssertionError: expected { Object (_events, _eventsCount, ...) } to have status code 400 but got 500
  + expected - actual

  -500
  +400

  at Context.status (test/setMenu.js:70:30)
  at process._tickCallback (internal/process/next_tick.js:68:7)

npm ERR! Test failed.  See above for more details.
`
I have already tried everything I can think of so far, I am willing to provide more info on request, I just do not get why what is essentially the same code may or may not work for some apparently vague reason, is Code Climate wrong for requesting I refract duplicate code? Why does it seem like Node JS needs duplicate code to function properly? I am very very frustrated as I type this question


text:
Q: How to call SQLPS from TSql in SQL Server 2008 I see lots of examples on running SQLPS from SQL Server Agent, but how do you call a powershell script from TSQL on demand?
I'm replacing a C# CLR function with a PowerShell script. The script will simply get a path and date modified for files in a directory structure.
What's the command to call a PowerShell script from a T-SQL stored procedure?

A: Something like this:
set @sql = 'powershell.exe -file "YourScript.ps1" -nologo'

EXEC xp_cmdshell @sql


text:
Q: Postgresql get single column of row in for loop This is probably really easy, but its driving me crazy.
I have the following function:
CREATE OR REPLACE FUNCTION get_group(serverid BIGINT, name VARCHAR(100)) RETURNS BIGINT
LANGUAGE plpgsql
AS $$
DECLARE
    group server_groups%ROWTYPE;
BEGIN
    FOR group IN SELECT * FROM server_groups WHERE server_id = serverid AND LOWER(group_name) = LOWER(name) LOOP
        RETURN group.id;
    END LOOP;
    RETURN 0;
END;
$$;

And the following tables:
server
server_id |  server_name
----------+---------------
 3251623  |  ServerOfDoom
 5578921  |  BestServerEU

server_groups
id | server_id |  group_name
---+----------+---------------
 1 |  3251623  |  aNiceGroup
 2 |  5578921  |  Valorant
 3 |  5578921  |  Admins

But when executing my function query I get the following error:
ERROR:  syntax error at or near "."
LINE 8:         RETURN group.id;

I get that this means I can't just get the id of the group row by saying group.id, but I'm really going crazy finding out how after visiting 100 different sites (maybe I'm just a bad Googler)
How do I get a single attribute of a row in a for loop?

A: You are overcomplicating things. Your requirement can be achieved with a single SQL query (which can be wrapped in a SQL function):
CREATE OR REPLACE FUNCTION get_group(serverid BIGINT, name VARCHAR(100))
  RETURNS BIGINT
as
$$
  select coalesce(max(id), 0) as id
  from server_groups
  where server_id = serverid
    and lower(group_name) = lower(name);
$$
language sql
stable;

If the WHERE clause returns no match, max(id) will yield null and the coalesce() will turn that into a 0 (although I would think a null would make much more sense).
If the WHERE clauses matches a row, the query will return the highest ID. As you only expect a single row from the query, the aggregate function won't change that.

If you really want that to be a PL/pgSQL function, you can use the FOUND status as shown in the manual:
CREATE OR REPLACE FUNCTION get_group(serverid BIGINT, name VARCHAR(100))
  RETURNS BIGINT
AS $$
declare
  group_id int;
BEGIN
  select id
    into group_id
  from server_groups
  where server_id = serverid
  and lower(group_name) = lower(name);

  if found then
    return group_id;
  else
    return 0;
  end if;
END;
$$
LANGUAGE plpgsql;


text:
Q: How to handle exceptions in lambda expressions I have metohod MyService#create which throws CustomException. I call this method in Optional#map like below:
return Optional.ofNullable(obj)
        .map(optObj -> {
            try {
                return myService.create(optObj);
            } catch (CustomException e) {
                return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
            }
        })
        .map(created -> new ResponseEntity<>("Operation successful", HttpStatus.CREATED))
        .orElse(new ResponseEntity<>("Operation failed", HttpStatus.BAD_REQUEST));

And when I call this method with arguments which cause exception then CustomException is catched but in result I get Operation successful and status 200. How to handle this exception in lambda and return message from exception?

A: You do catch exception and return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST).
Then you map it to new ResponseEntity<>("Operation successful", HttpStatus.CREATED).
If you want to have new ResponseEntity<>("Operation successful", HttpStatus.CREATED) only if call is successful rewrite your code to:
return Optional.ofNullable(obj)
        .map(optObj -> {
            try {
                myService.create(optObj);
                return new ResponseEntity<>("Operation successful", HttpStatus.CREATED);
            } catch (CustomException e) {
                return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
            }
        })
        .orElse(new ResponseEntity<>("Operation failed", HttpStatus.BAD_REQUEST));


text:
Q: Excel: How can I pick one row of a table based on the max value in one of the columns, and then copy cells of that row? I have this table regarding the scores in a game. Score and Final Score are calculated by some formulas.

I would like that, in the Final Score of the Hi-Score, the max value of the column J appeared (in this case 318) and that all the informations regarding that Final Score went above in the corresponding cells.
How can I do this? What formulas do I need to insert in the O column? Thank you.

A: One formula in O1:
=INDEX($A$2:$J$4,MATCH(MAX($J$2:$J$4),J$2:$J$4,0),MATCH(N1,$A$1:$J$1,0))

And drag down.  IF column N is spelled exactly like the header row it will automatically grab the correct column.

A: Building on Scott Craner's answer from the comments in answer form since I can't comment.
=INDEX(RAnge,MATCH(MAX(Range),RAnge,0))

The first range in that formula is the range of the data you want to find. So if you want to find the hits, that range would be A2:A4. To find level, that range would be G2:G4
The second and third range will both be the final score column.
Here is the formula as it should be written to find the total hits for the highest final score in cell O1:
=Index(A2:A4,Match(Max(J2:J4)),J2:J4,0)


text:
Q: Casting a Derived class pointer to a Base class reference I have a quick question regarding Base->Derived class relationships and casting. Like the title says, I need to cast a pointer to a derived class to a reference to a parent class. Currently, I have this code:
IIcon& retval = static_cast<IIcon&>(*obj), where obj is a AtlasTexture* object, which is a derived class of IIcon.
I am still a little foggy on the many different types of casts in C++, and was wondering if this would work, and if there was a more efficient or safe way to do this same thing.
Thanks.

A: You could write simpler
IIcon& retval = *obj;


text:
Q: dynamically change error div based on user input I want to change my error message depending on how many digits the user enters in credit card field. I'm trying to generate the message variable with this:
let numberDigit;
let creditCardMessage;

 if ($cardNumber.val().length < 13) {
   numberDigit = 'Too few digits. ';
 } else if ($cardNumber.val().length > 16) {
  numberDigit = 'Too many digits. ';
 }
creditCardMessage = numberDigit + 'Please enter between 13 and 16';

Then I want to pass the creditCardMessage variable in the following function:
function creditCardNumberEvent () {

if (!isCreditCardValid()) {
 showErrorMessage ($cardNumber, creditCardMessage, $cardNumber, 'creditCardError');
} else {
 removeErrorMessage($cardNumber, '#creditCardError');
}
}

All I get is the first value - the "too few digits." Thanks in advance.

A: When running your script, you can call CardNumberValid() which returns a Boolean, meaning you can use it in an if statement, like if(CardNumberValid())

function CardNumberValid() {
  var valid = true;
  var CardNumber = $("#CardNumber");
  if (CardNumber.val().length < 13) {
    $("#ErrorMsg").text("Too few digits. Please enter between 13 and 16");
    valid = false;
  } else if (CardNumber.val().length > 16) {
    $("#ErrorMsg").text("Too many digits. Please enter between 13 and 16");
    valid = false;
  }
  if(valid){
    $("#ErrorMsg").text("");
  }
  return valid;
}

$('#Validate').click(function() {
  alert("The card number " + (CardNumberValid() ? "is" : "is not") + " valid.");
})

<input id="CardNumber" />

<button id="Validate" type="button">Validate</button>

A: I did figure this out. I created a function as suggested and passed that function as an argument in another function: (which I now know is a callback function)
function creditCardMessageFunction () {

let numberDigit;
let creditCardMessage;

  if ($cardNumber.val().length < 13) {
     numberDigit = 'Too few digits. ';
  } else if ($cardNumber.val().length > 16) {
     numberDigit = 'Too many digits. ';
  } else {
    numberDigit = 'Numeric Values Only. ';
}
creditCardMessage = numberDigit + 'Please enter numbers between 13 and 16.';
return creditCardMessage;
}

A: I think this is what you're trying to achieve:

function logValidationMessage() {
  var cardNumber = document.getElementById('cardNumber');

  var numberDigits = null;

  if (cardNumber.value.length < 13) {
    numberDigits = 'Too few digits. ';
  } else if (cardNumber.value.length > 16) {
    numberDigits = 'Too many digits. ';
  } else {
    numberDigits = 'Card number is valid.';
  }

  console.log(numberDigits);
}

document.getElementById('btnCheckCardNumber').addEventListener('click', logValidationMessage);
<input type="text" id="cardNumber" />
<input type="button" id="btnCheckCardNumber" value="Check" />


text:
Q: What is the best way for me to gather my simulation results? I have a simulation model that returns a dataframe with information about the charging behavior of an agent:
   Station  kWh   Timestamp
   a        5     2020-01-01 09:22:07
   b        10    2020-08-20 12:02:10
   c        15    2020-12-10 17:31:39

I then have a function that takes as an input n (number of agents) and writes the dataframe for each agent in a csv file.
What I'm stuck at is how to run the simulation, lets say 1000 times, for 1000 agents. That would give me 1 million dataframes and I need to be able to gather results from each simulation so I can't write it in the same csv file.
Can anyone recommend a good way to do this?

A: Here is some pseudo-code which may help you. It would be easier to answer with a reproducible example.
import pandas as pd
import datetime as dt

def agent_sim(name):
    # do stuff ...
    # create agent name column
    df['agent'] = name
    # create timestamp for simulation time
    df['sim_timestamp'] = dt.datetime.now()
    return df

# create empty dataframe
df = pd.DataFrame()

agents = ['agent a', 'agent b', ...]

for agent in agents:
    for i in range(1000):
        df = df.append(agent_sim(agent))

# write simultations to csv
df.to_csv('agent_simulations.csv', index=False)

A: I am not clear on what your requirements are.
Here are some possibilities (I can provide basic code if needed):
Write one csv file per dataframe
Although I'm assuming you do not want to do that based on the wording of your question, it is still a possibility.
Use yaml/json
Using pandas.DataFrame's to_json method you could store all your data in a single json file.
You would need to find a unique identifier for each simulation to index the data.
Use a database
Have you considered using something like tinydb? It is a lightweight NoSQL database.


text:
Q: jquery Timer fails when used in loop I have a page with any number of div's and I need a separate timer for each div. I have setup this jsfiddle. The parts in the loop that deal with which timer are all set to timer 0 and when the script is ran, the first div is updated. But in this jsfiddle I have changed all of the references to item 0 to use the idx var and when ran none of the div's are updated. The code using idx is shown below. Would someone please point out where I'm going wrong?

1.59

2.59

3.59


text:
Q: How do you count the number of times a source has been cited in a document? Say you have a document with many citations and you want to see the number of times each one is cited. This could be implemented without much effort in a programming language, but I have a feeling this might be possible with biblatex.
The ideal solution would add the number of times a source is referenced as an extra column in the bibliography. Can this be done?


text:
Q: Loading logo on Customer Portal login page I have noticed that the logo I have placed in my login page template for Customer Portal does not load unless the user is already logged into Salesforce, which defeats the purpose of it as customers will not have access to this.
The logo itself is actually a static resource but has been set to public in the share settings.
Could anyone shed some light on this behavior and how I could fix it? Possibly without hosting the image outside Salesforce.

A: Static resources are only accessible once a user has been authenticated. But you can setup your logo as a document that can be marked as an "Externally Available Image".
The URL to access that logo is then:
https://{SALESFORCE-INSTANCE}.salesforce.com/servlet/servlet.ImageServer?oid={ORG-ID}&id={DOC-ID}

See How do I reference a public image stored in salesforce.com in my HTML? for the details.
For a Site you would replace {SALESFORCE-INSTANCE}.salesforce.com with the Site default web address e.g. mydomain.secure.force.com/mysite.


text:
Q: Moving between two Activities including data send and received, without loosing data I am trying to develop an app with two activities. After open, the app in the main activity user will input some number and do some general math calculation (such as Add, multiply, etc) by clicking the button. Then for another specific calculation user will move to 2nd activities (FabricCost) by clicking a button. In 2nd activity, the user will do some calculation and get a result. Then the user will send that result to the main activity by clicking a button. But the problem is, after sending that result, when the user going back to the main activity all the previous calculations of the main activity are already lost. Also when the user again going back to the 2nd activity by clicking the button, there also no result remaining, everything lost. I want to keep all the user input and data as it is in all the activities. I have tried with "onSaveInstanceState" but did not work. Please help me.
code by which going to 2nd activity from main activity
btnfabrateperkg.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick (View v) {

                Intent btnfabrateperkg = new Intent (MainActivity.this, FabricCost.class);
                startActivity(btnfabrateperkg);

code by which sending data to main activity from 2nd activity
btnsentresult.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick (View v) {

                String stetfabriccostperkg = etfabriccostperkg.getText().toString();

                Intent btnsentresult = new Intent (FabricCost.this, MainActivity.class);

                btnsentresult.putExtra( "etfabriccostperkg",stetfabriccostperkg);

                startActivity(btnsentresult);

code by which main activity getting result from 2nd activity
etfabrate.setText(getIntent().getStringExtra( "etfabriccostperkg"));

I have tried with "onSaveInstanceState" in main activity but didn't work, code as below
@Override
    protected void onSaveInstanceState(Bundle savedInstanceState) {

        savedInstanceState.putDouble(etbl.getText().toString(), 1.11);

        super.onSaveInstanceState(savedInstanceState);

    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState){

        super.onRestoreInstanceState(savedInstanceState);

        if (savedInstanceState == null) return;

            double myDouble = savedInstanceState.getDouble(etbl.getText().toString());

        }

Thank you.

A: You can follow the below steps to reach the result. You have to pass value every time from activity to another activity.
Step1 Going to 2nd activity from main activity
String stetfabriccostperkg = etfabriccostperkg.getText().toString();
Intent intent = new Intent (FabricCost.this, MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("myobjects", stetfabriccostperkg);
intent.putExtras(bundle);
startActivityForResult(intent, REQUEST_RESULT);

Step2 Save data in main activity while come from 2nd activity
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
                    if (requestCode == REQUEST_RESULT) {
                        // make use of "data" = profit
                        if (resultCode == Activity.RESULT_OK) {
                            Bundle b = data.getExtras();
                            if (b != null) {
                            String str = b.getString("myobject");
                         }
                        } else if (resultCode == 0) {
                            //Write your code if there's no result
                            System.out.println("RESULT CANCELLED");
                        }
                    }
                }

Step3 2nd activity on onCreate add below line
 Intent intent = this.getIntent();
 Bundle bundle = intent.getExtras();
 String str =  bundle.getString("myobjects");

Step4 Going to main activity from 2nd activity
Intent intent = new Intent();
intent.putExtra("myobject", str); //str is result to pass Main Activity
setResult(RESULT_OK, intent);
finish();


text:
Q: Resizing a cell's height and Witdth and loading an image in QTableWidget I want to make a 8*8 table with square cells ( a chess board ). Now I have the code to make the table but don't know how to resize the cells to be square shaped.
I also want to put pictures of pieces into the cells. How should I do these?
here is the code i have:
#include <QtGui/QApplication>
#include "mainwindow.h"
#include <QHBoxLayout>
#include <QTableWidget>

class Table : public QWidget
{
  public:
    Table(QWidget *parent = 0);

};

Table::Table(QWidget *parent)
    : QWidget(parent)
{
  QHBoxLayout *hbox = new QHBoxLayout(this);

  QTableWidget *table = new QTableWidget(8 , 8 , this);

  hbox->addWidget(table);
  setLayout(hbox);
}

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

    Table t;

    t.show();

    return a.exec();
}

EDIT:
If anyone can help me with loading an image as the background of cell too, it would be very appreciated!
I use this code and compiler does not generate an error but program fails to run. I think the problem is with the table->item(0,0). Should I initialize it first?
QString fileName = "1.bmp";
QPixmap pic (fileName);

QIcon icon (pic);

table->item(0,0)->setIcon(icon);

A: To make the cells square shaped do something like this:
  // set the default size, here i've set it to 20px by 20x
  table->horizontalHeader()->setDefaultSectionSize(20);
  table->verticalHeader()->setDefaultSectionSize(20);
  // set the resize mode to fixed, so the user cannot change the height/width
  table->horizontalHeader()->setResizeMode(QHeaderView::Fixed);
  table->verticalHeader()->setResizeMode(QHeaderView::Fixed);

Edit: To set the images, set the icon attribute on your QTableWidgetItems

A: after searching and searching and searching.... I finally got the answer. I should first make a QBrush object and set it as a background of a QtableWidgetItem and then use table->setItem !!!
QString fileName = "/1.bmp";
QPixmap pic (fileName);

QBrush brush(pic);

QTableWidgetItem* item = new QTableWidgetItem();
item->setBackground(brush);

table->setItem(0,0,item);


text:
Q: I want to have Order ID for Strapi Ecommerce I'm using Nuxt.v2 and Strapi.v4 without module, everythings works fine but in my ecommerce project I want to have Order ID same as other ecommerce websites, for example: Order ID 1000 and increment that ID start from 1000 per purchase means other user purchased Order ID going to 1001, is it possible?

A: Not necessarily what you want, but if it is your intention to hide how many orders you actually got this way, you could look into the new custom field feature (requires strapi 4.4.0+). There already is an UUID field that uses unique identifiers.
You can find it on the strapi market: UUID field


text:
Q: Tkinter Window: TypeError: can only concatenate str (not "int") to str I'm having trouble solving the Concatenate Error when it's present in a Tkinter Window. I tried using multiple methods but, they didn't work to well with what I'm trying to do. I'm trying to make it so where, at the click of a Tkinter button, it would randomly choose a value between 0 and 100. If the random value is less than or equal to 70, both "Good Guy" and "Bad Guy" would have their health reduced. But if it's greater than 70, Good guy would only take damage. It would then print their new hp into the window.
from random import randrange

class App5(tk.Toplevel):
    def __init__(self, title: str):
        super().__init__()
        self.title(title)

        self.style = ttk.Style(self)
        self.style.theme_use("classic")
        self.geometry("490x250")

        self.tres_label = ttk.Label(
            self,
            text="Oh yeah, also while you were doing that, I enrolled you into a tournament. \nHave fun........what? Why did I sign you up for a tournament you didn't ask for? \nTo increase the total run time on this project.",
        )
        self.tres_label.grid(row=0, column=0, padx=5, pady=5)

        self.rng_button = ttk.Button(self, text="Click Me", command=self.rng)
        self.rng_button.grid(row=2, column=0, padx=5, pady=5)

    def rng(self):
        class Character:
            def __init__(self, name: str, hp: int, damage: int):
                self.name = name
                self.hp = hp
                self.damage = damage

        Goodguy = Character("Goodguy", 300, 75)
        Badguy = Character("Badguy", 375, 25)
        score = 70
        num = randrange(0, 100)
        G = Goodguy.hp - Badguy.damage
        B = Badguy.hp - Goodguy.damage

        if num >= score:
            Goodguy.hp - Badguy.damage
            Badguy.hp - Goodguy.damage
            self.good = ttk.Label(self, text="Goodguy Hp:" + G)
            self.good.grid(row=3, column=3)
            self.bad = ttk.Label(self, text="BadGuy Hp:" + B)
            self.bad.grid(row=3, column=6)
            B = B - Goodguy.damage
            G = G - Badguy.damage
        else:
            Goodguy.hp - Badguy.damage
            self.good = ttk.Label(self, text="Goodguy Hp:" + G)
            self.good.grid(row=3, column=3)
            self.bad = ttk.Label(self, text="BadGuy Hp:" + B)
            self.bad.grid(row=3, column=6)
            B = B - Goodguy.damage
            G = G - Badguy.damage

A:
can only concatenate str (not "int") to str

is telling you exactly what the error is (and the traceback, which you should have added into your original question anyway, would have pinpointed exactly where).
The issue is you can't "sum up" a string and an integer. Instead, use string formatting:
"Goodguy Hp:" + G

would become
f"Goodguy Hp:{G}"

using f-string formatting.
The same stands for the other good guy and bad guy labels.

A: i suspect the issue is here:
self.good = ttk.Label(self, text="Goodguy Hp:" + G)

what type is G? if it's an int you cannot add them together like you're trying to do, you need to change it to text="Goodguy Hp: " + str(G), or use an f-string like @AKX mentioned
try changing this expression in all four places

A: In python you cannot concatenate an integer and a string. If you do try to do that it would result in the following error which you have gotten:
can only concatenate str (not "int") to str

The issues would be in the following blocks of code:
"Goodguy Hp:" + G

and
"BadGuy Hp:" + B

To solve this issue,
You could use the solutions @AKX and @vencaslac provided or you could use the %d operator:
"Goodguy Hp: %d" % G

"Badguy Hp: %d" % B


text:
Q: Blank screen with apple-mobile-web-app-capable and Facebook Connect We've got a few pages that use the apple-mobile-web-app-capable meta tag (value="yes"), but on a login page that allows Facebook Connect, you get a blank page when you click on the connect button. I've seen this posted on the old FB developer forums, but with no relevant responses. Has anyone figured this out already?

A: This could be a bug in facebooks API. I don't think they've tested their API in iPhone web app mode. Issue can be followed here: https://developers.facebook.com/bugs/317323871621290
The issue have been raised here on Stack Overflow a couple of times too:
How do I get back to the iPhone web app after having logged in with Facebook Connect?
blank white screen after FB login via web app?


text:
Q: Android TabLayout With Text and Icons Change color of both text and Icon on selected tab In my app implementing tablayout with each tab having both icons and text.
When tab is selected then icon and text should be selected of same tab and
un-selected tab with different color text and icons.
below is my code to implement tabs layout but not able to change  text color and icons color on tab selection.
private void setupTabIcons() {

    TextView tabOne = (TextView) LayoutInflater.from(mContext).inflate(R.layout.custome_tab_with_icon, null);
    tabOne.setText("Home");
    tabOne.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.selector_home, 0, 0);
    tabLayout.getTabAt(0).setCustomView(tabOne);

    TextView tabTwo = (TextView) LayoutInflater.from(mContext).inflate(R.layout.custome_tab_with_icon, null);
    tabTwo.setText("Search");
    tabTwo.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.selector_search, 0, 0);
    tabLayout.getTabAt(1).setCustomView(tabTwo);

    TextView tabThree = (TextView) LayoutInflater.from(mContext).inflate(R.layout.custome_tab_with_icon, null);
    tabThree.setText("WishList");
    tabThree.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.selector_wishlist, 0, 0);
    tabLayout.getTabAt(2).setCustomView(tabThree);

    TextView tabFour = (TextView) LayoutInflater.from(mContext).inflate(R.layout.custome_tab_with_icon, null);
    tabFour.setText("Cart");
    tabFour.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.selector_cart, 0, 0);
    tabLayout.getTabAt(3).setCustomView(tabFour);

    TextView tabFive = (TextView) LayoutInflater.from(mContext).inflate(R.layout.custome_tab_with_icon, null);
    tabFive.setText("Account");
    tabFive.setCompoundDrawablesWithIntrinsicBounds(0, R.drawable.selector_accounts, 0, 0);
    tabLayout.getTabAt(4).setCustomView(tabFive);

}

Please help how to change text color and icon when tab is selected.
TIA

A: Toggle tab text color
In your xml add the linesapp:tabTextColor and app:tabSelectedTextColor to the TabLayout .
        <android.support.design.widget.TabLayout
            android:layout_width="match_parent"
            app:tabTextColor="#000000"
            app:tabSelectedTextColor="#FFFFFF"
            android:layout_height="wrap_content"/>

Toggle tab icon In your fargment/activity add selector drawable to each tab.
        tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        //Set selector drawable to each tab
        tabLayout.addTab(tabLayout.newTab().setText("Warm Up").setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.selector_warmup_icon,null)));
        tabLayout.addTab(tabLayout.newTab().setText("Exercise").setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.selector_exercise_icon, null)));
        tabLayout.addTab(tabLayout.newTab().setText("Rest").setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.selector_rest_icon, null)));
        tabLayout.addTab(tabLayout.newTab().setText("Success").setIcon(ResourcesCompat.getDrawable(getResources(), R.drawable.selector_success_icon, null)));

selector_warmup_icon.xml (should be like)
 <?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@drawable/ic_human_white_48dp" android:state_selected="true"/>
    <item android:drawable="@drawable/ic_human_grey600_24dp" android:state_selected="false"/>

</selector>

A: You can do that by adding a TabLayout.OnTabSelectedListener and it has three methods onTabSelected(), onTabUnselected() and onTabReselected(), which you can use to change the color of both icon and text. Here's the link you can refer to it.

A: You can use a Color State List resource for the text color as well as for the tint of the icons. I think android:state_selected should work.


text:
Q: How to get ONLY the processes in the "apps" section of the Task Manager and how to get the currently opened process? (C#) I know there are a few "possible duplicate" questions but they don't have a proper answer. I've looked over the whole internet and I can't find a way to get only the processes that are in the "apps" section of the Task Manager (or the ones that are displayed as running on the windows taskbar, same thing) If the Task Manager can do it, then it can be done.

Also how would I go about getting only the process that the user is currently on? (the currently opened process, same thing) For example right know my currently opened process is chrome. If I go to play Minecraft, it will change to minecraft... you get the idea.
Please stop marking this as a duplicate and take some time to read my question.


text:
Q: http in the Location-header when the original request was made over https I am currently implementing https on our production environment, but I am scratching my head over a little thing here.
SSL is terminated in the load balancer and the flow in our stack is basically like this:
Production: Browser <- https -> Load balancer <- http -> Apache <- http -> Load balancer <- http -> Tomcat
Testing: Browser <- https -> nginx <- http -> Load balancer <- http -> Tomcat
When I access our login-page over HTTPS:
Request headers
POST /login/form HTTP/1.1
Host: www.example.org
Connection: keep-alive
Content-Length: 74
Cache-Control: max-age=0
Origin: https://www.example.org
Content-Type: application/x-www-form-urlencoded
Referer: https://www.example.org/login
Accept-Encoding: gzip,deflate,sdch
Accept-Language: nb,en-US;q=0.8,en;q=0.6

Response headers
HTTP/1.1 302 Moved Temporarily
Server: nginx
Date: Fri, 17 Jan 2014 11:16:50 GMT
Content-Length: 0
Connection: keep-alive
Set-Cookie: FOO=example
Location: http://www.example.org/portal
Strict-Transport-Security: max-age=31536000

I talked to a developer and he told me the following:

In the code there is sth like request.sendRedirect("/portal") and Tomcat does the rest.

I am able to reproduce the problem on the testing environment, although a bit different stack.
My questions:

*

*Why do I get http as the scheme in the Location-header when the original request from the browser was made with https?

*Is this an Apache mod_rewrite/mod_proxy or nginx problem?

*Is this a problem with Tomcat?

A: I had a similar issue. Adding the following in your virtualhost config should solve the problem. Basically it would edit the http request to https
Header edit Location ^http://(.*)$ https://$1

A: You get http in the response headers because the request that reaches Apache is HTTP - the SSL has been stripped away at the load balancer.  So from what Apache sees, it's just an HTTP request.
You can work around this by setting
ServerName https://www.example.org

in the global or virtual host configuration.  This will override the default http scheme so Apache will send the response you want.  The documentation for ServerName mentions this.

A: http://nginx.org/docs/http/ngx_http_proxy_module.html#proxy_redirect
proxy_redirect default;
proxy_redirect http://www.example.org/ https://www.example.org/;


text:
Q: How to find the number of squares in this figure using combination theory? I am trying to use the same combination method shown in this solution here -
How to find the number of triangles in this figure?
However, if I am trying to  apply the same logic here.
the number of straight line segements are 10 so the answer should be 10C4 but I know that is not correct. What am I missing here?

A: Unlike the triangle problem, not all sets of four lines make a square, so $10 \choose 4$ is not correct.  Here you need to choose two of the five horizontal lines, then choose two of the five vertical lines.  This gives a rectangle, of which there are ${5 \choose 2}^2=100$  For a square, you need to make sure the vertical and horizontal spacing is the same.  I would do it by cases.  There are $4$ ways to choose a pair with spacing $1$, $3$ ways with spacing $2$, and so on, so the number of squares is $4\cdot 4+3\cdot 3+2\cdot 2+1\cdot 1=30$


text:
Q: How to specify the HID Report in GadgetFS I am using GadgetFS to spoof a Nintendo Pro Controller through usb using these descriptors. However, I am not sure how to send the HID Report to the Switch. I know you can do it in ConfigFS, but I haven't been able to find endpoint support in ConfigFS, so I decided to use GadgetFS.
I have looked into varios resources like this and this. It seems like I should be able to send the HID Report descriptor through GadgetFS, but I can't find a way. It doesn't seem like USB_REQ_GET_REPORT is defined in any API.
My code can be found here which depends on the library found here. Finally, do I really need the HID Report descriptor anyway?

A: I think I have figured it out. When a device is an HID device, the bRequest value changes to some HID constants. Some of these HID specific constants can be found here.


text:
Q: Excel file corrupt or wrong extension error openpyxl & writerxlsx I am using the following code to create and excel file using xlsxwriter and openpyxl to edit it as I may need to read from other excel files later down the line, however when I try to open the file it gives me an error that the excel file is corrupt or the extension is incorrect. When the source file is saved as .xlsm this error is not present, I would like to know why that is.
import xlsxwriter
import openpyxl

# Create a workbook and add a worksheet.
workbook = xlsxwriter.Workbook('Dabble dabble.xlsx')
worksheet = workbook.add_worksheet()

workbook.close()

target_file = 'Dabble dabble.xlsx'
i = 2

No = i - 1
Company = "Panasonic"
Location = "California"
Store_type = "Hyper Market"
Date = "1/1/2020"

No_loc = "A" + str(i)
company_loc = "C" + str(i)
location_loc = "B" + str(i)
store_type_loc = "D" + str(i)
date_loc = "E" + str(i)

srcfile = openpyxl.load_workbook(target_file, read_only=False,
                                             keep_vba=True)

sheetname = srcfile['Sheet1']

sheetname[No_loc] = No
sheetname[company_loc] = Company
sheetname[location_loc] = Location
sheetname[store_type_loc] = Store_type
sheetname[date_loc] = Date

# Table headers
sheetname["B1"] = "Location"
sheetname["C1"] = "Company"
sheetname["D1"] = "Store Type"
sheetname["E1"] = "Date"

i = i + 1
srcfile.save(target_file) #Saving data to file
import pandas as pd

target_file = "Dabble dabble.xlsx"

df= pd.read_excel(target_file)

print (df)

However, when I parse the file using pandas it reads the data, which shows me that the file was created and written.
  Unnamed: 0    Location    Company    Store Type      Date
0           1  California  Panasonic  Hyper Market  1/1/2020

A: The issue is that you are setting keep_vba=True but the file you are dealing with isn't a xlsm file and doesn't have a vbaProject file. Just set it to false or omit the option.
srcfile = openpyxl.load_workbook(target_file,
                                 read_only=False,
                                 keep_vba=False)


text:
Q: How to deal with WebServices error "any is not supported in sequence"? I am trying to aquire data through Mathematica's WebServices and this example works just fine:
<<WebServices`
InstallService["http://www.webservicex.net/CurrencyConvertor.asmx?WSDL"]
ConversionRate["USD","RUB"]

However, when I try to install this service:
InstallService["http://cbr.ru/secinfo/secinfo.asmx?WSDL"]

Mathematica returns with error messages:
LoadSchema::unsupported: any is not supported in sequence.
LoadSchema::elementschema: The element schema cannot be found for {http://www.w3.org/2001/XMLSchema, schema}.

I'm not very well versed in XML however it seems that there's an "any" tag present in the code of the service, is that a provider's mistake?


text:
Q: Image segmentations with gradient filled regions I have to work on image segmentation. The idea is to divide an image into regions which have pixels either of the similar color or the ones which can be represented by a gradient equation (linear or radial). I have found many algorithms which do the separation based on colors but could not find anyone which handles gradients. Does someone know any such algorithm or suggestions on how to go for it.

A: Mean-Shift Segmentation might be what you are looking for. It is implemented in OpenCV.  It is tolerant of smooth gradients, yielding a more natural result, or something that a human would come up with if he was converting an image to a paint-by-number.
Here is an image that was segmented with mean-shift:

A: In gradient areas, the edge function (laplacian or other edge detection functions) will detect no edge (the result will be nearly zero ("black")). So, apply an edge filter on the image, and then you will have nearly black areas (for gradient or other similarly-colored sections) outlined by bright edges (where there was a strong difference in the original image). This image should be easily segmented by most segmentation algorithms (and if they classify the bright edges as their own segment, simply merge edge pixels back with the closest black area).

Note that you may want to find and segment only the gradient areas first, and then use a more decent segmentation algorithm on the original (non-edges) image. Note also that the edge detection doesn't work exactly for the radial gradients, so you may want to actually compute the edge function twice to acheive better results


text:
Q: How to get values from this json object? How to get values from this json?
The returned json from an API is like:
{
  "id": 191671,
  "callTrackingProfiles": {
    "1": {
      "destinationPhoneNumber": "8449000218",
      "phones": [
        {
          "phoneType": 3,
          "phoneNumber": "8443876176",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": false,
          "recordCalls": false,
          "countryCode": "USA"
        },
        {
          "phoneType": 7,
          "phoneNumber": "8442692468",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": false,
          "recordCalls": false,
          "countryCode": "USA"
        },
        {
          "phoneType": 10,
          "phoneNumber": "9493931848",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": true,
          "recordCalls": false,
          "countryCode": "USA"
        }
      ]
    },
    "2": {
      "destinationPhoneNumber": "8449000218",
      "phones": [
        {
          "phoneType": 3,
          "phoneNumber": "9495283517",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": true,
          "recordCalls": false,
          "countryCode": "USA"
        },
        {
          "phoneType": 7,
          "phoneNumber": "8443500663",
          "destinationWhisper": true,
          "callerWhisper": false,
          "isLocal": false,
          "recordCalls": false,
          "countryCode": "USA"
        }
      ]
    }
}

Now, I deserialized it:
dynamic jsonResults = JsonConvert.DeserializeObject<dynamic>(response);
var profiles = jsonResults.callTrackingProfiles;

and I can use foreach to loop it.
But how can I get the values of destinationPhoneNumber and phoneNumber?
foreach (var p in profiles)
{
    ...
    p.destinationPhoneNumber
    ...
}

This does not work, and p.1 has error:
error CS1061: 'object' does not contain a definition for 'destinationPhoneNumber' and no accessible extension method 'destinationPhoneNumber' accepting a first argument of type 'object' could be found (are you missing a using directive or an assembly reference?)

Thanks

A: I am assuming you're using visual studios. If so this is the easiest solution in my opinion: 1.Create a c# class. 2.Then Copy all of your JSON (from your example). 3.Then go to that class you created before and go to Edit>paste special>Paste JSON as Classes.
This will create a class for you based off that JSON. Then all you have to do is deserialize it into that class type and it will create an object which you can pull all the information out of. I hope that helps!
http://blog.codeinside.eu/2014/09/08/Visual-Studio-2013-Paste-Special-JSON-And-Xml/

A: Try creating some classes that define the structure of your JSON:
public class RequestVm
{
    public long Id { get; set; }
    public Dictionary<string, CallTrackingProfileVm> callTrackingProfiles { get; set; }
}

public class CallTrackingProfileVm
{
    public string destinationPhoneNumber { get; set; }
    public List<PhoneNumberVm> phones { get; set; }
}

public class PhoneNumberVm
{
    public int phoneType { get; set; }
    public string phoneNumber { get; set; }
    public bool destinationWhisper { get; set; }
    public bool isLocal { get; set; }
    public bool recordCalls { get; set; }
    public string countryCode { get; set; }
}

Then you can iterate over it like so:
var jsonResults = JsonConvert.DeserializeObject<RequestVm>(str);
var profiles = jsonResults.callTrackingProfiles;
foreach(var value in profiles.Values)
{
    var phone = value.destinationPhoneNumber;
}


text:
Q: How to process batchUpdate and copy from one spreadsheet into another using Google Sheets API Link to original question where I found the below script: How to batch-copy range with Google Sheets Api
Question: How do I modify the below to write into a different spreadsheetId? I've Googled everything I can and can only find examples where the copyPaste occurs within the same SpreadsheetID.
function Test_Copy() {
  var spreadsheetId = "1hLXq9zq-tAaGpPtGiY6859h4oKxIbNimxCHPPZOzdE0";
  var sheetId = "1792457718";
  var sheetIdd = "760382355";

  var rangeFrom = Sheets.newGridRange();
  rangeFrom.sheetId = sheetId;
  rangeFrom.startRowIndex = 0;
  rangeFrom.endRowIndex = 23637;
  rangeFrom.startColumnIndex = 0;
  rangeFrom.endColumnIndex = 23;

  var rangeTo = Sheets.newGridRange();
  rangeTo.sheetId = sheetIdd;
  rangeTo.startRowIndex = 0;
  rangeTo.endRowIndex = 23637;
  rangeTo.startColumnIndex = 0;
  rangeTo.endColumnIndex = 23;

var copyPasteRequest = Sheets.newCopyPasteRequest();
  copyPasteRequest.destination =  rangeTo;
  copyPasteRequest.source =  rangeFrom;
  copyPasteRequest.pasteType = "PASTE_VALUES";
  copyPasteRequest.pasteOrientation = "NORMAL";

  var resource = Sheets.newBatchUpdateSpreadsheetRequest();

  //Create request object
  var request = Sheets.newRequest();
  request.copyPaste = copyPasteRequest;
  resource.requests = [request];

  var res = Sheets.Spreadsheets.batchUpdate(resource , spreadsheetId);
  //Logger.log(res.replies);
  //Logger.log(res.spreadsheetId);

}


text:
Q: JQuery datepicker only works if I put an alert() in the script I'm coding a jQuery datatable with some input fields (on each row). One of the fields needs to be a date and so I'm trying to use jQuery datepicker to accomplish the input for that field.
The field in question is rendered for each row using a template:
var invoiceDateInputTemplate = '<input class="datepicker" id="InvoiceDate_{0}" name="InvoiceDate_{0}" type="text" />';

During the datatable build, I render the template and replace the {0} with the appropriate Id so the id & name parameters are unique for each row.
At the end of my $(document).ready() function, after the table has been built, I run the following code to make each of my 'date' fields into a datepicker enabled field using the class selection option. For some reason, this doesn't seem to want to cause the fields to become datepicker enabled:
$(function() {
    $(".datepicker").datepicker();
});

If I add an alert() call prior to the $(".datepicker").datepicker(), it works like a champ... an alert() call after the datepicker initialization does NOT work.
This causes the DatePicker to render:
$(function() {
    alert();
    $(".datepicker").datepicker();
});

This causes the DatePicker to NOT render (included to provide an example):
$(function() {
    $(".datepicker").datepicker();
    alert();
});

Why is this happening? Am I missing something that would be causing the DatePicker to not initialize the fields as expected? I'm pretty sure that it isn't standard operating procedure to have to fire an alert to get DatePicker to work correctly. Also, just to clarify, I don't believe that I have any fields being focused upon after the datatable builds.

A: I get the feeling that you've got an async problem!
The easiest solution is to bind the call to datepicker() on a custom event, then trigger the event after the datatable is built. Like so:
$(function() {
    // Create data table here
    $(window).trigger('datatable.built');
});

$(window).on('datatable.built', function() {
    $(".datepicker").datepicker();
});

A: What are you using for datatable? Most probably it renders after you attach event, in that case it should have an event like draw or somethingwhich indicates that data is rendered

A: Try use this:
$(function() {
    $(document).on("focusin",".datepicker",function(){
        $(this).datepicker();
    });
});

if it works, you can improve for not "recreate" datepicker everytime the element get focus

A: As it turns out, @Guy had the solution... I set the function up within a setTimeout and it started working as it should:
setTimeout(function() {
        $(".datepicker").datepicker();
    },1000);

I should have thought of that earlier... Thanks @Guy!


text:
Q: Will GCM works on Android 4.0 upgraded from Android 2.1 I am having GCM push notification in my project. I know GCM will work for Android 2.2 and above. But will it work for those phone having Android 4.0 which were upgraded from Android 2.1 ?

A: I'm actually using GCM on both Android version.
It works fine, the compatibility problems are only about actual version, and not about the olders, and in this case, with the 4.0, it's all fine.


text:
Q: Multiple HTML same id elements if only one is rendered in the DOM Can you have multiple same id elements if only one is rendered in the dom?
For example in Laravel you can have:
 @if (Route::has('login'))
   @auth

Dashboard

 @else

Sign up

   @endauth
 @endif

I realize multiple id on same elements is bad practice, but technically in a situation like this only one element would be rendered in the DOM, as far as browser is conserned, it only detects one of them, so would it have any bad effects regarding javascript etc..? It can simplify css though.
I don't plan to use this in my projects, just curious.

A: I would go this way :
@if (Route::has('login'))

{{ Auth::check() ? 'Dashboard' : 'Sign up' }}

@endif

A: In any case having a class is better even for the css as the ID adds a much bigger weight on the element, for example if you want to override a css property you won't be able to achieve it by just adding a class.
An example for this will be:
#header {
 font-size: 1.5rem;
}

later you want to override the css on just one header element and not on the other, adding a class to that element won't override the font-size of the element. I hope I am clear with the example.
So to summarize your code is okay, it will get only one element on the page with the ID when it get's rendered.

A: If only one "h2" of them will be rendered, it doesn't differ from writing only one of them
due to your code, there's no way the two "h2" will be rendered in the DOM
the only thing will cause a problem if any two elements were rendered in the DOM with the same ID
in that case, if you tried to select one of them or apply any js to them it will select the first element was rendered on the DOM


text:
Q: n-bit adder with saturation Hello there I'm trying to create a n-bit adder/subtractor in VHDL that has a saturation option, if saturation = 1 then if a + b overflows the output vector it should just lock to the maximum value and vice versa for subtraction.
Here's the process for handling the saturation part, I won't post all of my code here for my adder since I know that there is nothing wrong with that part, the problem is my thinking with how to handle the saturation...
process(saturate, o_flow, temp_sum)
begin
if (saturate = '1' AND o_flow = '1') then
    if carry(WIDTH-1) = '0' then
        y <= (WIDTH-1 => '0', others => '1');
    else
        y <= (WIDTH-1 => '1', others => '0');
    end if;
else
    y <= temp_sum;
end if;
end process;

Would love to get some help, so can you spot my misstake?

A: You simply forgot carry in your sensitivity list:
process(saturate, o_flow, temp_sum, carry)
begin
if (saturate = '1' AND o_flow = '1') then
    if carry(WIDTH-1) = '0' then
        y <= (WIDTH-1 => '0', others => '1');
    else
        y <= (WIDTH-1 => '1', others => '0');
    end if;
else
    y <= temp_sum;
end if;
end process;

But as you do not really explain what you observe and what is wrong with it, there could be other problems...


text:
Q: Conditional React component properties with multiple generics I am trying to implement a Typography component in React, and need to make it flexible enough, so it will as:

*

*variant prop is mandatory

*the as prop is optional
a. if as is a string, it will be a native html tag and surface this tag's properties
b. if as is a react element, it will surface the react element's properties
c. if as is not defined, it will default to the variant's mapped element
For example if as="a", we expect that href property will exist.
The example code is below, which works when testing the type Proxy only but using it with the react component it is not working:
import React from "react";

const TypographyDefaultMapping = {
    h1: 'h1',
    h2: 'h2',
    h3: 'h3',
    'body-medium': 'span',
    label: 'span',
} as const;

export type TypographyVariants = keyof typeof TypographyDefaultMapping;

type Tags = keyof HTMLElementTagNameMap;

type AsType = undefined | Tags | React.FunctionComponent<any>;

type VariantsDefaultType<T extends TypographyVariants> = Omit<
    React.ComponentPropsWithoutRef<typeof TypographyDefaultMapping[T]>,
    'as'
> & {
    variant: TypographyVariants;
};

export type NewConditionalTypography<
    T extends AsType,
    V extends TypographyVariants
> = T extends undefined
    ? VariantsDefaultType<V> // Undefined "as" property, fallback to variant's default
    : T extends Tags
    ? {
        variant: TypographyVariants;
        as: Tags;
        bloup: boolean;
    } & React.ComponentPropsWithoutRef<T> // "as" property is a valid HTML tag
    : T extends React.FunctionComponent<any> // "as" property is a React element
    ? {
        variant: TypographyVariants;
        as: React.FunctionComponent<any>;
        bib: boolean;
    } & React.ComponentProps<T>
    : never;

type Proxy<T = unknown> = T extends {
    as: infer As extends AsType;
    variant: infer Var extends TypographyVariants;
}
    ? NewConditionalTypography<As, Var>
    : T extends {
        variant: infer Var extends TypographyVariants; // case of not defined "as"
    }
    ? NewConditionalTypography<undefined, Var>
    : never;

const NewTypography = (props: Proxy) => (

Test: {JSON.stringify(props)}

);

const Link = ({ linkClick }: { linkClick: () => void }) => (
    <button onClick={linkClick}>Test</button>
);

// Expected to get HTMLHeadingElement props + variant prop
type TestProxy = Proxy<{ variant: 'h2' }>;
     // ^?

// Expected to get HTMLSpanElement props + variant prop
type TestProxySpan = Proxy<{ variant: 'body-medium' }>;
     // ^?

// Expected to get HTMLAnchor props + variant prop
type TestProxy2 = Proxy<{ variant: 'h2'; as: 'a' }>;
     // ^?

// Expected to get Link element props + variant prop
type TestProxy3 = Proxy<{ variant: 'h2'; as: typeof Link }>;
     // ^?

const TestingComponent = () => (

    // Should allow (and auto-complete) "href"
        <NewTypography variant="h2" />
    // Should allow (and auto-complete) "linkClick"
        <NewTypography
            variant="body-medium"
            as={Link}
        //   linkClick={() => console.log('Test')}
        />
    // Should not allow "href"
        <NewTypography variant="body-medium" as="span" href="www.example.com" />

);

or as a Typescript Playground link.
Any clue how can achieve this, and if it's feasible after all?
[Edit]:

*

*Simplified playground based on comments

A: You need to add the type parameters to the function so they can be inferred. After that some minor tweaks to  NewConditionalTypography and it should work:

export type NewConditionalTypography<
    T extends AsType,
    V extends TypographyVariants
> = // Undefined "as" property, fallback to variant's default
    T extends undefined? VariantsDefaultType<V>:
    // "as" property is a React element
    T extends (p: any) => JSX.Element ? { bib: boolean; } & React.ComponentProps<T>:
    // "as" property is a valid HTML tag
    T extends Tags ? { bloup: boolean; } & React.ComponentPropsWithoutRef<T> :
    {}

const NewTypography = <TVar extends TypographyVariants, TAs extends AsType = undefined>(props: {
    as?: TAs;
    variant: TVar;
} & NewConditionalTypography<TAs, TVar> ) => (

Test: {JSON.stringify(props)}

);

Playground Link


text:
Q: MySQL convert similarly named columns to rows I have a situation where I have a table that looks something like this, only there are 15 columns like this. Some of the columns will contain nulls. There are also additional columns in the table, but those are not important to the question.
CREATE TABLE test_table (
    test1 CHAR(4),
    test2 CHAR(4),
    test3 CHAR(4),
    test4 CHAR(4),
    test5 CHAR(4),
)

I need to insert these values (when not null) into another table, each as an individual row. I don't want to write 15 insert statements. Is there any slick way to do this?
INSERT INTO other_table
SELECT ??? FROM test_table WHERE ???


text:
Q: Concatenate ORC partition files on disk? I am using Spark 2.3 to convert some CSV data to ORC for use with Amazon Athena; it is working fine! Athena works best with files that are not too small so, after manipulating the data a bit, I am using Spark to coalesce the partitions into a single partition before writing to disk, like so:
df.coalesce(1).write.orc("out.orc", compression='zlib', mode='append')

This results in a single ORC file that is an optimal file size for use with Athena. However, the coalesce step takes a very long time. It adds about 33% to the total amount of time to convert the data!
This is obviously due to the fact that Spark cannot parallelize the coalesce step when saving to a single file. When I create the same number of partitions as there are CPUs available, the ORC write out to disk is much faster!
My question is, can I parallelize the ORC write to disk and then concatenate the files somehow? This would allow me to parallelize the write and merge the files without having to compress everything on a single CPU?


text:
Q: simplest way to detect if mobile device with javascript What is the simplest way to detect if the device is a mobile device with javascript?
I was thinking checking if the height is less than or equal to the iPhone's browser viewport height. Speaking of which, what is the iPhone's or a common viewport height for mobile devices?
I was having some troubles with window.height; in javascript as it was coming back undefined, however?
Anyone know how do best and simply detect if the browser is an mobile device with javascript?

A: This is what I have for my hobby project:
var Environment = {
    //mobile or desktop compatible event name, to be used with '.on' function
    TOUCH_DOWN_EVENT_NAME: 'mousedown touchstart',
    TOUCH_UP_EVENT_NAME: 'mouseup touchend',
    TOUCH_MOVE_EVENT_NAME: 'mousemove touchmove',
    TOUCH_DOUBLE_TAB_EVENT_NAME: 'dblclick dbltap',

    isAndroid: function() {
        return navigator.userAgent.match(/Android/i);
    },
    isBlackBerry: function() {
        return navigator.userAgent.match(/BlackBerry/i);
    },
    isIOS: function() {
        return navigator.userAgent.match(/iPhone|iPad|iPod/i);
    },
    isOpera: function() {
        return navigator.userAgent.match(/Opera Mini/i);
    },
    isWindows: function() {
        return navigator.userAgent.match(/IEMobile/i);
    },
    isMobile: function() {
        return (Environment.isAndroid() || Environment.isBlackBerry() || Environment.isIOS() || Environment.isOpera() || Environment.isWindows());
    }
};

Your solution about using dimension is not a good solution. It relies on the actual device dimension and many other variables.


text:
Q: Objectify can't find entity that appears to exist I'm using Objectify 5.1.1 on Google App Engine.  I have defined an Objectify entity called Insight and tried to query it by a boolean property called downloaded.  However, Objectify can't find this entity.
Here's how I'm trying to do the query:
Query<Insight> insightQueryTemplate = ofy().load().type(Insight.class).
                filter("downloaded", false).first().safe();

Here's a stripped down class definition for Insight:
@com.googlecode.objectify.annotation.Entity
public class Insight {
    @com.googlecode.objectify.annotation.Id
    public Long id;

    public boolean downloaded = false;

    public Insight () { }

}

When I look in the development server's datastore I can see the entity does exist but the downloaded property says "false (unindexed)" instead of simply "false".
I'm pretty sure this used to work with Objectify 3.1 so what am I doing wrong?

A: I think the tag @com.googlecode.objectify.annotation.Index needs to be annotated on the class like this:
@com.googlecode.objectify.annotation.Entity
public class Insight {
    @com.googlecode.objectify.annotation.Id
    public Long id;

    @com.googlecode.objectify.annotation.Index  // *** This was missing ***
    public boolean downloaded = false;

    public Insight () { }

}

According to https://cloud.google.com/appengine/docs/java/datastore/indexes#Java_Unindexed_properties, properties are either set with setProperty() or setUnindexedProperty().  But the current documentation for Objectify says that properties are set as unindexed by default.
So I annotated my class with @com.googlecode.objectify.annotation.Index and the problem was fixed.


text:
Q: Exportar CSV con PHP (fputcsv) no descarga Mi plataforma posee un botón para exportar los datos de una tabla a un archivo CSV.
Mi código es el siguiente:
    $table = 'produ';
    $output_file = 'file.csv';
    $delimiter = ';';
    $enclosure = '"';
    header('Content-Encoding: UTF-8');
    header('Content-Type: text/csv; charset:UTF-8');
    header('Content-Disposition: attachment; filename="' . $output_file . '"');
    $h = fopen($output_file, 'w');
    $sql = mysqli_query($con, "SELECT * FROM $table");
    $header_written = false;
    while ($row = mysqli_fetch_assoc($sql)) {
        if (! $header_written) {
            fputcsv($h, array_keys($row), $delimiter, $enclosure);
            $header_written = true;
        }
        fputcsv($h, $row, $delimiter, $enclosure);
    }
    fclose($h);

Estas líneas de códigos sí crean el archivo en cuestión. Sin embargo, lo que estoy buscando es que, al hacer click en el botón correspondiente, la descarga del archivo se realice automáticamente.
Vale decir que he podido hacer un a href="" para vincular al archivo en cuestión y descargarlo mediante un mensaje que se muestra al usuario de que el archivo está listo. Sin embargo, conforme se van realizando las exportaciones, los archivos se van acumulando en la carpeta correspondiente. Por ello, lo que deseo es que descargue directamente.
He intentado ya reemplazar la línea...
$h = fopen($output_file, 'w');

Con...
$h = fopen('php://output', 'w');
ob_clean();
...
ob_flush();

Ni aún así he logrado la descarga del archivo. Alguna idea?
EDITO:
Ya he intentado agregarle un exit(); al final del mismo y no funciona. Tampoco funciona la siguiente línea
    $h = fopen('php://memory', 'w');

Le he agregado mas headers para ver si así funcionaba, y tampoco...
    header("Content-type: application/force-download");
    header('Content-Disposition: inline; filename="'. $output_file .'"');
    header("Content-Transfer-Encoding: Binary");
    header("Content-length: ". filesize($output_file));
    header('Content-Disposition: attachment; filename="'. $output_file .'"');
    header("Cache-Control: no-cache, no-store, must-revalidate"); // HTTP 1.1
    header("Pragma: no-cache"); // HTTP 1.0
    header("Expires: 0"); // Proxies


text:
Q: Youtube play video : The youtube account associated with this video has been terminated I am playing video from playlist of my account. But some of videos are not playing with shows error in webview.
    - (void)playVideoWithId:(NSString *)videoId {

    NSString *youTubeVideoHTML = @"

   ";

    NSString *html = [NSString stringWithFormat:youTubeVideoHTML, videoId];

    UIWebView *videoView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    videoView.backgroundColor = [UIColor clearColor];
    videoView.opaque = NO;
    //videoView.delegate = self;
    [self.view addSubview:videoView];

    videoView.mediaPlaybackRequiresUserAction = NO;

    [videoView loadHTMLString:youTubeVideoHTML baseURL:[[NSBundle mainBundle] resourceURL]];
}

Error image

How can I fix this.

A: When an account is terminated or closed, all videos uploaded by the account will be removed from youtube server. You can't view this video.


text:
Q: How to make a proper test suite from a given code with Mockito? I am trying to make a test suite for my game. But I don't know where to begin and how test this whole class with mockito. Can somebody help me with that?
First, I mocked the board and level makers then I have done some test to parse a map with enemies, walls and a player on it and then call the parser to parse the map and then verify whether the the board and level maker methods were called, but I don't know how to continue from here. Also I have some problems mocking the Board class because its constructor has no access modifier so I can't access it when my test class is not in the same package ( how can I workd-around this problem).
Here is the parser class that I want to test:
    public class Parser {

    private LevelMaker levelMaker;

    private BoardMaker boardMaker;

    public Parser(LevelMaker levelMaker, BoardMaker boardMaker) {
        this.levelMaker = levelMaker;
        this.boardMaker = boardMaker;
    }

    /**
     * Makes Board on a level from txt file of a map.
     *
     * Supported characters:
     * ' ' an empty square.
     * '#' a wall.
     * '.' coins to collect.
     * 'P' square for players.
     * 'G' a square with a gamer (enemy in the game).
     *
     * @param map The text representation of the board
     * @return The level as represented by text map.
     */
    public Level parsingTheMap(char[][] map) {
        Square[][] grid = new Square[map.length][map[0].length];

        List<Enemy> enemies = new ArrayList<>();
        List<Square> startPositions = new ArrayList<>();

        makeGrid(map, map.length, map[0].length, grid, enemies, startPositions);

        Board board = boardMaker.createBoardFromGrid(grid);
        Level theLevel = levelMaker.createLevel(board, enemies, startPositions);
        return theLevel;
    }

    private void makeGrid(char[][] map, int width, int height,
                          Square[][] grid, List<Enemy> enemies, List<Square> startPositions) {
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                char c = map[x][y];
                addSquare(grid, enemies, startPositions, x, y, c);
            }
        }
    }

    /**
     * Adds a square to the grid based on a given character. These
     * character come from the map files and describe the type
     * of square.
     *
     * @param grid The grid of squares with board[x][y] being the
     *            square at column x, row y.
     * @param enemies List of all enemies that were added to the map.
     * @param startPositions List of all start positions that were added
     *            to the map.
     * @param x coordinate of the square.
     * @param y coordinate of the square.
     * @param c Character describing the square type.
     */
    protected void addSquare(Square[][] grid, List<Enemy> enemies,
                             List<Square> startPositions, int x, int y, char c) {
        switch (c) {
            case ' ':
                grid[x][y] = boardMaker.createEmptySquare();
                break;
            case '#':
                grid[x][y] = boardMaker.createWall();
                break;
            case '.':
                Square coinsSquare = boardMaker.createEmptySquare();
                grid[x][y] = coinsSquare;
                levelMaker.createCoin().occupying(coinsSquare);
                break;
            case 'G':
                Square enemySquare = makeEnemySquare(enemies, levelMaker.createEnemy());
                grid[x][y] = enemySquare;
                break;
            case 'P':
                Square playerSquare = boardMaker.createEmptySquare();
                grid[x][y] = playerSquare;
                startPositions.add(playerSquare);
                break;
            default:
                throw new GameConfigurationException("Invalid character at "
                        + x + "," + y + ": " + c);
        }
    }

    /**
     * creates a Square with the specified enemy on it
     * and appends the placed enemy into the enemy list.
     *
     * @param enemies all the enemies in the level
     * @param enemy the newly created enemy to be placed
     * @return a square with the enemy on it.
     */
    protected Square makeEnemySquare(List<Enemy> enemies, Enemy enemy) {
        Square enemySquare = boardMaker.createEmptySquare();
        enemies.add(enemy);
        enemy.occupying(enemySquare);
        return enemySquare;
    }

    /**
     * Parses the list of strings into a 2-dimensional character array and
     * passes it on to parsingTheMap(char[][])
     *
     * @param text The plain text, with every entry in the list being a equally
     *            sized row of squares on the board and the first element being
     *            the top row.
     * @return The level as represented by the text.
     */
    public Level parsingTheMap(List<String> text) {

        int height = text.size();
        int width = text.get(0).length();

        char[][] map = new char[width][height];
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                map[x][y] = text.get(y).charAt(x);
            }
        }
        return parsingTheMap(map);
    }

    /**
     * Parses the provided input stream as a character stream and passes it
     * result to parsingTheMap(List).
     *
     * @param src The input stream that will be read.
     * @return The parsed level as represented by the text on the input stream.
     * @throws IOException
     */
    public Level parsingTheMap(InputStream src) throws IOException {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(
                src, "UTF-8"))) {
            List<String> linesOfMap = new ArrayList<>();
            while (reader.ready()) {
                lines.add(reader.readLine());
            }
            return parsingTheMap(linesOfMap);
        }
    }

    /**
     * Parses the provided input stream as a character stream and passes it
     * result to parsingTheMap(List).
     *
     * @param map Name of a resource that will be read.
     * @return The parsed level as represented by the text on the input stream.
     * @throws IOException
     */
    public Level parsingTheMap(String map) throws IOException {
        try (InputStream boardStream = parsingTheMap.class.getResourceAsStream(map)) {
            if (boardStream == null) {
                throw new GameConfigurationException("Something went wrong: " + map);
            }
            return parsingTheMap(boardStream);
        }
    }

    protected BoardMaker getBoardMaker() {
        return boardMaker;
    }
}

My test so far:
public class ParserTest {

private BoardMaker boardMaker;
private LevelMaker levelMaker;
private Parser parser;

@BeforeEach
void setUp() {
    levelMaker = mock(LevelMaker.class);
    boardMaker = mock(BoardMaker.class);

    parser = new Parser(levelMaker, boardMaker);
}

@Test
void parserTest() {
    List<String> map = Lists.newArrayList(
            "##########",
            "#........#",
            "#P      G#");

    Square square = new Square();

    Board board = mock(Board.class);
    Level level = mock(Level.class);
    Coin coin = mock(Coin.class);

    when(boardMaker.createWall()).thenReturn(square);
    when(boardMaker.createEmptySquare()).thenReturn(square);
    when(levelMaker.createCoin()).thenReturn(coin);
    when(boardMaker.createBoard(any(Square[][].class))).thenReturn(board);
    when(levelMaker.createLevel(any(Board.class), anyList(), anyList()))
            .thenReturn(level);

    //the level to compare with returned level from mapParser
    Level Level = parser.parsingTheMap(map);

    verify(boardMaker).createBoard(any(Square[][].class));
    verify(boardMaker).createEmptySquare();
    verify(boardMaker).createWall();
    verify(levelMaker).createLevel(any(Board.class), anyList(), anyList());
    verify(levelMaker).createCoin().occupying(any(Square.class));
}
}


text:
Q: Embedding python plugins in multithreaded C application A friend and I are trying to implement a python plugin service for one of our C applications. Ideally we would like for the plugins to run in their own thread. So far we have a plugin class that the user implements, a running plugin is just an instance of the user implemented class. We need the running plugin instances to be able receive messages from another thread.
We have what almost appears to be a working solution but are running into issues with the GIL. Does anyone have any suggestions for how to go about implementing this?
Thanks


text:
Q: sync data from file to database Scenario
I have employee objects in a file(flat file), each row representing one employee record
I have employee objects in Database table employee
I want to sync the records in file to table employee
insert those which are not in table
update those which are there, but some fields are updated
delete those records which aer not in file, but exists in table
One simple solution(not sure, if this is correct) I can think of :
delete all the records from Dababase table, and insert all the reocrds in file to table
But I want to update those, which exists already, but one or more field is changed
Note: employee_id is unique/primary key to identify a record, and there are no duplicate records in file or table

A: You can create a temporary table which has the same columns with the employee table.  Load the data from the file to the temporary table first, and then it's pure sql operation.
For example, delete those not in the file
Delete from employee where employee_id not in (select employee_id from employee_tmp);

insert those in the file but not in the table
insert into employee select * from employee_tmp where empoyee_id not in (select employee_id from employee)