text:
Q: Nested redux state updates triggers render on each siblings Description: I am trying to update a state of a nested object. While updating the nested object, I see its sibling component's render method is also being called.
Expected behavior: From all the articles I have been through, it specifies if I return a new object with only updated nested object, react is smart enough to render only updated object.
Example:
reducer.tsx
// imports

const initialState = {
  firstLevel: {
    secondLevel: {
      jobLevel: {
        id: 'L52';
      },
      expectedSalary: {
        amount: '100000';
      }
    }
  }
}

export interface State {
  firstLevel: {
    secondLevel: {
      jobLevel: {
        id: string;
      },
      expectedSalary: {
        amount: string;
      }
    }
  }
}

export const mainState = (state: State = initialState, action) => {
  switch(action.type) {
    case 'NESTED_UPDATE':
      return {
        ...state,
        firstLevel : {
          secondLevel: {
            ...state.firstLevel.secondLevel,
            expectedSalary: {
              amount: '120000'
            }
          }
        }
      }
  }

}

So in the above redux state, I am not mutating state, to start with. I am returning new object which has change in > firstLevel.secondLevel.expectedSalary object. While firstLevel.secondLevel.jobLevel object is not changed.
Components:
Main.tsx
// imports
class MainSection extends Component<> {
  // constructor and more logic

  render() {
    return (

        <JobLevel {...props.firstLevel.secondLevel} />

        <ExpectedSalary
          {...props.firstLevel.secondLevel}
          updateSecondLevel={this.props.updatedSecondLevel} //I know its included in props, for readability
        />

  }
}

export default MainSection;

MainContainer.jsx
import {connect} from 'react-redux';
import {SplitActions, CreateRuleState} from '../types';
import RuleSplitSection from '../components/RuleSplitSection';
import Actions from '../actions/RuleDrawerActions';
import {calculateSplitRuleLineWidth} from '../utils/RuleUtil';

export const mapStateToProps = (state) => {
    return state;
};

export const mapDispatchToProps = dispatch => {
    return {
        updateSecondLevel: () => dispatch(Actions.updateSecondLevel())
    };
};

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(Main as any);

Subcomponents:
JobLevel.jsx
class JobLevel extends Component<> {
  // constructor and more logic

  render() {
    return (
      // debug point 1

        // assume TextField is another redux util component which takes some props as below.
        <TextField
          value={this.props.jobLevel}
          disabled // read only
        />

  }
}

ExpectedSalary.jsx
class ExpectedSalary extends Component<> {
  // constructor and more logic

  updateExpectedSalarySecondLevel = evt => {
    const expectedSalaryObj = {amount: evt.target.value}
    this.props.updateSecondLevel('expectedSalary', expectedSalaryObj);
  }

  render() {
    return (
      // debug point 2

        // assume TextField is another redux util component which takes some props as below.
        <TextField
          onChange={this.updateExpectedSalarySecondLevel}
          value={this.props.expectedSalary}
        />

  }
}

Scenario: In above case, when I type anything in ExpectedSalary Textfield, I am hardcoding the value to '120000' for now. My understanding was when I updated ExpectedSalary subobject, react is smart enough to just re-render ExpectedSalary sub component. But from debugging it, I am seeing that it stops at both debug point 1 and 2.
I was wondering why???
Now to avoid re-rendering of JobLevel I need to use shouldComponentUpdate and check deep copy  like below:
    shouldComponentUpdate(nextProps) {
        return this.props.jobLevel.id !== nextProps.jobLevel.id;
    }

So my questions would be:
 1. Going inside render method of JobLevel is part of react life-cycle?
 2. If so, do I need to avoid it? Is it expensive process?
Let me know is comments if more code reference is required. I have excluded Actions file from the code simple from boredom of typing here.

A: By default react re-renders all components on every re-render. You need to mark a component as Pure and have stable props, or implement componentDidUpdate as you've done to avoid a re-render. react-redux does this for connected components.
In your case there are couple of things necessary to avoid re-rendering JobLevel. The first is to extend PureComponent instead of Component and the second is to only pass in the necessary props at the call site.
import {PureComponent} from 'react';

class JobLevel extends PureComponent<> {
  // constructor and more logic
  ...
}

And right now when you're rendering JobLevel you are spreading all of ...props.firstLevel.secondLevel which includes the expectedSalary key which is changing. You will need to only pass the required, stable props:
<JobLevel jobLevel={props.firstLevel.secondLevel.jobLevel} />
Otherwise you are essentially doing
<JobLevel
  jobLevel={props.firstLevel.secondLevel.jobLevel}
  expectedSalary={props.firstLevel.secondLevel.expectedSalary}
/>

so since the expectedSalary prop is changing, the component will be re-rendered even if JobLevel is marked Pure. React cannot introspect your render code to know which props are being used or not - it does a shallow comparison across all props that are passed to decide if a PureComponent needs to be re-rendered.


text:
Q: Table aligning left when elements are shown I have this HTML code:

        <FORM name=myForm>

                        Quiz/Test Title:

                            <INPUT size=25 type=text name=t>

                            <input type="button" value="Show/Hide" onclick="showStuff('multiplechoice')">

Multiple Choice

                            Section Name:

                                <INPUT size=20 type=text name=section1>

                            Directions:

                                <INPUT size=71 type=text name=directions1>

                            Question Number:

                                <INPUT size=2 type=text name=n1 id=n1 value=1 onkeypress="return alpha(event,numbers)">

                            Question:

                                <textarea rows=2 cols=55 name=q1 id=q1></textarea>

                            Answer A:

                                <INPUT size=35 type=text name=a1>

                            Answer B:

                                <INPUT size=35 type=text name=b1>

                            Answer C:

                                <INPUT size=35 type=text name=c1>

                            Answer D:

                                <INPUT size=35 type=text name=d1>

                            Answer (A,B,C,D):

                                <INPUT size=1 type=text name=correct1 onkeyup="upper(this)" onkeypress="return alpha(event,letters)" maxlength="1">

        </FORM>

Ok so the problem is when I click show/hide it shows the form, but it moves everything in the form over to the left. I would like it to stay all aligned in the center. Is there anyway to do this? I left out all the other functions I have linked to everything else, so don't worry about that it all works. Any help is greatly appreciated.

A: why don't you place your two TBodys into separate table?
something like below:
<FORM name=myForm>

             Quiz/Test Title:

                <INPUT size=25 type=text name=t>

             <input type="button" value="Show/Hide" onclick="showStuff('multiplechoice')">

Multiple Choice

            Section Name:
            <INPUT size=20 type=text name=section1>

            Directions:
            <INPUT size=71 type=text name=directions1>

            Question Number:
            <INPUT size=2 type=text name=n1 id=n1 value=1 onkeypress="return alpha(event,numbers)">

            Question:
            <textarea rows=2 cols=55 name=q1 id=q1></textarea>

            Answer A:
            <INPUT size=35 type=text name=a1>

            Answer B:
            <INPUT size=35 type=text name=b1>

            Answer C:
            <INPUT size=35 type=text name=c1>

            Answer D:
            <INPUT size=35 type=text name=d1>

            Answer (A,B,C,D):
            <INPUT size=1 type=text name=correct1 onkeyup="upper(this)" onkeypress="return alpha(event,letters)"   maxlength="1">

</FORM>

it fixes everything. see this working codepen

redpajama_set_name: RedPajamaStackExchange


text:
Q: Error message when using drawimage() on a pushed canvas object, not helped by preloading() When trying to draw an image on an obstacle in an html canvas game I get this error message: Uncaught InvalidStateError: Failed to execute 'drawimage' on 'CanvasRenderingContext2D': The HTMLImageElement provided is in the 'broken' state.
The obstacle is invisible but the game still stops if the player collides with where it should be. The other stationary obstacles' images in the game are visible. What do I do?
I tried uploading the images in my html as a preload() function but it still doesn't work. Other articles about similar situations do not cover this same context and do not help me who is quite new to programming.
Here is the code:
<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" type="text/css" href="stylesheet.css"> <link/>

 My Lost Game

Press the 'up', 'down', 'left' and 'right' keys on your keyboard to move. Avoid the obstacles and reach the goal.

A: You need to create a  separate image object for each image
The code below loads images from an array of image URLs and returns an array of images in the same order as the URL names
var loading = 0; // number of images still loading
function preloader(imageURLs){
    // function creates and loads an image
    function createImage(url){
        loading += 1; // count up when loading images
        const image = new Image;
        image.src = url;
        image.onload = () => loading -= 1;  // count down when loaded
        return image;
    }
    const images = imageURLs.map(createImage);
    return images;
}
const imageList = preloader(["player.jpg", "player2.jpg", "obstacle3.jpg"]);
// at this point loading greater than zero

When loading is 0 you know all images have loaded
Thus in your render loop
function mainLoop(){

    if(loading === 0){ // all images have loaded
        ctx.drawImage(imageList[0],0,0);  // draw first image
        ctx.drawImage(imageList[1],0,0);  // draw second image
        ctx.drawImage(imageList[2],0,0);  // draw third image
    }

    requestAnimationFrame(mainLoop);
}
requestAnimationFrame(mainLoop);

Or you can have it call a function when all loaded
var loading = 0; // number of images still loading
function preloader(imageURLs, callback){
    // function creates and loads an image
    function createImage(url, callback){
        loading += 1; // count up when loading images
        const image = new Image;
        image.src = url;
        image.onload = () => {
            loading -= 1;  // count down when loaded
            if(loading === 0){ // all done
               callback();  // call callback
            }
        }
        return image;
    }
    const images = imageURLs.map(createImage);
    return images;
}
function start(){  // function to start main loop when images have loaded
    requestAnimationFrame(mainLoop);
}
// second argument is the callback function that is called when all images have loaded
const imageList = preloader(["player.jpg", "player2.jpg", "obstacle3.jpg"], start);
function mainLoop(){
    ctx.drawImage(imageList[0],0,0);  // draw first image
    ctx.drawImage(imageList[1],0,0);  // draw second image
    ctx.drawImage(imageList[2],0,0);  // draw third image
    requestAnimationFrame(mainLoop);
}


text:
Q: How To Add An "a href" Link To A "div"? I need to know how to add an a href link to a div? Do you put the a href tag arounf the entire "buttonOne" div? Or should it be around or inside the "linkedinB" div?
Here's my HTML:

A: try to implement with javascript this:

some stuff

A: In this case, it doesn't matter as there is no content between the two divs.
Either one will get the browser to scroll down to it.
The a element will look like:
buttonOne

Or:
linkedinB

A: Try creating a class named overlay and apply the following css to it:
a.overlay { width: 100%; height:100%; position: absolute; }

Make sure it is placed in a positioned element.
Now simply place an  tag with that class inside the div you want to be linkable:

PhilipK's suggestion might work but it won't validate because you can't place a block element (div) inside an inline element (a). And when your website doesn't validate the W3C Ninja's will come for you!
An other advice would be to try avoiding inline styling.

A: Can't you surround it with an a tag?

A: I'd say:

However, it will still be a link. If you want to change your link into a button, you should rename the #buttonone to #buttonone a { your css here }.

A: Your solutions don't seem to be working for me, I have the following code. How to put link into the last two divs.

Flat and Modern Buttons

Border Stylin'

See the movies list

Avail a free rental day


text:
Q: Проблема с переопределением std::function и снова доброго вечера всем форумчанам.
Возникла проблема с переопределением объектов std::function<void()>
и будто вещь это не особо сложная, а разобраться никак не получается.
есть у меня некоторый класс:
введите код здесь
#include <functional>
class ProcessEventHandler
{
public:
      std::function<void()> ProcessCrashHandler;
      std::function<void()> ProcessStopHandler;
};

с его помощью я буду реализовывать Колбек в следующий класс
class ProcessManager : public ProcessEventHandler
{
public:
ProcessManager(const std::string &sFilePath);
ProcessManager(const _int32 &ProcessID);
~ProcessManager();
............
private:
 void onProcessStart();
 void onProcessWatch();
 void onProcessCrash();
 void onProcessStopped();
 void onProcessManulyStop();
...........
};

проблема заключается в том, что для объектов
   std::function<void()> ProcessCrashHandler;
   std::function<void()> ProcessStopHandler;

в классе потомке нужно присвоить функции
void onProcessCrash();
void onProcessStopped();

пытаюсь это сделать в конструкторе
  ProcessManager::ProcessManager(const std::string &sFilePath) :
  m_ppiProcInfo(),
  m_sCommandLine(sFilePath),
  m_isRunning(false)
  {
  ProcessCrashHandler = onProcessCrash;
  ProcessStopHandler = &ProcessManager::onProcessStopped;

  m_pcEventLoger = new EventLogger(getCurrentDirPath());
  onProcessStart();
   }

я как только уже не пробовал ничего не получается, через лямда пробовал тоже не получилось. не могу понять то ли у меня руки кривые, или с компилятором-то не в порядке
Помогите пожалуйста
ошибки
 error C2679: binary '=' : no operator found which takes a right-hand operand of type 'overloaded-function' (or there is no acceptable conversion)
 error C3867: 'ProcessManager::onProcessCrash': function call missing argument list; use '&ProcessManager::onProcessCrash' to create a pointer to member

A: Не-не, так не пойдёт.
Дело в том, что onProcessCrash — не функция! Поэтому вы не сможете сохранить её не только в переменной типа std::function<void(void)>, но даже обыкновенному указателю на функцию типа void (*)(void).
На самом деле это функция-член, для её вызова вам нужен конкретный this. Привязка this осуществляется просто: при помощи std::bind.
Попробуйте так:
ProcessCrashHandler = std::bind(&ProcessManager::onProcessCrash, this);


text:
Q: How to determine is file a dll library using winapi I need to find all *.exe and *.dll files in selected directory (with subdirectories). For determining *.exe I use GetBinaryType, but I can't to determine that current file is dll.
The part of code
if (GetBinaryType(wName, &binaryType) || /*condition: if wName is DLL*/) {
    System::Diagnostics::Debug::WriteLine(fName);
}

A: Just read IMAGE_FILE_HEADER record of file. If Characteristics field contain IMAGE_FILE_DLL flag - you have dll.


text:
Q: Creating a non-generic entity derived from a generic abstract class in Entity Framework I've already seen Generics and inheritance in C# but I'm not sure if it's exactly the same thing.
Suppose that I have a user entity in my database:
public abstract class User{ ... }

I have some classes derived from it:
public class NormalUser : User { ... }
public class SuperUser : User { ... }

I have the appropriate DbSets in my context for both derived classes (and not for User base class, obviously). There is no problem up to here.
Now, I want to create some other object called Attachment, that all users can have. But this is an abstract class. It will not be implemented solely, but I know that it will be created by some subclass of the User. I could directly try out a User property, but no, in the derived classes, I'd like to have a strongly typed user property that is mapped to NormalUser or SuperUser (or any other).
I've ended up like this:
public abstract class Attachment<T> where T : User
{
    ...

    public long CreatorId { get; set; }
    public virtual T Creator { get; set; }

}

I know that Entity Framework does not support generics, but I'm not having Attachment itself as an entity. Now, I've created a derived class, replacing the generic as required:
public class NormalUserAttachment : Attachment<NormalUser> {

   public string SomeExtraDataJustForNormalUserAttachments{get;set;}
   ...
}

Now, I've got a new class that is derived from Attachment and has it's properties with NormalUser as the User type.
However, when I try to run the app (automatic migrations enabled) I'm getting an error with dbo.NormalUserAttachment not existing.
Why would this be happening? I'm not directly using a generic type, I'm using a non-generic type that is derived from a generic type, but with all the generics replaced with actual types. Is it still not supported, or is it something else? I'm on Entity Framework 6.1.3, code-first.


text:
Q: form styling vertical align I am having trouble styling a form.  The section labelled destination group I cannot get it to align vertically.  See screenshot below.  I have added color borders to help with debugging of the css.

I have created a js fiddle for this
http://jsfiddle.net/uuNTC/
Below is a stripped down version of the code
HTML

Dates

          <input type="text" value="03/09/2012" name="dateFrom" id="dateFrom" class="dateInputs">
          <input type="text" value="09/09/2012" name="dateTo" id="dateTo" class="dateInputs">

Include "On Request" With:

      <select name="onRequest" id="onRequest">
          <option selected="selected" value="1">Stop Sell</option>
          <option value="2">Available</option>
      </select>

Destination Group:

          <select size="10" multiple="multiple" name="destinationGroups[]" id="destinationGroups">

            <option value="Tunisia All">Tunisia All</option>
            <option value="Turkey All">Turkey All</option>
            <option value="Turkey PNR">Turkey PNR</option>
            <option value="UAE Abu Dhabi ">UAE Abu Dhabi </option>
            <option value="UAE All Dubai">UAE All Dubai</option>
            <option value="VIE">VIE</option>
            <option value="VIE">MORE</option>
            <option value="VIE">MORE</option>
            <option value="VIE">MORE</option>
            <option value="VIE">MORE</option>
            <option value="VIE">MORE</option>
            <option value="VIE">MORE</option>
          </select>

the css
ul#ulFilterList,
ul#ulFilterList li  { margin: 0px; padding: 0px }

.dateInputs { margin:0px; text-align:left; width: 50px; display: inline-block;   }

#ulFilterList { width: 100% }

ul#ulFilterList li
{
  list-style:none;
  margin-bottom: 5px;
  border: solid 1px blue;
}

.filterLabel {
    font-weight: normal;
    width: 29%;
    display: inline-block;
    text-align:right;
    height: 100%;
    font-size: 11px ;
    margin-top: auto
}

A: One of the benefits of using display: inline-block; is that you can specify a vertical-alignment. In this fiddle I've set the vertical-alignment for the .filterLabel elements to vertical-align: top;. On the down-side, you'll need to return to the default vertical-align: baseline; for labels that are next to single-line inputs (the "Dates" and "Include 'On Request' With" labels), or style the corresponding INPUT elements upwards a bit.


text:
Q: Magento - Extending Topmenu.php block stops the topmenu.phtml template loading I'm extending app/code/core/Mage/Page/Block/Html/Topmenu.php with the following xml:
<config>
    <modules>
        <Custom_Menu>
            <version>1.0</version>
        </Custom_Menu>
    </modules>
    <global>
        <blocks>
            <page>
                <rewrite>
                    <html_topmenu>Custom_Menu_Block_Page_Html_Topmenu</html_topmenu>
                </rewrite>
            </page>
        </blocks>
    </global>
</config>

And my class definition:
class Custom_Menu_Block_Page_Html_Topmenu extends Mage_Page_Block_Html_Topmenu
{

}

Even with my class not overriding any methods, the following template file just doesn't get processed:
app/design/frontend/base/default/template/page/html/topmenu.phtml

I'm not overriding the template file.
As soon as I disable my module, it starts working again.
Do I need to declare anything else in my xml file?

A: Do this change in your config.xml file
<html_topmenu>Custom_Menu_Block_Html_Topmenu</html_topmenu>

and change your class name to
class Custom_Menu_Block_Html_Topmenu extends Mage_Page_Block_Html_Topmenu
{

}

A: One thing springs to mind. You may have your class file in the wrong place.  Your rewrite code looks correct, so when Magento instantiates a page/html_topmenu block it correctly resolves it to your Custom_Menu_Block_Page_Html_Topmenu class name.  However, Magento may not be able to find the class Custom_Menu_Block_Page_Html_Topmenu.  Try running the code
$block = new Custom_Menu_Block_Page_Html_Topmenu;
var_dump($block);

from an empty controller and/or bootstrap file to ensure that Magento can find your class.  It also wouldn't hurt to run
$block = Mage::getSingleton('core/layout')->createBlock('page/html_topmenu');
var_dump($block);

To ensure your rewrite is doing what it needs to do.


text:
Q: Get elastic beanstalk environment variables in docker container So, i'm trying not to put sensitive information on the dockerfile. A logical approach is to put the creds in the ebs configuration (the GUI) as a ENV variable. However, docker build doesn't seem to be able to access the ENV variable. Any thoughts?

FROM jupyter/scipy-notebook

USER root

ARG AWS_ACCESS_KEY_ID
RUN echo {$AWS_ACCESS_KEY_ID}

A: I assume that for every deployment you create a new Dockerrun.aws.json file with the correct docker image tag for that deployment. At deployment stage, you can inject environment values which will then be used in docker run command by EB agent. So your docker containers can now access to these environment variables.

A: Putting sensitive information (for a Dockerfile to use) can be either for allowing a specific step of the image to run (build time), or for the resulting image to have that secret still there at runtime.
For runtime, if you can use the latest docker 1.13 in a swarm mode configuration, you can manage secrets that way
But the first case (build time) is typically for passing credentials to an http_proxy, and that can be done with --build-arg:
 docker build --build-arg HTTP_PROXY=http://...

This flag allows you to pass the build-time variables that are accessed like regular environment variables in the RUN instruction of the Dockerfile.
  Also, these values don't persist in the intermediate or final images like ENV values do.

In that case, you would not use ENV, but ARG:
ARG <name>[=<default value>]

The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag


text:
Q: Concatenate a numpy array of strings to numpy array of numbers I am learning multiple linear regression in python, and for one particular instance I have the following equation: y=b+m1x1+m2x2+...+m5x5. I will like to print out the  same equation on my terminal in the same format with the values inserted for m and b
As of now I have the following code implemented:
insert numpy as np
from sklearn.linear_model import LinearRegression
regressor = LinearRegression()
...
print("b= ",regressor.intercept_) # b= 42467.529248548686
m= np.array(regressor.coef_)
print(m) # [8.66e+01 -8.73e+02  7.86e+02  7.73e-01  3.29e-02  3.66e-02]
x_var= ['x'+ str(i) for i in range(1,6)]
print(x_var) # it gives ['x1', 'x2', 'x3', 'x4', 'x5']

I know that my question might be super basic, but how should how do I concatenate the numpy array of integers m with array of strings x_var?
Thanks in advance.

A: you can use the zip function:
equation = []
for coef, var in zip(m, [''] + x_var):
    equation.append(str(coef) + var)

print(" + ".join(equation))

or
equation = [str(m[0])]
for coef, var in zip(m[1:], x_var):
    equation.append(str(coef) + var)

print(" + ".join(equation))


text:
Q: Getting app binary not found error detox test Getting error running detox test
Below is my Package.json
{
  "name": "TDD",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "jest tests/**/*.spec.js"
  },
  "dependencies": {
    "react": "16.8.3",
    "react-native": "0.59.9"
  },
  "devDependencies": {
    "@babel/core": "^7.4.5",
    "@babel/runtime": "^7.4.5",
    "babel-jest": "^24.8.0",
    "detox": "^12.11.1",
    "enzyme": "^3.10.0",
    "enzyme-adapter-react-16": "^1.14.0",
    "jest": "^24.8.0",
    "metro-react-native-babel-preset": "^0.54.1",
    "react-test-renderer": "16.8.3"
  },
  "jest": {
    "preset": "react-native",
    "setupFiles": [
      "./tests/setup.js"
    ]
  },
  "detox": {
    "test-runner": "jest",
    "configurations": {
      "ios.sim.debug": {
        "binaryPath": "ios/build/Build/Products/Debug-iphonesimulator/TDD.app",
        "build": "xcodebuild -project ios/TDD.xcodeproj -scheme TDD -configuration Debug -sdk iphonesimulator -derivedDataPath ios/build",
        "type": "ios.simulator",
        "name": "iPhone X"
      }
    }
  }
}

Getting below error:
detox[11148] INFO:  [test.js] configuration="ios.sim.debug" artifactsLocation="artifacts/ios.sim.debug.
2019-06-16 12-34-53Z" recordLogs="none" takeScreenshots="manual" recordVideos="none" recordPerformance=
"none" reportSpecs=true node_modules/.bin/jest --config=e2e/config.json --maxWorkers=1 '--testNamePatte
rn=^((?!:android:).)*$' "e2e"

detox[11149] INFO:  [DetoxServer.js] server listening on localhost:50040...

detox[11149] ERROR: [index.js/DETOX_INIT_ERROR]

Error: app binary not found at '/path/TDD/ios/build/Build/Products/Debug-iphonesimulator/TDD.app', did you build it?
    at Device._getAbsolutePath (/path/TDD/node_modules/detox/src/devices/Device.js:249:13)
    at Device.prepare (/path/TDD/node_modules/detox/src/devices/Device.js:18:29)
    at Detox.init (/path/TDD/node_modules/detox/src/Detox.js:70:23)
    at process._tickCallback (internal/process/next_tick.js:68:7)
Example: should show the welcome message
Example: should show the welcome message [FAIL]

 FAIL  e2e/firstTest.spec.js
  Example
    ✕ should show the welcome message (3ms)

  ● Example › should show the welcome message

    app binary not found at '/path/TDD/ios/build/Build/Products/Debug-iphonesimulator/TDD.app', did you build it?

      at Device._getAbsolutePath (../node_modules/detox/src/devices/Device.js:249:13)
      at Device.prepare (../node_modules/detox/src/devices/Device.js:18:29)
      at Detox.init (../node_modules/detox/src/Detox.js:70:23)

  ● Example › should show the welcome message

    ReferenceError: device is not defined

      1 | describe('Example', () => {
      2 |   beforeEach(async () => {
    > 3 |     await device.reloadReactNative();
        |           ^
      4 |   });
      5 |
      6 |   it('should show the welcome message', async () => {

      at device (firstTest.spec.js:3:11)
      at tryCatch (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:45:40)
      at Generator.invoke [as _invoke] (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:271:22)
      at Generator.prototype.(anonymous function) [as next] (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:97:21)
      at tryCatch (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:45:40)
      at invoke (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:135:20)
      at ../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:170:11
      at callInvokeWithMethodAndArg (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:169:16)
      at AsyncIterator.enqueue (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:192:13)
      at AsyncIterator.prototype.(anonymous function) [as next] (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:97:21)
      at Object.<anonymous>.exports.async (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:216:14)
      at Object._callee (firstTest.spec.js:2:14)

  ● Example › should show the welcome message

    ReferenceError: element is not defined

      4 |   });
      5 |
    > 6 |   it('should show the welcome message', async () => {
        |                                         ^
      7 |     await expect(element(by.id('welcome'))).toBeVisible();
      8 |   });
      9 | });

      at _callee2$ (firstTest.spec.js:6:41)
      at tryCatch (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:45:40)
      at Generator.invoke [as _invoke] (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:271:22)
      at Generator.prototype.(anonymous function) [as next] (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:97:21)
      at tryCatch (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:45:40)
      at invoke (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:135:20)
      at ../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:170:11
      at callInvokeWithMethodAndArg (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:169:16)
      at AsyncIterator.enqueue (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:192:13)
      at AsyncIterator.prototype.(anonymous function) [as next] (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:97:21)
      at Object.<anonymous>.exports.async (../node_modules/@babel/runtime/node_modules/regenerator-runtime/runtime.js:216:14)
      at Object._callee2 (firstTest.spec.js:6:41)

detox[11148] ERROR: [cli.js] Error: Command failed: node_modules/.bin/jest --config=e2e/config.json --m
axWorkers=1 '--testNamePattern=^((?!:android:).)*$' "e2e"

e2e -> init.js
const detox = require('detox');
const config = require('../package.json').detox;
const adapter = require('detox/runners/jest/adapter');
const specReporter = require('detox/runners/jest/specReporter');

// Set the default timeout
jest.setTimeout(120000);
jasmine.getEnv().addReporter(adapter);

// This takes care of generating status logs on a per-spec basis. By default, jest only reports at file-level.
// This is strictly optional.
jasmine.getEnv().addReporter(specReporter);

beforeAll(async () => {
  await detox.init(config);
});

beforeEach(async () => {
  await adapter.beforeEach();
});

afterAll(async () => {
  await adapter.afterAll();
  await detox.cleanup();
});

firstTest.Spec.js
describe('Example', () => {
  beforeEach(async () => {
    await device.reloadReactNative();
  });

  it('should show the welcome message', async () => {
    await expect(element(by.id('welcome'))).toBeVisible();
  });
});

A: If you can successfully run detox build then try to do this:

*

*Check that your build's output binary is in the directory you specify in binaryPath in package.json

*Change display name of your app in Xcode and change it accordingly in binaryPath

*Run detox build and detox test

*Change your app's display name back in Xcode and in package.json

*Run detox build and detox test
It worked for me


text:
Q: How do I lock the screen orientation to portrait in Safari using plain JavaScript? I want to "lock" the orientation of the website to portrait mode in safari using pure javascript.
Let's say that I am building an application, I don't want users to be able to visit my app in landscape-mode. How do I do that?

Edit: I make the app in web-languages, I will assign it as a profile so anyone can download it on iPhone, so nothing with xCode or something.

A: the screen.lockOrientation method is not supported by Safari, so you'll have to do feature detection.
For Safari, you might try the ponyfill: https://github.com/chmanie/o9n

A: maybe using "windows.screen" work for you;
var alowed = window.screen.orientation.lock("portrait");


text:
Q: How to get Word 2003 to make my print layout go from left to right? My copy of MS Word 2003 was installed on my computer with the locale set to Israel, so among other things my Normal.dot template was set up for right-to-left.  I managed to fix most of the Hebrew support things so that I am working in English by default now.  The only thing I haven't found a cure for is how to make the "print layout" view also go from left to right; as things are, the page flow always appears from right to left, even in English documents - IOW, page 1 appears on the right of page 2, as shown below.

I can't see any obvious option to change this.  How do I do it?

A: Your normal.dot file looks fine and even using a machine set to Israel/Hebrew, I am unable to find a fix, but here are some observations and hopefully it can lead you to an answer.
I think that this is down to the regional options of your machine.
When using Hebrew on an English machine, I default left to right.

When I change to Israeli/Hebrew, it still acts "the English way", my guess is that you need to look in the Office installation files and see if you can install the English proofing tools - you may also want to try changing your machines default language to English and see if that changes things.
However, again, wether Hebrew or English, your normal.dot works on my machine even when set to Hebrew/Israel.


text:
Q: AOP Advice around RequestMapping How can I create a Pointcut around my methods annotated with @RequestMapping?
I have a Pointcut defined that I'd like to restrict a bit further:
@Pointcut("execution(public * company.controllers.AbstractController+.*(..))")
public void methodPointcut() { }

Is it possible to further restrict that to only methods which are annotated with @RequestMapping?
I tried adding && @annotation to the end of the Pointcut, but that is not a well formed Pointcut.

A: You can specify annotations in a pointcut:
@Pointcut("execution(@RequestMapping public * company.controllers.AbstractController+.*(..))")
public void methodPointcut() { }

Is this something you've already tried?

A: I think this was easiest to do with two Pointcuts.
@Pointcut("execution(public * company.controllers.AbstractController+.*(..))")
public void methodPointcut() {}

and
@Pointcut("within(@org.springframework.web.bind.annotation.RequestMapping *)")
public void requestMapping() {}

Then simply doing:
@Before("methodPointcut() && requestMapping()")


text:
Q: How to activate the splitter in Notepad++? The Notepad++ v7.6.2 release notes reveal a new feature:

*Add new feature: double click splitter resets panes to equal size.

How does one enable the splitter to begin with?

A: Right click the file name in the tab bar and select Move/Clone to Other view.


text:
Q: Insert a value to a column by condition I am attempting to fill in a new column in my dataset. I have a dataset containing information on football matches. There is a column called "Stadium", which has various stadium names. I wish to add a new column which contains the country of which the stadium is located within. My set looks something like this
Match ID       Stadium
1              Anfield
2              Camp Nou
3              Stadio Olimpico
4              Anfield
5              Emirates

I am attempting to create a new column looking like this:
Match ID       Stadium            Country
1              Anfield              England
2              Camp Nou             Spain
3              Stadio Olimpico      Italy
4              Anfield              England
5              Emirates             England

There is only a handful of stadiums but many rows, meaning I am trying to find a way to avoid inserting the values manually. Any tips?

A: You want to get the unique stadium names from your data, manually create a vector with the country for each of those stadiums, then join them using Stadium as a key.
library(dplyr)

# Example data
df <- data.frame(`Match ID` = 1:12,
                 Stadium = rep(c("Stadio Olympico", "Anfield",
                                 "Emirates"), 4))

# Get the unique stadium names in a vector
unique_stadiums <- df %>% pull(Stadium) %>% unique()

unique_stadiums
#> [1] "Stadio Olympico" "Anfield"         "Emirates"

# Manually create a vector of country names corresponding to each element of
# the unique stadum name vector. Ordering matters here!
countries <- c("Italy", "England", "England")

# Place them both into a data.frame
lookup <- data.frame(Stadium = unique_stadiums, Country = countries)

# Join the country names to the original data on the stadium key
left_join(x = df, y = lookup, by = "Stadium")
#>    Match.ID         Stadium Country
#> 1         1 Stadio Olympico   Italy
#> 2         2         Anfield England
#> 3         3        Emirates England
#> 4         4 Stadio Olympico   Italy
#> 5         5         Anfield England
#> 6         6        Emirates England
#> 7         7 Stadio Olympico   Italy
#> 8         8         Anfield England
#> 9         9        Emirates England
#> 10       10 Stadio Olympico   Italy
#> 11       11         Anfield England
#> 12       12        Emirates England


text:
Q: Rust scoping rules for struct-owned functions I am trying to understand what exactly the scope is for functions defined within an impl block but which don't accept &self as a parameter.  For example, why doesn't the following chunk of code compile? I get the error "cannot find function generate_a_result in this scope".
pub struct Blob {
    num: u32,
}

impl Blob {
    pub fn new() -> Blob {
        generate_a_result()
    }

    fn generate_a_result() -> Blob {
        let result = Blob {
            num: 0
        };

        result
    }
}

A: These functions are called associated functions. And they live in the namespace of the type. They always have to be called like Type::function(). In your case, that's Blob::generate_a_result(). But for referring to your own type, there is the special keyword Self. So the best solution is:
Self::generate_a_result()


text:
Q: With ActiveMQ Artemis is it possible to find out if a listener has stopped listening to a topic? I'm using ActiveMQ Artemis 2.18.0 and some Spring Boot clients that communicate with each other via topics. The Spring Boot clients use JMS for all MQTT operations.
I'd like to know if it is possible for a producer with one or more subscribers to find out whether a certain subscriber is actively listening or not. For example, there are 3 clients - SB1, SB2, and SB3. SB1 publishes to test/topic, and SB2 and SB3 are subscribed to test/topic. If SB2 shuts down for any reason would it be possible for SB1 to become aware of this?
I understand that queues would be the way to go for this, but my project is much better suited to the use of topics, and it is set up this way already and works fine. There's just one operation where it must be determined whether the listener is active or not in order to update the listener's online status, a crucial parameter. Right now, clients and the server continually poll a database so that the online status is periodically updated, I want to avoid doing this and use something that Artemis may provide instead.

A: Apache ActiveMQ Artemis emits notifications to inform listeners of potentially interesting events as consumer created or closed, see Management Notifications at http://activemq.apache.org/components/artemis/documentation/latest/management.html.
A listener of the management notification address would receive a message for each consumer created or closed, see the Management Notification Example at http://activemq.apache.org/components/artemis/documentation/latest/examples.html#management-notification

A: Part of the point to pub/sub based messaging is to decouple the information producer (publisher) from the consumer (subscriber). As a rule a published REALLY shouldn't care if there even are any subscribers.
If you want to know the status of the subscriber then it's up to the subscriber to update this, not the publisher. Things like the Last Will & Testament feature allow the subscriber to update it's status in the event of a failure to explicitly do it when going offline.


text:
Q: Python check if a string has characters I am processing 500GB of data to find only the lines which has Characters.
Can you suggest me a efficent/Faster way.
Data is like:
%^^%^^%^^%
This is a valid
*%^%^ Valid
This is not a valid one

output should be:
Data is like:
This is a valid
*%^%^ Valid
This is not a valid one

I am trying this:
isalpha()
issue is it will remoce the line
    *%^%^ Valid
Actuall some how this code is also not working
if line.isalpha()=='True':
  print(line)

This is not working...
can I use regular expressions but read some where it will slow it is that true?

A: Use regex, like:
>>> import re
>>>
>>> pattern = re.compile(r'\A[%|\^]*$')
>>>
>>> pattern.match('%^ Text')  # no match
>>> pattern.match('%^^%^')  # match
<re.Match object; span=(0, 5), match='%^^%^'>

A: You are not using isalpha correctly, it returns True when all characters in the string are alphabetic.
You could try using any and map to make sure at least one character is alphabet in the line.
txt = """
Data is like:
%^^%^^%^^%
This is a valid
*%^%^ Valid
This is not a valid one
"""

for line in txt.split("\n"):
    if any(map(str.isalpha, line)):
        print(line)

prints:
Data is like:
This is a valid
*%^%^ Valid
This is not a valid one


text:
Q: nth-child in Bootstrap3 not aligning properly I can't ever seem to get this to work, I have a simple bootstrap page with an image gallery that has images of different heights.  I am trying to use the nth-child to clear the left side after every fourth .col-md-3
Bootply smippet - http://www.bootply.com/7BhYr6J8rH
The content of the finished page is going to be dynamically populated from a database, so I need this flexibility to work. Can anybody point out where I'm going wrong?

A: Hard to explain but you are using nth-child on the image. Because there is no image list it will never reach a 4th image, each column has 1 image and no more. However, a row does contain a list of columns so I edited your code to clear by column like so http://www.bootply.com/7BhYr6J8rH:
.row .col-md-3:nth-child(5n) {
   clear:left;
}

Another idea, what you could do is add

 after each fourth column for the same result and cleaner code.


text:
Q: What is the problem in this code, i got leak in thos code?
Possible Duplicate:
Find out memory leak?

Problem with finding leak in this code, so please help me.
Thanks in advance.
Regards
ABMutableMultiValueRef phoneNumbers = ABRecordCopyValue(ref, kABPersonPhoneProperty);
        for(CFIndex j = 0; j < ABMultiValueGetCount(phoneNumbers); j++)
        {
            CFStringRef phoneNumberRef = ABMultiValueCopyValueAtIndex(phoneNumbers, j);
            NSString *phoneNumber = (NSString *) phoneNumberRef;

        contact.strMobileNo = phoneNumber;
        NSLog(@"phoneNO is %@", phoneNumber);
        CFRelease(phoneNumberRef);

        ABMultiValueRef emails = ABRecordCopyValue(ref, kABPersonEmailProperty);
        for(CFIndex k = 0; k < ABMultiValueGetCount(emails); k++)
        {
            CFStringRef emailRef = ABMultiValueCopyValueAtIndex(emails, k);
            NSString *mailid = (NSString *) emailRef;
            contact.strMail = mailid;
            NSLog(@"Email is %@", mailid);

            CFRelease(emailRef);

        }
        CFRelease(emails);

    }
    CFRelease(phoneNumbers);

A: If you are using Instruments to detect leaks, take into account the fact the leaks will show you the point where the leaked memory is allocated, not the point where the leak actually happens.
Your code seems right to me. You correctly release objects you get through AB methods. On the other hand, you assign a couple of the to ivars of your contact object. It could be possible that the leak happens there, so have a look also to the lifecycle of contact, or to any object containing it.


text: Q: Using 42 foot pipe sections to make 45 degree bend I was asked a question today regarding the number of 42 foot joints of steel pipe needed to make a 45 degree curve.  I was told that each joint of pipe could only be bent at a maximum of 2 degrees.  Can anyone provide me a formula to make this calculation in the future.?


text:
Q: JTree Conundrum: Tree vs. Branch by Vector Extension It seems that when I add a custom object to a JTree, the tree will recognize it as a branch if it extends Vector, but as a leaf when it does not. I'm designing a custom renderer to allow check boxes in all of my cells (both branches and trees). This would not be hard except that I want to be able to nest indefinitely.
This really isn't a code question, but more of a logic question. Basically the behavior I am trying to get it the same class with an optional Vector extension. I know that is not possible but that's the behavior that will be required to do this.
Here is my current JTree:

and here is the code that got me to that point.
Method in the GUI to produce JTree:
public void start() {
    CheckBoxLeaf node = new CheckBoxLeaf("1 Leaf");
    CheckBoxLeaf node2 = new CheckBoxLeaf("2 Leaf");

    CheckBoxLeaf node3 = new CheckBoxLeaf("Red Leaf");
    CheckBoxLeaf node4 = new CheckBoxLeaf("Blue Leaf");

    CheckBoxBranch parent = new CheckBoxBranch("Dr. ", new CheckBoxLeaf[]{node, node2});
    CheckBoxBranch parent2 = new CheckBoxBranch("Seuss", new CheckBoxLeaf[]{node3, node4});

    JTree tree = new JTree(new CheckBoxBranch[]{parent, parent2});
    tree.setCellRenderer(new custom.jtree.TreeCellRenderer());

    infoScroll = new JScrollPane(tree);
}

Leaf class:
public class CheckBoxLeaf {

    private final String text;

    public CheckBoxLeaf(String name) {
        text = name;
    }

    @Override
    public String toString() {
        return text;
    }
}

Branch class:
public class CheckBoxBranch extends Vector {

    private final String text;

    public CheckBoxBranch(String name, CheckBoxLeaf[] subNodes) {
        text = name;
        addAll(Arrays.asList(subNodes));
    }

    @Override
    public String toString() {
        return text;
    }
}

My renderer class really isn't important at the moment as it does nothing except force all cells to have JCheckBoxes.
This code in it's current state will just allow leafs to be nested into branches. It does not allow for branches to be nested within other branches which is what I'm attempting to do.
If anyone can offer up some help for me it would be greatly appreciated. Thanks!

A: to avoid showing arrows on leaf nodes, you can override following method in your tree model as shown below:
@Override
public boolean isLeaf(Object node){
    return node instanceof CheckBoxLeaf;
}


text:
Q: PIC18F45Q43 44 pin TQFP power supply I'm working on a project with PIC18F45Q43's 44 pin TQFP package. The PCB I designed had a power supply based on the 7805, but when I power the circuit; the PIC18F45Q43 burns out. I even tried powering with 3.3 V but it still burns out.
Surprisingly, when I power the 40 pin DIP package with the 7805; the circuit works completely fine.
What can be the cause of this? And what is the ideal power supply for the pic microcontrollers, especially the SMD packages?
Also, what is the best way to create 5 V and 3.3 V outputs for components in the same circuit using single input power source?

A: You issues are almost certainly PCB layout related, and the lack of supply decoupling capacitors at the PIC doesn't help either.
It also looks a lot like you've just let the auto-router do its thing all by itself with little to no supervision or rules - it's easy to spot when looking at your board by all the weird junctions and mismatched trace widths.
Some recommendations:

*

*Put 100nF decoupling caps at each pair of PIC supply pins. Physically locate these caps immediately adjacent to the PIC, and connect the cap directly to the PIC's pins (no wild loops or vias).

*Use bigger caps at the regulators, and place each of them physically close to the regulator they serve. Although the ones you have do technically meet the minimum spec for at least some regulator manufacturers, I don't know exactly who's "LM7805" or "LD1117" you're using, and their requirements may be different. Increase those caps by a factor of 10, and also ensure that the trace routing between the caps and their regulator pins is short & fat.

*Pay much closer attention to how you route the GND net all over your board. Some issues which jump out at me are:

*

*the tiny trace on the bottom side between R7 and "AWY" is the only GND link between the regulators and the rest of the board!

*another tiny trace on the bottom looping around C1 up to C2

*tiny trace off the top of "HOM" leading to a weird branch on the top side below "DISARM"

*and lots more examples like these all over the board

*I'd strongly recommend that you tear up all of your routing and manually route the GND net 1st, using traces with a width no less than 50mil. After that, route the Vcc and 3.3v nets with a similar width, as well as the supply to your "WIFI" coming from the "USE_3.3V" and "USE_5V" jumpers. Try as much as possible to keep all the GND and power traces together and on the same side of the board, only jumping to the other side for short hops where necessary and to avoid long loops.

*Once the power nets are manually routed, feel free to release the auto-router on the signals. None of these on your board are critical high-speed signals, so the messy result you get from an auto-router with no rules doesn't matter much, but once it's done - go back and do some manual cleanup! Move vias out of pads (for example at "DBL", C2, PIC pin-2, etc).
Get rid of weird unnecessary loops and junctions. Some examples in your existing layout:

*

*"LORA" pins 1-2 & 7

*fork in the GND net on the top side between "DISARM" and "HOME"

*Take a closer look at the pad & hole sizes you have for the various components - are the holes for the buttons large enough, and do the holes for the "PASS" LEDs need to be as large as they are? I would strongly consider enlarging the pads for your off-board connectors ("PROG", "WIFI", "SOUND") as well as the "LORA" module.

A: It's not easy to tell from the layout image, but it looks like the supply tracks are not properly connected to pins 28 and 29 of the TQFP package.

Also, the capacitors on your voltage regulators are too small, and bypass capacitors may not be close enough to the PIC pins. In fact, they do not appear to be any bypass capacitors at all.

A: As others have said, your layout is pretty bad. If you want easy layout the simplest way is to spring for a 4-layer board.
The proximate cause of the destruction of the MCUs can be found in the LD1117 datasheet:

Only a very common 10 µF minimum capacitor is needed for stability.

If the regulator is oscillating it can produce an output that oscillates almost up to the input voltage, which is very much not healthy for the chip.
The LD1117 is a very old regulator and the datasheet does not consider the possibility of a ceramic capacitor. If you don't want to use a tantalum or aluminum electrolytic, then use an (at least) 22uF ceramic capacitor (preferably rated for 10V) and add a couple ohms in series (due to voltage coefficient and too-low ESR).
The LM7805 is not going to oscillate in your circuit, however you still should have adequate bypass capacitors near the loads.


text:
Q: Calculating all possible intersections We have a data frame with one column for a category and one column for discrete values. We want to get all possible intersections (number of common values) for all combinations of categories.
I came up with the following code. However, is there something shorter out there? I am sure there is a better way of doing this, a specialized function that does exactly this. The code below can be shortened, of course, for example with purrr:map, but that is not my question.
## prepare an example data set
df <- data.frame(category=rep(LETTERS[1:5], each=20),
                 value=sample(letters[1:10], 100, replace=T))

cats <- unique(df$category)
n <- length(cats)

## all combinations of 1...n unique elements from category
combinations <- lapply(1:n, function(i) combn(cats, i, simplify=FALSE))
combinations <- unlist(combinations, recursive=FALSE)
names(combinations) <- sapply(combinations, paste0, collapse="")

## for each combination of categories, get the values which belong
## to this category
intersections <- lapply(combinations,
          function(co)
             lapply(co, function(.x) df$value[ df$category == .x ]))
intersections <- lapply(intersections,
    function(.x) Reduce(intersect, .x))
intersections <- sapply(intersections, length)

This brings us to my desired outcome:
> intersections
    A     B     C     D     E    AB    AC    AD    AE    BC
   20    20    20    20    20    10     8     8     9     8
   BD    BE    CD    CE    DE   ABC   ABD   ABE   ACD   ACE
    8     9     7     8     8     8     8     9     7     8
  ADE   BCD   BCE   BDE   CDE  ABCD  ABCE  ABDE  ACDE  BCDE
    8     7     8     8     7     7     8     8     7     7
ABCDE
    7

Question: is there a way of achieving the same result with less fuzz?

A: Here is a possible approach with data.table to cast the data.frame and model.matrix to count the higher-order interactions:

*

*Cast to wide-format by grouping all matching values between categories in the rows (credits to @chinsoon12 for the dcast syntax).

*Identify all higher-order interactions with model.matrix and sum over the columns.
library(data.table)

df_wide <- dcast(setDT(df), value + rowid(category, value) ~ category, fun.aggregate = length, fill = 0)
head(df_wide)
#>    value category A B C D E
#> 1:     a        1 1 1 1 1 1
#> 2:     a        2 1 0 0 1 1
#> 3:     a        3 0 0 0 1 0
#> 4:     b        1 1 1 1 0 1
#> 5:     b        2 1 0 1 0 1
#> 6:     c        1 1 1 1 1 1

colSums(model.matrix(~(A + B + C + D + E)^5, data = df_wide))[-1]
#>         A         B         C         D         E       A:B       A:C
#>        20        20        20        20        20        13        11
#>       A:D       A:E       B:C       B:D       B:E       C:D       C:E
#>        12        12        11        13        13        11        13
#>       D:E     A:B:C     A:B:D     A:B:E     A:C:D     A:C:E     A:D:E
#>        10         8         9         9         7         9         7
#>     B:C:D     B:C:E     B:D:E     C:D:E   A:B:C:D   A:B:C:E   A:B:D:E
#>         8         9         7         8         5         7         5
#>   A:C:D:E   B:C:D:E A:B:C:D:E
#>         5         6         4

Data
set.seed(1)
df <- data.frame(category=rep(LETTERS[1:5], each=20),
    value=sample(letters[1:10], 100, replace=T))


text:
Q: Kerb4j - How to get role name from SPNEGO Token? I'm trying to get the role name from the SPNEGO token returned by Active Directory for use with Spring Security authorization. I'm  using kerb4j to authenticate since my understanding is that it can get group (i.e. role) information from the token (instead of a subsequent LDAP query) by using this code.
In my Spring web security config, I have the following:
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Value("${app.service-principal}")
    private String servicePrincipal;

    @Value("${app.keytab-location}")
    private String keytabLocation;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

       http.exceptionHandling()
            .authenticationEntryPoint(spnegoEntryPoint())
            .and()
            .authorizeRequests().antMatchers("/", "/home").permitAll()
            .antMatchers("/hello").access("hasRole('ROLE_ADMIN')")
            .anyRequest().authenticated()
                .and()
                .formLogin().loginPage("/login").permitAll()
                .and()
                .logout().permitAll().and() //spring
                .addFilterBefore(spnegoAuthenticationProcessingFilter(authenticationManagerBean()),
                        BasicAuthenticationFilter.class);
    }

@Bean
public SpnegoAuthenticationProvider kerberosServiceAuthenticationProvider() {
    SpnegoAuthenticationProvider provider = new SpnegoAuthenticationProvider();
    provider.setTicketValidator(sunJaasKerberosTicketValidator());
    provider.setExtractGroupsUserDetailsService(new ExtractGroupsUserDetailsService());
    provider.setServerSpn(servicePrincipal);
    return provider;
}

ExtractGroupsUserDetailsService only gets a SID such as (S-1-2-20-132925241-12333....) rather than an AD group name such as ADMIN. How can ExtractGroupsUserDetailsService be written to extract the name of the group? Is this information available in the SPNEGO token?
Update
Simply replacing ROLE_ADMIN in the hasRole SpEL with the SID does not work.
Update 2
A given SID string is not matching SID string passed into hasRole because hasRole appends ROLE_ the passed in String. Once I changed ExtractGroupsUserDetailsService to prefix "ROLE_" to the SID (e.g. ROLE_S-1-2-20-132925241-12333....), the matching worked.
Still though... how can I get the group name (e.g. ADMIN) in ExtractGroupsUserDetailsService instead of the SID?

A:
ExtractGroupsUserDetailsService only gets a SID such as (S-1-2-20-132925241-12333....) rather than an AD group name such as ADMIN. How can ExtractGroupsUserDetailsService be written to extract the name of the group? Is this information available in the SPNEGO token?

No, the Kerberos PAC only contains SIDs, not names. (Windows access control is never based on names.) You will still need an LDAP search for those.


text:
Q: If I write an entire system based on Magento2, can I sell it to another individual? Based on Magento2 license agreement, if I write an entire system based on Magento2 platform, will it be considered as my legal property and can I sell my entire system to another individual ?
Currently, we are working on an enterprise level ecommerce solution based on Magento2 platform. We are making hundreds of extensions that overriding Magento's core functionalities without editing the core files, and just by overriding using well-written Magento2 extensions. We are not touching Magento2, and we don't sell/change/add/modify/rename it.
One of our concerns is its license and our business exit strategy: If we build our entire software based on Magento2 as its base platform and core of our software, will it be considered as our own property and not Magento's property ? Our business owner concern is that if we build it based on Magento2, it will be considered as Magento's property and it won't be ours and it will be too dangerous for his business.
But I think if we build extensions for Magento, there is no place in the agreement that confirms its extensions is not Magento's property. I think we shouldn't write the entire software from the beginning to consider it as our own property, right ? Am I missing something?


text:
Q: Rebinding a SQL Server user to its login after a restore with this user After performing a restore of a SQL Server (v12.0.2000) database, I figured that a user needs to be remapped to its login (this issue seems to be known as orphan users). And one of the simplest way to do it is to perform a :
use [MyDatabase];
alter user MyUser with login = MyUser;

Nevertheless, just after achieving a restore, the USE command fails because I'm trying to execute the above command with 'MyUser', which is the one that is orphaned...
Because it is in a script, I would like to avoid performing a restore with one user and a alter user with another user, in order the first user be correctly remapped to its login.
Is there a way to do this with 'MyUser' (who could connect to master without problem) ?
I tried it by fully qualifying 'MyUser' the following way without success :
use master;
alter user MyDatabase.MyUser with login = MyUser;

Any idea if this is possible and how to do it ?

A: Unfortunately no.  Remember that a database principal and a server principal are two separate objects.  Until you fix the orphan the server principal MyUser has no access to MyDatabase even though there is an orphaned user called MyUser in the database.
The other way to fix an orphan is to change the SID of the server principal to match that of the database principal.  This does have a risk of creating orphans in other databases and even more importantly in this case to do it you have to drop the principal and re-create it with the new SID.  Which of course isn't possible using that particular ID.
Your only method is going to be to fix this using a separate id with the appropriate permissions.  That could be an id with sysadmin permissions (which would have permissions to connect to the database even without an associated database principal) or an id that has DBO access on the database.  Note those are examples, there are several other permissions available that will allow you to modify server/database principals.

A: You could use sp_change_users_login to update the database user's SID:
https://msdn.microsoft.com/en-us/library/ms174378.aspx
Alternatively, you could script the login from the production server using sp_help_revlogin, drop the DR user and recreate it with the script:
https://support.microsoft.com/en-us/kb/918992


text:
Q: Removing listeners from an ace-editor With editor.on('change', ...) I added a listener, now I need to remove it again. editor.off(fromEditorOnReturnedFunction) didn't work.

A: off needs event name too
editor.on('change', fn)
editor.off('change', fn)

also note that on returns function it was passed, so editor.on('change', fn) == fn


text:
Q: Toggle WMS layer on/off with own button click on leaflet I've created a few maps and now i would like to publish them using leaflet and geoserver. Everything is working fine, i can change the layers using layer control, but i want to do that using my own buttons. The problem is that i cant figure out how. I have all the buttons created , and i just want to create a function that adds the wms tile layer to the map on click
Any help would be greatly appreciated. Here is what i tried so far but it doesnt work:
function appear(){
    var floodToday = L.tileLayer.wms("http://localhost:8080/geoserver/wms", {
        layers: 'FloodlayerWMS',
        format:'image/png',
        version: '1.1.1',
        transparent: true
    })
    map.addLayer(floodToday);
}
$(".WToday").on("click",appear);

I found this answer already:Hide/Show layerGroups in Leaflet with own Buttons but it hasn't proved useful. I'm guessing my problems are connected to the use of wms tile layers but i'm not sure how to go around it.
UPDATE
@HudsonPH's answer was a bit to complicated for me as I have almost no knowledge in Javascript and JQuery but after fiddling around with the code a bit and trying different options this is what works for me:
$("#WToday").click(function(event) {
    var floodToday = L.tileLayer.wms("http://localhost:8080/geoserver/wms", {
    layers: 'FloodlayerWMS',
    format:'image/png',
    version: '1.1.1',
    transparent: true
    })
map.addLayer(floodToday);
});

Thank you all for trying to help me.

A: you can use trim to compare the names and trigger a event.
Obs: I used data-attribute to get the value
 $("[name='leaflet-base-layers']").parent().each(function (index) {
            $layerControl = $(this);
            if ($that.attr("Your-Date-Attribute").trim() == $layerControl.find("span").text().trim()) {
                $(this).find("input").trigger("click");
            }
        });


text:
Q: Refactoring code to allow for unit testing of HttpClient I am dealing with a piece of code that looks like this:
public class Uploader : IUploader
{
    public Uploader()
    {
        // assign member variables to dependency injected interface implementations
    }

    public async Task<string> Upload(string url, string data)
    {
        HttpResponseMessage result;
        try
        {
            var handler = new HttpClientHandler();
            var client = new HttpClient(handler);

            result = await client.PostAsync(url, new FormUrlEncodedContent(data));

            if (result.StatusCode != HttpStatusCode.OK)
            {
                return "Some Error Message";
            }
            else
            {
                return null; // Success!
            }
        }
        catch (Exception ex)
        {
            // do some fancy stuff here
        }
    }
}

I am trying to unit test the Upload function. In particular, I need to mock the HttpClient. After reading the other answers on here and these two articles, I know that one of the better ways to solve this is to mock the HttpMessageHandler instead and pass that to HttpClient and have it return whatever I want.
So, I started along that path by first passing in HttpClient in the constructor as a dependency:
public class Uploader : IUploader
{
    private readonly HttpClient m_httpClient; // made this a member variable

    public Uploader(HttpClient httpClient) // dependency inject this
    {
        m_httpClient = httpClient;
    }

    public async Task<string> Upload(string url, string data)
    {
        HttpResponseMessage result;
        try
        {
            var handler = new HttpClientHandler();

            result = await m_httpClient.PostAsync(url, new FormUrlEncodedContent(data));

            if (result.StatusCode != HttpStatusCode.OK)
            {
                return "Some Error Message";
            }
            else
            {
                return null; // Success!
            }
        }
        catch (Exception ex)
        {
            // do some fancy stuff here
        }
    }
}

and adding: services.AddSingleton<HttpClient>(); to the ConfigureServices method of Startup.cs.
But now I face a slight issue where the original code specifically creates a HttpClientHandler to pass in.  How then do I refactor that to take in a mockable handler?

A: I find the simplest way is to continue using HttpClient, but pass in a mocking HttpClientHandler such as https://github.com/richardszalay/mockhttp
Code sample from the link above:
var mockHttp = new MockHttpMessageHandler();

mockHttp.When("http://localhost/api/user/*")
        .Respond("application/json", "{'name' : 'Test McGee'}");

// Inject the handler or client into your application code
var client = mockHttp.ToHttpClient();

var response = await client.GetAsync("http://localhost/api/user/1234");

var json = await response.Content.ReadAsStringAsync();

Console.Write(json); // {'name' : 'Test McGee'}

The Dependency Injection framework built into .NET Core ignores internal constructors, so it will call the parameter-less constructor in this scenario.
public sealed class Uploader : IUploader
{
    private readonly HttpClient m_httpClient;

    public Uploader() : this(new HttpClientHandler())
    {
    }

    internal Uploader(HttpClientHandler handler)
    {
        m_httpClient = new HttpClient(handler);
    }

    // regular methods
}

In your unit tests, you can use the constructor accepting the HttpClientHandler:
[Fact]
public async Task ShouldDoSomethingAsync()
{
    var mockHttp = new MockHttpMessageHandler();

    mockHttp.When("http://myserver.com/upload")
        .Respond("application/json", "{'status' : 'Success'}");

    var uploader = new Uploader(mockHttp);

    var result = await uploader.UploadAsync();

    Assert.Equal("Success", result.Status);
}

Normally I'm not a big fan of having an internal constructor to facilitate testing, however, I find this more obvious and self-contained than registering a shared HttpClient.
HttpClientFactory might be another good option, but I haven't played around with that too much, so I'll just give info on what I've found useful myself.

A: One way would be to abstract your HTTP functionality into a service i.e. HttpService which implements an interface of IHttpService:
IHttpService
public interface IHttpService
{
    Task<HttpResponseMessage> Post(Uri url, string payload, Dictionary<string, string> headers = null);
}

HttpService
public class HttpService : IHttpService
{
    private static HttpClient _httpClient;

    private const string MimeTypeApplicationJson = "application/json";

    public HttpService()
    {
        _httpClient = new HttpClient();
    }

    private static async Task<HttpResponseMessage> HttpSendAsync(HttpMethod method, Uri url, string payload,
        Dictionary<string, string> headers = null)
    {
        var request = new HttpRequestMessage(method, url);
        request.Headers.Add("Accept", MimeTypeApplicationJson);

        if (headers != null)
        {
            foreach (var header in headers)
            {
                request.Headers.Add(header.Key, header.Value);
            }
        }

        if (!string.IsNullOrWhiteSpace(payload))
            request.Content = new StringContent(payload, Encoding.UTF8, MimeTypeApplicationJson);

        return await _httpClient.SendAsync(request);
    }

    public async Task<HttpResponseMessage> Post(Uri url, string payload, Dictionary<string, string> headers = null)
    {
        return await HttpSendAsync(HttpMethod.Post, url, payload, headers);
    }
}

Add to your services:
services.AddSingleton<IHttpService, HttpService>();

In your class you would then inject IHttpService as a dependency:
public class Uploader : IUploader
{
    private readonly IHttpService _httpService; // made this a member variable

    public Uploader(IHttpService httpService) // dependency inject this
    {
        _httpService = httpService;
    }

    public async Task<string> Upload(string url, string data)
    {
        HttpResponseMessage result;
        try
        {

            result = await _httpService.PostAsync(new Uri(url), data);

            if (result.StatusCode != HttpStatusCode.OK)
            {
                return "Some Error Message";
            }
            else
            {
                return null; // Success!
            }
        }
        catch (Exception ex)
        {
            // do some fancy stuff here
        }
    }
}

You could then use Moq to mock HttpService in your unit test:
[TestClass]
public class UploaderTests
{
    private Mock<IHttpService> _mockHttpService = new Mock<IHttpService>();

    [TestMethod]
    public async Task WhenStatusCodeIsNot200Ok_ThenErrorMessageReturned()
    {
        // arrange
        var uploader = new Uploader(_mockHttpService.Object);
        var url = "someurl.co.uk";
        var data = "data";

        // need to setup your mock to return the response you want to test
        _mockHttpService
            .Setup(s => s.PostAsync(url, data))
            .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.InternalServerError));

        // act
        var result = await uploader.Upload(new Uri(url), data);

        // assert
        Assert.AreEqual("Some Error Message", result);
    }

    [TestMethod]
    public async Task WhenStatusCodeIs200Ok_ThenNullReturned()
    {
        // arrange
        var uploader = new Uploader(_mockHttpService.Object);
        var url = "someurl.co.uk";
        var data = "data";

        // need to setup your mock to return the response you want to test
        _mockHttpService
            .Setup(s => s.PostAsync(new Uri(url), data))
            .ReturnsAsync(new HttpResponseMessage(HttpStatusCode.OK));

        // act
        var result = await uploader.Upload(url, data);

        // assert
        Assert.AreEqual(null, result);
    }
}


text:
Q: Perl: Debug for uninitialized s///? I'm some trouble finding the problem with my program. Getting the error:
Use of uninitialized value in substitution (s///)
I realize this has been asked before, but that didn't help me. I realize $1 might be unitialized, but I was wondering if you guys could help me figure out why?
Here's the problem part of the code:
$one_match_ref->{'sentence'} = $1 if ($line =~ /^Parsing \[sent. \d+ len. \d+\]: \[(.+)\]/);
$one_match_ref->{'sentence'} =~ s/, / /g;

EDIT: I have declared the $one_match_ref->{'sentence'} like so:
my $sentence;
$one_match_ref = {
        chapternumber => $chapternumber_value,
        sentencenumber => $sentencenumber_value,
        sentence => $sentence, ##Get from parsed text: remove commas
        grammar_relation => $grammar_relation_value, ##Get from parsed text: split?
        arg1 => $argument1, ##Get from parsed text: first_dependencyword
        arg2 => $argument2 ##Get from parsed text: second_dependencyword
    };

But none of these variables have anything assigned to them.
My attempts:
A. If I put: if( defined (one_match_ref->{'sentence'})) after the s///, it works. But this is cumbersome, and seems to be avoiding the problem instead of fixing it.
The last time I used that fix, it was because my loop had an "off-by-one" error, I don't think this is the case this time.
B. If I declare: my $sentence = ''; It prints, but with a lot of blank lines in between. How can I eliminate these?
EDIT: For interest and efficiency purposes: Is it better to use split to get what I want?
Thanks in advance for any help or advice. Let me know if you need an example of the file format.

A: I'm not sure it's $1 that's uninitialised here but rather $one_match_ref->{'sentence'}.
That value is set if and only if the line matches the regex. Otherwise it's not touched at all.
My reasoning is that it's complaining during the substitute rather than the assignment. You could possibly fix it by simply setting $one_match_ref->{'sentence'} to a known value before those two lines (such as the empty string).
But this depends on what you're actually using those values for.

A: Your code boils down to
my $sentence;
$one_match_ref = { sentence => $sentence };
() if ($line =~ /^Parsing \[sent. \d+ len. \d+\]: \[(.+)\]/);
$one_match_ref->{'sentence'} =~ s/, / /g;

You assign undef to $one_match_ref->{'sentence'}, then you try to remove the commas from it. That doesn't make any sense, thus the warning.
Maybe you want
my $sentence;
$one_match_ref = { sentence => $sentence };
if ($line =~ /^Parsing \[sent. \d+ len. \d+\]: \[(.+)\]/) {
   $one_match_ref->{'sentence'} = $1;
   $one_match_ref->{'sentence'} =~ s/, / /g;
}


text:
Q: Is there any content management system api that can integrate with azure search Is there any content management system(like slideshare, with REST api access to connect and query the data or search for content) that can integrate with azure search cognitive services?

A: There is not, but you can use AzSearch.js to build simple website for browsing your data stored in Azure Search Index. It's extensible and customizable.
Checkout this video for more details.
BTW: what are you trying to build?


text:
Q: PyQt5 plt.show() not-blocking function I've a problem when I have to display the results as a histogram with the plt.show() function, I need the function to be non-blocking because I need the return value of the principal funciont to make new calculations and show a new histogram.
(P.S. i'm using PyCharm ide and Python 3.6.7rc2 matplotlib 3.0.0)
This is the function in the code:
def plotHistStd(data_file, attribute, number, method):
original = copy.deepcopy(data_file)
modified = copy.deepcopy(data_file)
tmp_arr = []
tmp_arr2 = []
if method == 1:
    for i in range(0, original.__len__()):
        if original[i] > 0:
            if number > 0:
                tmp = log1p(original[i]+number)
                tmp_arr.append(copy.deepcopy(original[i]))
                tmp_arr2.append(copy.deepcopy(tmp.real))
            else:
                tmp = np.log1p(original[i]+number)
                tmp_arr.append(copy.deepcopy(original[i]))
                tmp_arr2.append(copy.deepcopy(tmp.real))
        else:
            tmp = np.log1p(original[i]+number)
            tmp_arr.append(copy.deepcopy(original[i]))
            tmp_arr2.append(copy.deepcopy(tmp.real))
        modified[i] = tmp.real
elif method == 2:
    for i in range(0, original.__len__()):
        if original[i] > 0:
            tmp2 = pow((original[i]), (1.0/number))
            tmp_arr.append(copy.deepcopy(original[i]))
            tmp_arr2.append(copy.deepcopy(tmp2.real))
        else:
            tmp2 = cm.exp(number*cm.log(original[i]))
            tmp_arr.append(copy.deepcopy(original[i]))
            tmp_arr2.append(copy.deepcopy(tmp2.real))
        modified[i] = tmp2.real
v_max = max(tmp_arr)
v_min = min(tmp_arr)
v_max2 = max(tmp_arr2)
v_min2 = min(tmp_arr2)
v_max = max(v_max, v_max2)
v_min = min(v_min, v_min2)
fig = plt.figure()
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(2, 1, 2)
n, bins, patches = ax1.hist(original, color="blue", bins=15, range=(v_min, v_max))
ax1.set_xlabel(attribute)
ax1.set_ylabel('Frequency')
n, bins, patches = ax2.hist(modified, color="red", bins=15, range=(v_min, v_max))
ax2.set_xlabel(attribute)
ax2.set_ylabel('Frequency')
plt.subplots_adjust(hspace=0.3)
plt.xticks(rotation=90)
plt.show() #need these non-blocking version
return modified

The function is called from the main window, developed in another Python class file.
I tried to insert plt.ion() after plt.show() but it does not work.
P.s. add the function in the main window that calls that indicates in precedence:
    def apply_stdandardization(self):
    if self.file[self.file.__len__() - 4:self.file.__len__()] != ".csv":
        QtWidgets.QMessageBox.warning(QtWidgets.QWidget(),"Alert Message", "No CSV file was selected!")
    else:
        number = self.lineEdit_2.text()
        index = self.comboBox_2.currentText()
        std_method = 0
        #data_file = pd.read_csv(self.file)
        number = float(number)
        try:
            number = float(number)
        except Exception:
            QtWidgets.QMessageBox.warning(QtWidgets.QWidget(), "Alert Message",
                                          "Insert only numeric value")
        if self.rad_log.isChecked():
            std_method = 1
        elif self.rad_exp.isChecked():
            std_method = 2
        self.new_df = std_function(str(index), number, std_method)

EDIT:
I tried to insert plt.ion() before plt.show(), actually the program is not blocked, but the histogram window does not open correctly and if I click on it, the program crashes with the following errors:
Fatal Python error: PyEval_RestoreThread: NULL tstate

Thread 0x000016c0 (most recent call first):
 File "C:\Python36\lib\threading.py", line 299 in wait
 File "C:\Python36\lib\threading.py", line 551 in wait
 File "C:\PyCharm\helpers\pydev\pydevd.py", line 128 in _on_run
 File "C:\PyCharm\helpers\pydev\_pydevd_bundle\pydevd_comm.py", line 320 in run
 File "C:\Python36\lib\threading.py", line 916 in _bootstrap_inner
 File "C:\Python36\lib\threading.py", line 884 in _bootstrap

 Thread 0x00000fb8 (most recent call first):
 File "C:\PyCharm\helpers\pydev\_pydevd_bundle\pydevd_comm.py", line 382 in _on_run
 File "C:\PyCharm\helpers\pydev\_pydevd_bundle\pydevd_comm.py", line 320 in run
 File "C:\Python36\lib\threading.py", line 916 in _bootstrap_inner
 File "C:\Python36\lib\threading.py", line 884 in _bootstrap

Thread 0x00000b28 (most recent call first):
 File "C:\Python36\lib\threading.py", line 299 in wait
 File "C:\Python36\lib\queue.py", line 173 in get
 File "C:\PyCharm\helpers\pydev\_pydevd_bundle\pydevd_comm.py", line 459 in _on_run
 File "C:\PyCharm\helpers\pydev\_pydevd_bundle\pydevd_comm.py", line 320 in run
 File "C:\Python36\lib\threading.py", line 916 in _bootstrap_inner
 File "C:\Python36\lib\threading.py", line 884 in _bootstrap

Current thread 0x00000b08 (most recent call first):
File "C:/Users/Enrico/PycharmProjects/PythonDataset/PDA.py", line 681 in <module>
File "C:\PyCharm\helpers\pydev\_pydev_imps\_pydev_execfile.py", line 18 in execfile
File "C:\PyCharm\helpers\pydev\pydevd.py", line 1135 in run
File "C:\PyCharm\helpers\pydev\pydevd.py", line 1735 in main
File "C:\PyCharm\helpers\pydev\pydevd.py", line 1741 in <module>

Process finished with exit code 255


text:
Q: is it possible to make a email bot that replies accordingly? so i was wondering if its possible to make a email bot that reads mails and reply accordingly?
It should work like an enhanced chat bot.
I have googled but came across nothing.
Any platform/technology will work.
Thanks

A: This question is better separated into its parts, try breaking the task down into 3 separate subtasks.
part 1 - hook emails into an API
I suggest looking at something like MailGun: https://www.mailgun.com/
part 2 - use chatbot logic to determine an appropriate reply
A good example of a versatile chatbot is here:
https://www.pandorabots.com/
part 3 - use an emailer script to compile and send a reply
Which you can then do using MailGun, or something more generic like PHPMailer

All in all once you have used something like mailgun to receive the email, it can be stored in a database or parsed as JSON. From here you can do whatever kind of manipulation you want based on requirements. Something more autonomous would parse that JSON into a chatbot to determine the reply then send off the reply right away. Something a little more manual would be to store the email into a database, then use a cron job to pick up new emails at an interval (every x seconds/minutes/hours/etc) and process the chatbox and reply logic from there.
Hope this helps!


text:
Q: Parameter separator in URLs, the case of misused question mark What I don't really understand is the benefit of using '?' instead of '&' in urls:

It makes nobody's life easier if we use a different character as the first separator character.
Can you come up with a reasonable explanation?
EDIT: after more research I found that "&" can be a part of file name (terms&conditions.html) so "?" is a good separator. But still I think using "?" for separators makes lives easier (from url generators and parsers point of view):

Is there any advantage in using "&" which is not clear at the first glance?

A: The answer's pretty much in this article - http://www.skorks.com/2010/05/what-every-developer-should-know-about-urls/ . To highlight it, here goes :

Query is the preferred way to send some parameters to a resource on
  the server. These are key=value pairs and are separated from the rest
  of the URL by a ? (question mark) character and are normally separated
  from each other by & (ampersand) characters. What you may not know is
  the fact that it is legal to separate them from each other by the ;
  (semi-colon) character as well. The following URLs are equivalent:
http://www.blah.com/some/crazy/path.html?param1=foo&param2=bar
http://www.blah.com/some/crazy/path.html?param1=foo;param2

A: The RFC 3896 (https://www.ietf.org/rfc/rfc3986.txt) defines general and sub delimiters ... '?' is a general, '&' and ';' are sub. The spec is pretty clear about that.
In this case the latter '?' chars would be treated as part of the query. If the query parser follows the spec strictly, it would then pass the whole query on to the app-destination. If the app-destination could choose to further process the query string in a manner which treats the ? as a param name-value pairs delimiter, that is up to the app's designers.
My guess is that this often 'just works' because code that splits query strings and the original uri uses all delimiters for matching: 1) first query is split on '?' then 2) query string is parsed using char match list that includes '?' (convenience only).... This could be occurring in ubiquitous parsing libraries already.

A: From the URI spec's (RFC 3986) point of view, the only separator here is "?". the format of the query is opaque; the ampersands just are something that HTML happens to use for form submissions.


text:
Q: matplotlib colormap without normalization I am creating scatterplots of data with integer targets.  Naturally, I represent the targets as color in the scatterplot.  However, sometimes my models, because of the nature of the model, predict targets that are not in the original set.  I.e., my training targets are chosen from [0,1,2], and my model occasionally predicts 3, because it is not very bright.
The problem is that when I scatterplot my data, and then separately scatterplot the predictions, the target 2 gets mapped to a different color in each scatter, which makes for a bad picture.  This is because matplotlib by default scales the values in my color list to be between some given values.  I would like to override this default behavior, and have my color list (which are integers), always map to the same color, e.g. 1 maps to green, regardless of how many different classes are in my c=targets parameter.

A: Create a list of colors, say colors = ['blue', 'red', 'green', 'purple'], that has as many colors as you have different targets. Then, set c=colors[target] with target being the integer your model popped out. This means you will need to plot each point one at a time unless you sort all the targets and plot at the end.

A: I ended up doing the following:
def cmap_one(i):
    return "#"+hex(((i+1)*2396745)%(256**3))[2:].rjust(6,"0")
def cmap(colors):
    return list(map(cmap_one, colors))

The cmap function gives me a static mapping from integers to html colors.  They are pretty far apart, so I get very different colors, and 2396745 is relatively prime to 256**3, so every color is eventually used before looping back to the beginning.  Incidentally, 2396745 is approximately 256**3/7, so the colors start almost repeating after 7.  If you want that to be bigger, at the expense of having consecutive colors be closer together, replace 2396745 with a smaller number, also indivisible by 2.


text:
Q: Как правильно сделать прогресс выполнения фоновых задач в очередях? изучаю выполнение фоновых задач через очереди на php,
в качестве сервера очередей использую redis
такая задача возникла..
как правильно сделать прогресс выполнения фоновых задач в очередях?
например..

*

*конвертация видео в другой формат

*сжатие большого изображения

*импорт товаров в бд с внешнего api

предполагаю алгоритм зависит от вида задачи...

случай 3: если это импорт..то нужно подсчитать количество рядов в файле,например там 300 строк,
в бд добавляем по 100 строк
количество итераций=300/100=3
всего 3 итерации:
1-33%
2-66%
3-100%
случай 2 "сжатие большого изображения"..
как узнать здесь количество итераций?
или в момент запуска воркера,увеличивать счетчик прогресса каждую секунду и
записывать/обнволять в бд по id_task значение в поле "progress" , а когда закончит работу обновить значение на 100%
общий алгоритм возможно должен быть похож на это:
function progress(int $total)
{
    echo 'Starting task' . PHP_EOL;
    for ($i = 1; $i <= $total; $i++) {
        $progress = 100 * $i / $total;
        echo $i . '-' . $progress . '%' . PHP_EOL;
        // some heavy task
        sleep(1);
    }
    $progress = 100;
    echo '$progress: ' . $progress . '%' . PHP_EOL;
    echo 'Task completed' . PHP_EOL;
}

progress(10);


text:
Q: restrict the "textfield" to accept only digits and maximum 10 digits in magento form here is a code : http://pastebin.com/qCNGSKRn to display telephone filed to enter telephone number.
i want to restrict above field to accept only numbers and also maximum 10 numbers to be entered. all special charactars and special symbols and white spaces should not allowed.
that field should not accept more than 10 digits.
please help me to find solution.

                *<?php echo $this->__('Telephone') ?>

                    <input type="text" name="telephone" value="<?php echo $this->escapeHtml($this->getAddress()->getTelephone()) ?>" title="<?php echo $this->__('Telephone') ?>" class="input-text  <?php echo $this->helper('customer/address')->getAttributeValidationClass('telephone') ?>" id="telephone" />

A: i have to use this in class " class="input-text validate-length maximum-length-10 minimum-length-10 validate-digits helper('customer/address')->getAttributeValidationClass('telephone') ?>"" https://magento.stackexchange.com/questions/56413/restrict-the-textfield-to-accept-only-digits-and-maximum-10-digits-in-magento
http://inchoo.net/magento/out-of-the-box-form-validation-in-magento/


text:
Q: java applet not caching with 1.6 update 24 and IE/Chrome I have a fairly large applet that I want to be cached between browser restarts.
I have set the cache_archive and cache_version tags, as well as the cache_ex tag.
cache_ex tag uses jar version to determine cache invalidation.
If the client is running latest java (1.7 update 40), then I see from the IIS web logs that there are no http gets of the jars when I restart the browser and load the applet.
With java 1.6 update 24, there are http gets.
I am forced to use this ancient version 1.6 of java because of company idiocy.
How can I get this working?
Thanks.

A: To answer my own question, here are my settings (I am using JavaScript to load applet)
cache_option: "Plugin",
cache_archive: "RELATIVE/PATH/TO/JAR#1,RELATIVE/PATH/TO/JAR#2, etc.",
cache_version: "JAR#1-VERSION, JAR#2-VERSION, etc.",
cache_archive_ex: "JAR#1;preload;JAR#1-VERSION, JAR#2;preload;JAR#2-VERSION, etc.  ",

Important: jars that you want in the sticky cache should not be in the archive tag.
thanks.


text:
Q: What is the meaning of 'exhausting the evidence' in the sentence? Here is the sentence

... let us call the relevant, overall sets of scientific belief 'theories'; different, conflicting theories are consistent with the data; the data exhaust the evidence for belief; therefore, there is no evidential reason to believe one of these theories as opposed to another.

What is the meaning of this (should I say subsentence?) 'the data exhaust the evidence for belief'?
Should that have been 'the data exhausts the evidence for belief'?
If so, I think what it means is that the existent data is completely fulfilling, or sufficient enough only for our belief. But then, it doesn't seem to fit the context of the argument as a whole. Maybe I'm missing something!
Here's the link from where the sentence is snipped - http://plato.stanford.edu/entries/scientific-realism/#UndTheDat

A: The data is/data are issue (covered before on ELU) makes no different to the meaning here, which depends solely on the specific usage of to exhaust - defined by OED as...

To draw out all that is essential or interesting in (an object of investigation or exposition); to treat or study (a subject) so as to leave nothing further to be explained or discovered.

That's to say, the writer claims that where the available data is consistent with multiple conflicting theories, we can't use it to discover "truth" (i.e. - to decide which theory to believe).

A: In this sense "exhausted" means "used up" or "depleted", there is no further evidence offered.
The reason that it is confusing is that in this article, data is being used in it's plural form. It is like saying "the miners exhaust the seam of gold" but because we usually treat data as though it means a single thing, this particular usage is superficially strange.


text:
Q: Graph theory (Chromatic Polynomial) What is chromatic polynomial of tree?
What is chromatic polynomial of complete graph with n vertices?
Sketch two different (i.e, nonisomorphic) graphs that have the same chromatic polynomial.

A: The chromatic polynomial is a polynomial of a graph  which counts the number of distinct ways to color G  with 't' or fewer colors. It counts the number of proper vertex coloring of G.
for details you may refer to http://en.wikipedia.org/wiki/Chromatic_polynomial.


text:
Q: Lex and Yacc, how to get values from variables ? (begginner) this is my first post and first of all I want to say that I am a total beginner. I'm sorry if my question may seem simple but I really did not find an answer.
I would like to be able to analyze a JSON file that I wrote. Thanks to a tutorial I was able to create my grammar, but I would like to be able to access the corresponding values to use them in C functions, and I don't know how to do it.
Here's my lex and yacc files :
%{
#include <stdio.h>
int yywrap() { return 1;}
void yyerror(const char* s) {fprintf(stderr,"Error : %s.\n",s);}
%}

%token X Y DIRECTION POINT1 POINTS2
%token INTEGER STRING
%start linkage
%%

linkage: '{' point1 ','  points2 '}' ;

point1: POINT1 ':' point ;
point: '{'
         X ':' INTEGER ','
         Y ':' INTEGER ','
         DIRECTION ':' STRING  {printf("%s",$3);}
        '}';

points2: POINTs2 ':' '[' points2_list ']';
points2_list: points2_ | points2_list ',' points2_ ;
points2_: '{'
         X ':' INTEGER ','
         Y ':' INTEGER ','
         DIRECTION ':' STRING
        '}';

%%

int main(int argc,char** argv)
{
yyparse();
}

%{
#include <stdio.h>
#include "sample.tab.h"
%}
%%
"\"x\""    return X;
"\"point1\""       return POINT1;
"\"y\""  return Y;
"\"points2\""       return POINTS2;
[0-9]+          return INTEGER;
\"[^\"]*\"       return STRING;
[ \n\t\r]       ;
.               return yytext[0];
%%

I don't really understand how variables work, for example to print the direction.
Again, I'm a beginner, I'm not a programmer, I just want to learn more :)
Thanks you


text:
Q: A pdf foxit file with comments and highlights on it is overwritten by latex and thus I lost the comments. Where can I recover the previous pdf file? A foxit reader pdf file with comments on it is just overwritten by a compile on TeXstudio and thus I lost the comments. Where can I recover the previous pdf file?

A: If you have Shadow Copy enabled, you can try right-clicking the file and opening the Restore previous versions dialog:

If you have no other backup or snapshot service set up, your only hope would be a file recovery utility such as Recuva.


text:
Q: Упрощения триггера WPF Добрый утро! Каким образом можно упростить данный триггер и какие замечания будут по данному коду?
<Window>...
<Window.Resources>
    <Style
        x:Key="MyButtonAbout"
        TargetType="{x:Type Button}"
        BasedOn="{StaticResource MaterialDesignRaisedButton}">
       <Setter Property="Content">
           <Setter.Value>
               <StackPanel Orientation="Horizontal">
                   <materialDesign:PackIcon
                       Width="25"
                       Height="25"
                       VerticalAlignment="Center"
                       Foreground="Gray"
                       Kind="CommentAlertOutline" />
                   <TextBlock
                       Margin="3"
                       HorizontalAlignment="Center"
                       VerticalAlignment="Center"
                       Foreground="Gray"
                       Text="About" />
               </StackPanel>
            </Setter.Value>
       </Setter>
        <Style.Triggers>
            <Trigger  Property="IsMouseOver" Value="True">
                <Setter Property="Content">
                    <Setter.Value>
                        <StackPanel Orientation="Horizontal">
                            <materialDesign:PackIcon
                                Width="25"
                                Height="25"
                                VerticalAlignment="Center"
                                Foreground="Yellow"
                                Kind="CommentAlertOutline" />
                            <TextBlock
                                Margin="3"
                                HorizontalAlignment="Center"
                                VerticalAlignment="Center"
                                Foreground="Orange"
                                Text="About" />
                        </StackPanel>
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>
  </Window.Resources>
  <Grid>
     <Button Style="{StaticResource MyButtonAbout}"/>
  </Grid>
</Window>

A: Вам не нужно переустанавливать Content в триггере, если вы хотите изменить свойства уже существующего элемента.
Меняйте свойства через <Setter TargetName="MyElementName" Property="PropertyName" Value="MyValue" />, предварительно установив имя для элемента.
При этом Content нужно вынести в ControlTemplate, чтобы была возможность обращаться в сеттере к элементу через TargetName.
<ControlTemplate x:Key="CustomButtonTemplate" TargetType="{x:Type Button}">
    <StackPanel Orientation="Horizontal">
               <materialDesign:PackIcon
                   Name="Icon"
                   Width="25"
                   Height="25"
                   VerticalAlignment="Center"
                   Foreground="Gray"
                   Kind="CommentAlertOutline" />
               <TextBlock
                   Name="Text"
                   Margin="3"
                   HorizontalAlignment="Center"
                   VerticalAlignment="Center"
                   Foreground="Gray"
                   Text="About" />
    </StackPanel>
    <ControlTemplate.Triggers>
        <Trigger Property="IsMouseOver" Value="True">
            <Setter TargetName="Icon" Property="Foreground" Value="Yellow" />
            <Setter TargetName="Text" Property="Foreground" Value="Orange" />
        </Trigger>
    </ControlTemplate.Triggers>
</ControlTemplate>

Затем в стиле устанавливаем свойство Template:
<Style x:Key="MyButtonAbout" TargetType="{x:Type Button}">
      <Setter Property="Template" Value="{StaticResource CustomButtonTemplate}" />
</Style>

Если в стиле вы больше ничего не делаете, то можно применить шаблон напрямую к кнопке, без создания стиля:
<Button Content="ClickMe" Template="{StaticResource CustomButtonTemplate}" />

Более подробно можете прочесть здесь.