Q: hide and show a dynamic created UL list with Jquery? Well, as the question says, Im found a code that makes the UL list show and hide with Jquery.
Here is a link on jsFiddle and when I made a UL list directly on the HTML it works but not if I add it dynamically with javascript. http://jsfiddle.net/p2v0ka1s/4/
The problem I found is that the Jquery creates classnames that is called and changed by clicking, and those classnames doesnt apply to my dynamic UL list and I dont know why. Can you please help me?
Here is my code that creates it dynamically and the test of jquery that doesnt work. http://jsfiddle.net/aytnt4bL/1/ The Jquery code is at the button of the javascript code (I added it there, but I have it as a separate sourcefile in my computer.
I add the code here in the text too, so you can see it!
It works perfect with non-dynamic UL list so there is my issue, to make it work with my dynamic created UL list. Thanks!
 $(function() {
    $('.contactlist').click(function(e) {
      e.stopPropagation();
      var sub = $('> ul', this);
      if(sub.length) {
        if(sub.is(':visible')) {
          sub.hide();
          sub.removeClass('open');
        } else {
          $('.contactlist .open').hide().removeClass('open');
          sub.show();
          sub.parents('ul:not(.contactlist)').addClass('open').show();
          sub.addClass('open');
        }
      }
    });
  });

Thanks for your help!

A: You need to use event delegation for attaching events to dynamically added elements:
$('body').on('click','.contactlist',function(e) {
  e.stopPropagation();
  var sub = $('> ul', this);
  if(sub.length) {
    if(sub.is(':visible')) {
      sub.hide();
      sub.removeClass('open');
    } else {
      $('.contactlist .open').hide().removeClass('open');
      sub.show();
      sub.parents('ul:not(.contactlist)').addClass('open').show();
      sub.addClass('open');
    }
  }
});


Q: React input field doesn't see value changing When i picking date, event doesn't see anything, nothing happened, i cannot extract my value from input field. What **** ? Is it problem React or Datepicker? In datepicker manual nothing say about that, http://t1m0n.name/air-datepicker/docs/index.html

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      dueDate: 'Date and time'
    }
  }

  componentDidMount(){
    this.initDatepicker();
  }

  initDatepicker(){
    $(this.refs.datepicker).datepicker();
  }

  render(){
    return (

Choose date!

        <input
          value={this.state.dueDate}
          type='text'
          onChange={event => console.log(event)}
          ref='datepicker'
        />

    )
  }
}

ReactDOM.render(
  <MyComponent />,
  document.getElementById('app')
);

<link href="https://cdnjs.cloudflare.com/ajax/libs/air-datepicker/2.2.3/css/datepicker.min.css" rel="stylesheet"/>

A: You bound the input field value to the state property dueDate. Now if you want to modify it, you have to refresh the state property on input field change, therefore:
onChange={event => this.setState({dueDate: event.target.value})}

A: You wrote a controlled component. You set a state value to input element. If the state changes, your input value change. So you change the code below like,
  // input element
    <input value={this.state.dueDate} onChange={this.handleDueDate}/>

    // handleDueDate method
    handleDueDate(event){
        this.setState({
            dueDate: event.target.value
        })
    }

If you change your code looks like, its works fine.


Q: Im trying to set up a graph but keep gettin error "isolated expression" beginfig(1);
numeric u;
path xaxis,yaxis;
Scale: 1=u
u=0.5in;
yaxis= (0,-4.1u)--(0,4.2u);
xaxis= (-4.1u,0)--(4.2u,0);
pickup pencircle scaled 1pt;
drawarrow xaxis;
drawarrow yaxis;
pickup pencircle scaled 0.1pt;
for i=0 upto 100: draw (-4+i*0.1,-4)*u--(-4+i*0.1,4)*u; endfor;
for i=0 upto 100: draw (-4,-4+i*0.1)*u--(4,-4+i*0.1)*u; endfor;
pickup pencircle scaled 0.25pt;
for i=0 upto 10: draw (-4+i,-4)*u--(-4+i,4)*u; endfor;
for i=0 upto 10: draw (-4,-4+i)*u--(4,-4+i)*u; endfor;
label.rt(btex $x$ etex, (4.2u,0));
label.top(btex $y$ etex, (0,4.2u));
endfig(1);
end.

A: The code of the OP image has syntactic errors.
Luckily, the metapost program gives a user-friendly tips to find them.
The metapost program is upset with two lines in the code:
first complain
>> Scale
! Isolated expression.
<to be read again>
                   :
l.4 Scale:
           1=u
?

points out to the line 4 (which is indicated as l.4)
and says that 1=u is an isolated expression,
i.e. it is meaningless in the context.
Since we can not guess what that line of code supposed to mean,
the simplest fix then would be to remove the line altogether
or (as a minimal correction) just make it a comment by prefixing it with %.
After this fix the metapost program's next complain is about line 19:
! Extra tokens will be flushed.
<to be read again>
                   (
l.19 endfig(
            1);
?

meaning that ( token is not supposed to be there, the fix is to remove (1).
After the two corrections the code looks like
beginfig(1);
numeric u;
path xaxis,yaxis;
%Scale: 1=u
u=0.5in;
yaxis= (0,-4.1u)--(0,4.2u);
xaxis= (-4.1u,0)--(4.2u,0);
pickup pencircle scaled 1pt;
drawarrow xaxis;
drawarrow yaxis;
pickup pencircle scaled 0.1pt;
for i=0 upto 100: draw (-4+i*0.1,-4)*u--(-4+i*0.1,4)*u; endfor;
for i=0 upto 100: draw (-4,-4+i*0.1)*u--(4,-4+i*0.1)*u; endfor;
pickup pencircle scaled 0.25pt;
for i=0 upto 10: draw (-4+i,-4)*u--(-4+i,4)*u; endfor;
for i=0 upto 10: draw (-4,-4+i)*u--(4,-4+i)*u; endfor;
label.rt(btex $x$ etex, (4.2u,0));
label.top(btex $y$ etex, (0,4.2u));
endfig;
end.

and the metapost program is happy to compile it.


Q: Need help in understanding "for any vector $a \in [n]^2$..." where $[n] = \{0, 1, ... n-1\}$ In a paper I see "for any vector $a \in [n]^2$..." where $[n] = \{0, 1, ... n-1\}$
What can it potentially mean? $[n]$ seem to be a set.... what then $[n]^2$ might denote? Especially we say for any vector $a$.
Any guesses?
P.S paper is HERE
(page 8, middle left column) ...


Q: After insert Node to XML formating I add a new node to an existing XML but the format is not well.
Original XML is:
<xml xmlns:xi="http://www.w3.org/2001/XInclude">

   <vars>
....

I tried to insert before "vars" and the result is
<xml xmlns:xi="http://www.w3.org/2001/XInclude">

    <TCafe initvalue="1" type="int"/><vars>

But I expect
<xml xmlns:xi="http://www.w3.org/2001/XInclude">

    <TCafe initvalue="1" type="int"/>

       <vars>

My code is simple:
var xmlDoc = new DOMParser().parseFromString(dataRegelWerk);
if(allok == false){
                var root = xmlDoc.documentElement;

                var varselem = xmlDoc.getElementsByTagName('vars')[0];
                var newEle = xmlDoc.createElement('TCafe');
                var att1 = xmlDoc.createAttribute("initvalue");
                att1.value = "1";
                var att2 = xmlDoc.createAttribute("type");
                att2.value = "int";
                newEle.setAttributeNode(att1);
                newEle.setAttributeNode(att2);

                root.insertBefore(newEle, varselem);
            }

var myFile = serializer.serializeToString(xmlDoc);

Do I understand something wrong with insertBefore? or is this a good XML formatting and I just expect a wrong thing?


Q: Javascript MVC Framework for building reusable components on a non-SPA site We have an existing Genealogy site which is not a single-page app, and over the years we've created a number of jQuery plugins for doing things such as typeahead, various modal-based utilities, and components that are reusable around the site. We aren't doing a single-page app because we are a content publisher, and we're not yet confident that search engines will reliably index these in our use case.
We are now looking at adding some more complex widgets that have multi-view modal flows. An example for our Genealogy site is that there are numerous cases where a user must select a Person record from a pool of records they are following OR optionally, create a new one.
For example, say you are viewing a person record want to change the family tree relationships on a person. You click on a link and a modal appears allowing you to edit their relationships. We were envisioning a modal flow that looks like this:

*

*View 1 (Index): A management page that lists current relationships, along with an "Add Person" pulldown that allows you to select a relationship type (Parent, Spouse, Child, Sibling)

*View 2 (Add a person): We show a text input field with typeahead support. As the user types, we look through the pool of people on their graph and try to make a match. If they match something in typeahead, we can capture that and send that back to the parent app.

*View 3 (Search for matches): The user may have just missed the typeahead results - so allow the API to see if there are any potential matches in their graph. Allow the user to choose a match, and send this back. If there are no matches, they can click "These are not my person"

*View 4 (Create person): If we couldn't find a matching person in their graph, this is a completely new person. Give them a form to give details about the person.
I'm at a loss for what might be the best solution for this. I've looked into EmberJS and AngularJS, and folks in both those communities suggested that if you're not building a single-page app, it's not worthwhile using these frameworks.
Can anyone point me in the right direction? I can't be unique in this use case!

A: I have built several mini-SPA apps using both Knockout.js and Ember.js. There are a lot of good reasons for serving a mini-Single-Page-Application rather than converting your entire app, mainly that client-side code doesn't do everything better.
In my experience, both Angular and Ember.js are very useable without making your whole app client-side. Ember gives you some very useful tools for making "widgets".
For example, if I want my Ember application to render on a part of my server-side page, I can do this:
var App = Ember.Application.create({
  // Set the rootElement property to the div that I want my ember app to render inside
  rootElement: "#your-root-element",
  Resolver: Ember.DefaultResolver.extend({
    resolveTemplate: function(parsedName) {
      // Override this method to make this app look for its templates in a subdirectory
    }
  }),
});

// Don't render the app on any page by default
App.deferReadiness();

// Instead, check to see if the #rootElement is present on the page before rendering.
$(document).ready(function() {
  if ( $(App.get('rootElement')).length > 0 ) {
    App.advanceReadiness();
  }
});

I'm sure you can do similarly with Angular.js. I prefer Ember for the following reasons:

*

*A genuine class/mixin system. This is really helpful when you want to share code: it should be very familiar to anyone who is used to working on the server side.

*Very flexible templating.

*Clear separation of concerns, allowing many different views and such to be handled elegantly.


Q: Connecting GitHub Account and SourceTree with SSH I am on a Windows 10 laptop with git version 2.20.1.windows.1 and Sourcetree version 3.0.17. I am using the System Git (I don't have the Embedded Git downloaded, so there isn't any interference there).
I am trying to add my GitHub account to Sourcetree for easier cloning of repos (so I don't have to use HTTPS links for each one), and I am not able to see any of the repos once the account is added. I have tried using both OAuth and basic, and also tried using OpenSSH, as suggested in this SO post (this is also the only way I could get Sourcetree to link with my Bitbucket account).
Unfortunately it is not working, but when I open Git Bash and type ssh -T git@github.com I receive a message acknowledging I have connected my account to git on my laptop. It also doesn't work adding the account via HTTPS (OAuth or basic).
Does anyone have a suggestion, as this is slowing my migration of some projects to GitHub?

A: Check your SourceTree Git settings, and make sure your are using the System Git, not the embedded one.

Otherwise, your local Git installation (which does connect to GitHub) would be ignored.


Q: Can I cancel out gravity only with gyro and magnetometer? On a device I want to detect a range of forces: small forces (Minimum around 0.01g) but also stronger forces like 0.1g - 0.15g.
This device will have different positions in 3d space so in order to detect the small forces I have to know its angle in order to be able to subtract 1g. Because the device can have a random position (angle position).
What I did so far: I used the MPU6050 and used a complementary filter with accel. and gyro.
It's something like:
agnleX_k+1 = 0.98*(angle_k + deltaT * gyro_k+1) + 0.02*angle_acc_k+1;

angle_acc is the angle calculated from the accel. sensor. Something like:
arctan(accelX / sqrt(accelX^2 + accelY^2 + accelZ^2 + ))

So I am interested in:
forceX_k+1 = accelX_k+1 - 1g*sin(agnleX_k+1)

The problem is:
If I want to detect a small force coming in very fast, let's say on accelX_k+1 I would want to detect a Change from 0g to 0.01g or more but in a very small time range. The problem is that my calculated angle would then also be influenced by this small and fast change of the accel. sensor although the angle haven't really changed.
I think I would have to do the angle calculation independent of the accel. sensor. Can I do something like a complementary filter with gyro and magnetometer? Would that work the same as my filter described above but just with the mag. sensor instead? Or how would you do that? I was thinking about using MPU9250.

A: You stated using MPU6050, which contains both an accelerometer and a gyrosocpe. You could use them independantly - get acceleration from the accelerometer and get angles from the gyroscope, and then use the angles to compensate for rotation. There is no need for the angle to depend on your accelerometer.

A: Using DMP library fromJeff Rowberg will do the work for you.
it can compensate gravity acceleration internally way faster that Arduino code.
Link to github


Q: Issue while printing the decimal values when reading from excel using java In Excel I have these decimal values:

TS
BS

5.60
4.10

10.00
10.00

10.00
10.00

10.00
10.00

While parsing, it shows different values:

TS
BS

0.1375
0.85

0.0125
0.7125

0.0125
0.8125000000000001

0.0125
0.7875000000000001

I need to print the exact values.
Here is the code:
Iterator<Row> itr = sheet.iterator();
while (itr.hasNext())
{
    Row row = itr.next();
    Iterator<Cell> cellIterator = row.cellIterator();
    while (cellIterator.hasNext())
    {
      Cell cell = cellIterator.next();
      switch (cell.getCellType())
      {
        case STRING:
        System.out.print(cell.getStringCellValue() + "\t\t\t");
        break;
        case NUMERIC:
        if (DateUtil.isCellDateFormatted(cell)) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
        System.out.print(dateFormat.format(cell.getDateCellValue()) + "\t\t\t");
        } else {
           System.out.print(cell.getNumericCellValue() + "\t\t\t\t");
          }
           break;
            default:
             }
           }
            System.out.println("");
       }

I'm using Apache POI-4.1.1.
Could please someone help me with this?

A: g00se is right. My issue is solved. I had to parse the values from formula.
Iterator<Row> itr = sheet.iterator();
while (itr.hasNext()) {
 Row row = itr.next();
 //iterating over each column
 Iterator<Cell> cellIterator = row.cellIterator();
 while (cellIterator.hasNext()) {
 Cell cell = cellIterator.next();
 CellType cellType = cell.getCellType();
 if (cell.getCellType() == CellType.FORMULA) {
 switch (cell.getCachedFormulaResultType()) {
 case NUMERIC:
 System.out.print(cell.getNumericCellValue() + "\t\t");
 break;
 case STRING:
 System.out.print(cell.getRichStringCellValue() + "\t\t");
 break;
    }
 }
 switch (cell.getCellType()) {
 case STRING:
//field that represents string cell type
System.out.print(cell.getStringCellValue() + "\t\t");
break;
case NUMERIC:
//field that represents number cell type
if (DateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");                                System.out.print(dateFormat.format(cell.getDateCellValue()) + "\t\t");
   }
  else {
double roundOff = Math.round(cell.getNumericCellValue() * 100.0) / 100.0;
System.out.print(roundOff + "\t\t");
        }
         break;
         case BLANK:
         break;
         default:
       }
     }
  System.out.println("");
 }
}


Q: Use empty list as fill value for Series.fillna I need to change the NaN values the column 'FocusColumn' to empty lists.

I tried to do it like this:
df['FocusColumn'].fillna([],inplace=True)

But it throws me the following error:
337         if validate_scalar_dict_value and isinstance(value, (list, tuple)):
338             raise TypeError(
339                 '"value" parameter must be a scalar or dict, but
340                 f'you passed a "{type(value).__name__}"'
341             )
TypeError: "value" parameter must be a scalar or dict, but you passed a "list"

What is the correct way to do it?

A: Looks like you can work around this by supplying a dict to Series.fillna.
>>> df
   FocusColumn
0          NaN
1          1.0
2          NaN
>>> df['FocusColumn'].fillna({i: [] for i in df.index})
0    []
1     1
2    []
Name: FocusColumn, dtype: object

Notes:

*

*Surprisingly, this only works for Series.fillna.

*For large Series with few missing values, this might create an unreasonable amount of throwaway empty lists.

*Tested with pandas 1.0.5.

A: You could try the following:
import pandas as pd
import numpy as np

df = pd.DataFrame({'FocusColumn': [1, 2, 3, 4, np.NaN, np.NaN, np.NaN, np.NaN], 'Column1': [1, 2, 3, 4, 5, 6, 7, 8], 'Column2': [7, 8, 6, 5, 7, 8, 5, 4]})

df['FocusColumn'] = df['FocusColumn'].apply(lambda x: [] if np.isnan(x) else x)
print(df)

Output:
  FocusColumn  Column1  Column2
0           1        1       7
1           2        2       8
2           3        3       6
3           4        4       5
4          []        5       7
5          []        6       8
6          []        7       5
7          []        8       4


Q: React Buttons change color from parent component I'm learning react and making a simple quiz where the div changes color based on if the solution is correct or not, but I want to reset the color when the "Next" or "Previous" question is selected from the parent component. I tried creating a prop called clearColor and when that is true reset the color from within the  component but this isn't quite working. I was wondering how to best go about this? Because I am so new to react I wasn't even quite sure what to google so any help is appreciated!

class Button extends React.Component {

  constructor(props) {
    super(props);
    this.state = this.getInitialState();
  }

  componentWillMount() {
    this.initialState = this.state
  }

  getInitialState = () => ({
      bgColor: ""
  })

  resetState = () => {
    if (this.props.clearColor) {
      this.setState(this.initialState)
    }
  }

  boxClick = (e) => {
    if (this.props.isCorrect) {
      this.setState({
        bgColor: "#9ef0bc"
      })
    } else {
      this.setState({
        bgColor: "#f56342"
      })
    }
  }

  render() {
    return (

{this.props.name}

    );
  }
}

function Quiz() {
    const questions = [
        {
            questionText: 'What is the capital of France?',
            answerOptions: [
                { answerText: 'New York', isCorrect: false },
                { answerText: 'London', isCorrect: false },
                { answerText: 'Paris', isCorrect: true },
                { answerText: 'Dublin', isCorrect: false },
            ],
        },
        {
            questionText: 'Who is CEO of Tesla?',
            answerOptions: [
                { answerText: 'Jeff Bezos', isCorrect: false },
                { answerText: 'Elon Musk', isCorrect: true },
                { answerText: 'Bill Gates', isCorrect: false },
                { answerText: 'Tony Stark', isCorrect: false },
            ],
        },
        {
            questionText: 'The iPhone was created by which company?',
            answerOptions: [
                { answerText: 'Apple', isCorrect: true },
                { answerText: 'Intel', isCorrect: false },
                { answerText: 'Amazon', isCorrect: false },
                { answerText: 'Microsoft', isCorrect: false },
            ],
        },
        {
            questionText: 'How many Harry Potter books are there?',
            answerOptions: [
                { answerText: '1', isCorrect: false },
                { answerText: '4', isCorrect: false },
                { answerText: '6', isCorrect: false },
                { answerText: '7', isCorrect: true },
            ],
        },
    ];

    const [currentQuestion, setCurrentQuestion] = React.useState(0);
    const [clearColor, setClearColor] = React.useState(false)

    const nextClicked = () => {
        setClearColor(true);
        const nextQuestion = currentQuestion + 1;
        if (nextQuestion < questions.length) {
            setCurrentQuestion(nextQuestion);
        }
    };

    const previousClicked = () => {
        setClearColor(true)
        if (currentQuestion <= 0) {
            setCurrentQuestion(0);
        } else {
            const nextQuestion = currentQuestion - 1;
            setCurrentQuestion(nextQuestion);
        }
    }

    return (

                            Question {currentQuestion + 1}/{questions.length}

{questions[currentQuestion].questionText}

                        {questions[currentQuestion].answerOptions.map((answerOption) => (
                            <Button name={answerOption.answerText} isCorrect={answerOption.isCorrect} clearColor={clearColor} />
                        ))}

              <button className="prev" onClick={() => previousClicked()}>Previous</button>
                <button className="next" onClick={() => nextClicked()}>Next</button>

    );

}

ReactDOM.render(
    <Quiz />,
  document.getElementById('root')
);
body {
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}
* {
  font-family: "Verdana", cursive, sans-serif;
  color: #014650;
}

body {
  background-color: #014650;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
}

.app {
  display: flex;
  justify-content: space-evenly;
}

.score-section {
  display: flex;
  font-size: 24px;
  align-items: center;
}

/* QUESTION/TIMER/LEFT SECTION */
.question-section {
  width: 100%;
  position: relative;
}

.question-count {
  margin-bottom: 20px;
}

.question-count span {
  font-size: 28px;
}

.question-text {
  margin-bottom: 12px;
}

.timer-text {
  background: rgb(230, 153, 12);
  padding: 15px;
  margin-top: 20px;
  margin-right: 20px;
  border: 5px solid rgb(255, 189, 67);
  border-radius: 15px;
  text-align: center;
}

/* ANSWERS/RIGHT SECTION */
.answer-section {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.boxClickCss {
  width: 80%;
  font-size: 16px;
  color: #014650;
  background-color: white;
  border-radius: 15px;
  display: flex;
  padding: 5px;
  justify-content: flex-start;
  align-items: center;
  border: 5px solid #234668;
  cursor: pointer;
  margin-top: 15px;
}

.boxClickCss:hover {
  background-color: #6A939A;
}

button {
  width: 100%;
  font-size: 16px;
  color: #7BC8C3;
  background-color: #252d4a;
  border-radius: 15px;
  display: flex;
  padding: 5px;
  justify-content: flex-start;
  align-items: center;
  border: 5px solid #234668;
  cursor: pointer;
  margin-top: 15px;
}

.correct {
  background-color: #2f922f;
}

.incorrect {
  background-color: #ff3333;
}

button:hover {
  background-color: #555e7d;
}

button:focus {
  outline: none;
}

button svg {
  margin-right: 5px;
}

.buttons {
  display: flex;
  justify-content: space-between;
}

.prev {
  width: 30%;
  text-align: center;
}

.next {
  width: 30%;
  text-align: center;
}

.quiz {
  background-color: #DEF2F0;
  width: 450px;
  min-height: 200px;
  height: min-content;
  border-radius: 15px;
  padding: 20px;
  box-shadow: 10px 10px 42px 0px rgba(0, 0, 0, 0.75);
}

I also have a codepen here if that is easier to work with: https://codepen.io/mayagans/pen/mdOypGG?editors=1111 I tried looking into lifting up state so I can change the bgColor in the parent  component but I'm not sure that is react-y? Any help on how to tackle this appreciated!

A: You need to lsiten to props changes during componentDidUdpate like this, to check:
componentDidUpdate() {
    if (this.props.clearColor && this.state.bgColor) {
      this.setState(this.initialState)
    }
  }

Moving the state up is reacty and you could be using that.
I would recommend that or moving it into a context.
Also maybe look into function components, which will be the main way to write react in the future.

A: This is how I would do it. I would just lift all the state up to Quiz component. Also would keep boxClick function in Quiz component and pass it to Button component. And I am colouring the button only which title match currently selected answer using setAnswer hook.
const Button = ({answer, name, bgColor, isCorrect, boxClick, setAnswer}) => {

  return (

 {
            boxClick(isCorrect)
            setAnswer(name)
          }}>
        {name}

  )
}

const Quiz = () => {

  const questions = [
        {
            questionText: 'What is the capital of France?',
            answerOptions: [
                { answerText: 'New York', isCorrect: false },
                { answerText: 'London', isCorrect: false },
                { answerText: 'Paris', isCorrect: true },
                { answerText: 'Dublin', isCorrect: false },
            ],
        },
        {
            questionText: 'Who is CEO of Tesla?',
            answerOptions: [
                { answerText: 'Jeff Bezos', isCorrect: false },
                { answerText: 'Elon Musk', isCorrect: true },
                { answerText: 'Bill Gates', isCorrect: false },
                { answerText: 'Tony Stark', isCorrect: false },
            ],
        },
        {
            questionText: 'The iPhone was created by which company?',
            answerOptions: [
                { answerText: 'Apple', isCorrect: true },
                { answerText: 'Intel', isCorrect: false },
                { answerText: 'Amazon', isCorrect: false },
                { answerText: 'Microsoft', isCorrect: false },
            ],
        },
        {
            questionText: 'How many Harry Potter books are there?',
            answerOptions: [
                { answerText: '1', isCorrect: false },
                { answerText: '4', isCorrect: false },
                { answerText: '6', isCorrect: false },
                { answerText: '7', isCorrect: true },
            ],
        },
];

  const [currentQuestion, setCurrentQuestion] = React.useState(0);
  const [bgColor, setbgColor] = React.useState('')
  const [answer, setAnswer] = React.useState('')

  const boxClick = isCorrect => {
     if(isCorrect) {
       setbgColor("#9ef0bc")
     } else {
       setbgColor("#f56342")
     }
   }

    const nextClicked = () => {
        const nextQuestion = currentQuestion + 1;
        if (nextQuestion < questions.length) {
            setCurrentQuestion(nextQuestion);
        }
    };

    const previousClicked = () => {
        if (currentQuestion <= 0) {
            setCurrentQuestion(0);
        } else {
            const nextQuestion = currentQuestion - 1;
            setCurrentQuestion(nextQuestion);

        }
    }

    return (

                            Question {currentQuestion + 1}/{questions.length}

{questions[currentQuestion].questionText}

                        {questions[currentQuestion].answerOptions.map((answerOption) => (
                            <Button name={answerOption.answerText} isCorrect={answerOption.isCorrect} boxClick={boxClick} bgColor={bgColor} setAnswer={setAnswer} answer={answer} />
                        ))}

              <button className="prev" onClick={() => previousClicked()}>Previous</button>
                <button className="next" onClick={() => nextClicked()}>Next</button>

    );

}

ReactDOM.render(
    <Quiz />,
  document.getElementById('root')
);


Q: Ruby compatibility error encoding I'm having a problem. Let's look:

C:\temp> ruby script.rb

script.rb                 => Powershell output

puts "ę"                  => ę #irb \xA9
puts "\xA9"               => ▯
puts "ę"=="\xA9"          => false
input = $stdin.gets.chomp => input=="ę"
puts "e#{input}e"         => eęe
puts "ę"==input           => false
puts "ę#{input}"          => Encoding::Compatibility Error Utf8 & CP852

irb                       => #command line in ruby
puts "ę"=="\xA9"          => true
input = $stdin.gets.chomp => input=="ę"
puts "ę"==input           => true  && "\xA9"==input => true
puts "ę#{input}"          => ęę

It looks like powershell's input uses other font for all special characters than ruby and notepad++(?). Can i change that so it will work when i type in prompt(when asked) and does not show an error?
Edit: Sorry for misdirection. I added invoke and specified that file has extension ".rb" not ".txt"
Edit2: Ok, I've researched some more information and I've been trying do some encoding(UTF8) to a variable. Somethin' strange occured.
puts "ę#{input.encoding}"         => ęCP852
puts "\xA9"                       => UTF-8

Encoding to CP852 has revealed that encoding pass on bytes. I learned that value of "ę"=20+99=119, "ą" = 20 + 85, 20 = C4
Ok. got it ".encoding" - shows what encoding i use. And that resolve this problem.
puts "ę#{input.encode "UTF-8"}"         => ęę

Thanks everyone for your input.

A: If your input in prompt( either cmd or powershell) is causing problems due to incompatibility of using differents encodings just try to encode it via methods in script.encode "UTF-8" #in case of Ruby language If you dont know what methods do that just google your_language_name encoding


Q: How to configure Database Driver Location(s) in a Nifi process when Nifi is runing on a Kuberntes pod I have deployed Nifi on Kubernetes using cetic/helm-nifi helm chart. I have to insert log data to a MySQL database using a PutDatabaseRecord process. To do that, inside of PutDatabaseRecord process, I have to configure Database Connection URL, Database Driver Class Name & Database Driver Location(s).

As the Database Driver Location, I downloaded the connector jar (https://dev.mysql.com/downloads/connector/j/) inside the pod and configured the location of the MySQL connector jar file inside the PutDatabaseRecord process. In that way, if the pod is getting restart, I have to download connector manually inside the pod again. It is not a recommended way to do that. Appreciate if you can suggest a solution for this.

A: It would be really helpful to see your Kubernetes configuration, but overall you can use ConfigMaps for this purpose - as it is standard Kubernetes resource for storing configuration data. It is described in more details here.
Below is the example of ConfigMap, where MySQL connector jar file is mounted to the pod:

  containers:
    - name: container
      volumeMounts:
      - name: config
        mountPath: /usr/local/mysql-connector-java.jar
  volumes:
    - name: config
      configMap:
        name: config-map
        items:
        - key: mysql-connector-java.jar
          path: mysql-connector-java.jar

But ConfigMap will work for you only if you are storing the connector jar file, which size is not exceeding 1 MiB.
Otherwise, there is one more option -  mounting a persistent volume with a MySQL connector jar file - as described here and here.  The jar file will be  copied to the pod once persistent volume is mounted into it - and it can be re-mounted to the pod after its restart/re-creation.


Q: Integrate custom java web application with MS dynamics CRM Currently we have custom java application which is connected to salesforce CRM via canvas integration. Now we need to integrate with MS dynamics CRM.
Could you please tell me high level steps? how authentication will happen when control come from dynamics to custom application? Is there any canvas integration / iframe like thing in ms dynamics?

A: The best thing for a non .Net Application is to use the Dynamics 365 WebApi
It supports all common types of CRM Instances (On-Premise, Online) and authentication Methods:

*

*OAuth (2)

*Office365

*AD

*etc...

You can than look for existing projects on the web. (Like this guide for example)


Q: Filtering in overlay_nearest I am using QGIS 3.24,
I have 2 polylines layers:

*

*First one is composed of 2 rivers, crossing. The two of them are named 1 and 2

*Second one is composed of parallel lines form this rivers. 5 and 6

Starting from my parallel layer (red), i would like to find the nearest entity in my layer river (blue), BUT with a filter. Indeed, i want to join parallel line with the same river they're from. So I DON'T want my parallel line 5 to be joined with my river 1, but i want it to be joined with my river 2.
I've tried this, with field_calculator, from my layer parallel:
array_to_string(overlay_nearest('river_layer',id,filter:=river_name='river_name',limit:=1))

id is id from river_layer
But nothing happens! If i write it like this:
array_to_string(overlay_nearest('river_layer',id,filter:=river_name='1',limit:=1))

It's working, but it's only pointing to entity from river 1, ofc.
I've read https://github.com/qgis/QGIS/issues/43146 but I don't get this formula: \'layer2\'? Why \? And this [0]? I don't get it neither.

I think I've misled the first answerer. My river is 'segmented', so it may cause some trouble with that answer, even if it could work:

On this picture, lines 31, 32, 33 and 34 are from the same river (It's already stored in my tables, river and parallel lines). I have 4 parallel lines, and they are segmented too (I marked them with point at the middle of them). We can imagine a part of the attribute table like this:

If I put a buffer on my river (I can even do it BEFORE river is segmented), I fear that some parallel segmented lines might be associated with the wrong river, like on my picture, which shows some errors:

Maybe I could create a virtual layer, with something like this, considering P_para_line as my point layer with points in the middle of parallel segmented lines:
SELECT
    ST_startpoint(ST_ShortestLine(p.geometry, r.geometry)),
    r.id AS id_of_the_segmented_portion_of_river,
    ROUND(ST_Length(ST_ShortestLine(r.geometry, p.geometry)), 6) AS distance
FROM
    P_para_line AS p, river_layer AS r
WHERE
    p.river_name = r.river_name

After this, I get way too many points on the same coordinate! I wish I could keep only the point with the shortest distance. I can suppress other points manually, but I think i can change my virtual layer query.

A: Create a buffer around the river layer (containing 1 and 2) with a distance slightly larger then the distance to the second line layer (containing 5 and 6).
Then check within which of the buffers the second line is and get the value of an attribute (like id) by its field name, e.g. using FIeld calculator.
Use this expression:
array_max (
    array_foreach(
        overlay_nearest (
            'buffer',  -- change the layer name
            $id,
            limit:=2  -- change the number, depending how many rivers/parallel lines you have
        ),
        if (
            within (
                $geometry,
                geometry(
                    get_feature_by_id (
                        'buffer',  -- change the layer name
                        @element
                    )
                )
            ),
            attribute (
                get_feature_by_id (
                    'buffer',  -- change the layer name
                    @element
                ),
                'id'  -- change the name of attribute whose value you want to get
            ),''
        )
    )
)

Red line is labeled with the expression above, getting the value of the id of from the layer river (blue):


Q: QScrollArea not scaling to the window I'm trying to use a QScrollArea in order to be able to put a lot of widgets on the same window. Unfortunately, the QWidget containing the QScrollAea (which is central) is not scaling to the size of the window, which makes it... not like I want... I tried different things but I can't fix it... any idea?
QWidget *central = new QWidget(this);
QScrollArea *scroll = new QScrollArea(this);
QVBoxLayout *vLayout = new QVBoxLayout(central);

this->setCentralWidget(central);
central->setLayout(vLayout);

//vect is not empty
for (elt t : vect)
{
    vLayout->addWidget(new TweetDisplay(elt, t));
}

//If I remove those three lines, everything is displayed but of course, I can't scroll.
scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOn);
scroll->setWidget(central);
scroll->setWidgetResizable(true);

Picture for reference:

A: Instead of setting the central widget to central you should try using scroll as your central widget.  Thus, the proper line would be:
this->setCentralWidget(scroll);

Remember the scroll area uses central as the widget it contains already, so setting it as the central widget doesn't actually make sense.


Q: SSIS export to Excel template - keep row height I have a following excel 2007 template (.xlsx):

I have set up an SSIS process to copy that template and populate the first two columns with data as the file will be printed and then signed by order recipients. Everything is going well except for one thing - after the process populates the template with data, the cells don't retain their size - making signature cells too small.

Any ideas on how to force excel to keep the cell heights ?

A: One idea would be to create a macro that runs when the workbook is opened and it sets the row height using the Range.RowHeight property, here:
https://msdn.microsoft.com/en-us/library/office/ff193926.aspx

A: If anyone ever has a similar issue, I managed to find a workaround. Instead of using SSIS I'm using SSRS where I keep the cell height by adding an "invisible (white text on white background) column at the end. I set up an SSRS subscription to automatically export the data and send as an Excel.


Q: Interfaces With generic factory i'm trying to do fancy stuff like this:
i have following code:
public interface IMyInterface
    {
      void Method1();
    }

  public interface IClassFactory
  {
      object GetObject();
  }

  public interface IGenericClassFactory<T> where T: IMyInterface
  {
       T GetObject();
  }

public class MyClass : IMyInterface
    {
        public void Method1()
        {
            Console.WriteLine("Medota 1");
        }

    }

    public class MyFactory : IClassFactory
    {
         public object GetObject()
        {
            return new MyClass();
        }
    }

    public class MyGenericFactory<T> : IGenericClassFactory<T> where T : IMyInterface, new()
    {
        public T GetObject()
        {
           // T t = new T();
            //return t;
            //var ctor = typeof(T).GetConstructor(new Type[0]);//1] { typeof(int) });
            //if (ctor != null)
            //{
            //    return (T)ctor.Invoke(new object[0]); // new object[1] { 5});
            //    //return Activator.CreateInstance<T>(); //to samo co wyzej tylko nie jest bezpieczne
            //}
            //throw new InvalidOperationException("T nie posiada domyślnego konstruktora");
           // return Activator.CreateInstance<T>(); //bez parametrów
           // return (T)Activator.CreateInstance(typeof(T), 5, "EOG", new object()); // z parametrami
            return new T();

        }
    }

 static void Main(string[] args)
        {
            IClassFactory factory;
            factory = new MyFactory();

            IGenericClassFactory<IMyInterface> genFactory;
            genFactory = new MyGenericFactory<MyClass>(); //Do not compile!

            MyClass obj = genFactory.GetObject() as MyClass;

            obj.Method1();
            Console.ReadKey();
        }

I can do this like:
 IGenericClassFactory<IMyInterface> genFactory;
            genFactory = new MyGenericFactory<MyClass>();

//so i can chose object to create
but i think it is pointless because i want to have Factory of more then one object.
Can u help me?
Thx in advance

A: You should not make your factory class generic but the method GetObject should be generic:
public T GetObject<T>() where T: IMyInterface, new()

Then:
 static void Main(string[] args)
 {
      var factory = new MyFactory();
      var obj = factory.GetObject<MyClass>();

      obj.Method1();
      Console.ReadKey();
 }

So all in all you should get rid of your generic code and simply modify your MyFactory class
public class MyFactory : IClassFactory
{
     public T GetObject<T>()
    {
        //TODO - get object of T type and return it
        return new T();
    }
}

By the way - I am not sure what is the purpose of having this generic implementation? Does it make any sense from the perspective of the usage of Factory pattern?


Q: Trouble pulling events between 2 dates in Codeigniter / PHP I have created an events calendar with codeigniters calendar class which you can view here: Events Calendar
I have it set up where the events are showing up on the calendar and when you click "view events" on a particular day, all the events with that start date pull up and are shown in a modal window.
Well... the problem is that unless its the START DATE of a particular event, the modal window details don't pull up. I know this is because i'm saying in my query to pull events where the start date equals a certain date...
I'm kind of stumped on how to modify this to say, "pull all records where this day is ANYWHERE BETWEEN the start and end date of the event.
Do I need to run a while loop or something and loop through each day of the month? Any ideas on an easier way to do this are appreciated.
the start and end dates are set up as 'Y-m-d H:i:s' in the database and the $query_date variable being passed in is 'Y-m-d', which i change to the same format in the first few lines of the function.
function get_list_events($query_date) {

        $start_date_start = date('Y-m-d H:i:s', strtotime($query_date.' 00:00:00'));
        $start_date_end = date('Y-m-d H:i:s', strtotime($query_date.' 23:59:59'));

        $this->db->where('active', 1);
        $this->db->where("start_date BETWEEN '$start_date_start%' AND '$start_date_end%'", NULL, FALSE);
        $query = $this->db->get('events');

        $data = array();

        foreach ($query->result() as $row) {
        $data[] = array(
            'id' => $row->id,
            'title' => $row->title,
            'description' => $row->description,
            'cost' => $row->cost,
            'image' => $row->image,
            'start_date' => $row->start_date,
            'end_date' => $row->end_date,
            'venue' => $row->venue,
            'venue_address' => $row->venue_address,
            'venue_city' => $row->venue_city,
            'venue_state' => $row->venue_state,
            'venue_zipcode' => $row->venue_zipcode,
            'contact_name' => $row->contact_name,
            'contact_email' => $row->contact_email,
            'contact_phone' => $row->contact_phone,
            'contact_website' => $row->contact_website,
            'create_date' => $row->create_date,
            'active' => $row->active,
        );
        }
        return $data;

    }

A: I guess your start_date column has the DATETIME or the TIMESTAMP data type. If that isn't true, please update your question.
There's a common trap in date-range processing in all kinds of SQL, due to the fact that when you compare a pure DATE with a DATETIME, they hardly ever come out equal.  That's because, for example, DATE('2011-07-1') means the same thing as 2011-07-01 00:00:00.
So you need
      start_date >= '$start_date_start'
  AND start_date <  '$start_date_end' + INTERVAL 1 DAY

instead of what you have, which is
start_date BETWEEN '$start_date_start%' AND '$start_date_end%' /*wrong!*/

The second clause with the < ... + INTERVAL 1 DAY picks up all possible times on the last day of your interval.
Edit Now that you've disclosed that you have two DATETIME columns, called start_date and end_date, it sounds like you're looking for items which start on or before a specific date, and end on or after that same date.  Try something like this:
 WHERE DATE(start_date) <= DATE('$specific_date')
   AND DATE(end_date) >= DATE('$specific_date')

The trick on queries like this is to spend the majority of your time thinking through and specifying the results you want. If you do this, the SQL is often perfectly obvious.


Q: How to set cvxpy n-dim variable first value? I'm a beginner at python and I try to use cvxpy library for my optimization project. I try to change the first value of my n dimensional variable But I get an AttributeError
import cvxpy as cp
S = cp.Variable(100)
S[0].value=320000

output:AttributeError: can't set attribute

It works for 1-dim variable
import cvxpy as cp
S = cp.Variable()
S.value=320000

Thanks in advance

A: The 'Variable' object does not support item assignment. You may enforce your requirement as a constraint:
import cvxpy as cp
S = cp.Variable(100) # Define your variables

objective = ... # Define your objective function

constraints = [] # Create an array of constraints
constraints.append(S[0]==320000) # Make your requirement a constraint

# Add more constraints

prob = Problem(objective, constraints) # Define your optimization problem
prob.solve(verbose=True) # Solve the problem

print(S.value)


Q: Google maps javascript example not working I am using the example from the google maps website.
https://developers.google.com/maps/documentation/javascript/tutorial
I am posting the entire code below. I get a blank screen - nothing seems to show up either on firefox or chrome. Can anyone suggest what is going on?
Thank you,
-VJ

      <!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0 }
      #map-canvas { height: 100% }
    </style>
    <script type="text/javascript"
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=SET_TO_TRUE_OR_FALSE">
    </script>
    <script type="text/javascript">
      function initialize() {
        var mapOptions = {
          center: new google.maps.LatLng(-34.397, 150.644),
          zoom: 8,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
      }
      google.maps.event.addDomListener(window, 'load', initialize);
    </script>
  </head>
  <body>
    <div id="map-canvas"/>
  </body>
</html>

A: Ok so i figured out the problem. I was saving the code in an html file using wordpad and saving it in format Unicode. When I saved the file using notepad and format ANSI, everything is ok. Took me the entire morning to figure this out!!!


Q: Display Google Map Direction instructions in different languages I am using Google Map service. Now I integrated Google Map Direction into my application, but all direction instructions are English.
Anyone know the way to translate it into other languages? (e.g Vietnamese). You can see the site: maps.google.com, when you use your own language, all the direction instructions are translated into your language. That's what I need.
Thanks :)

A: The directions service will either use the browser's configured language or you can specify the language to use when loading the API.
From the API docs:

Textual directions will be provided using the browser's preferred
  language setting, or the language specified when loading the API
  JavaScript using the language parameter. (For more information, see
  Localization.)

A: Just specify your language using the language parameter when loading the API:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en-US"></script>
See full list of supported languages here : https://developers.google.com/+/web/api/supported-languages


Q: UICollectionView load image cannot get correct cell swift 3 My UICollectionView is fetching images in cellForItemAt. After I upgrade to swift 3, some images are not showing when I scroll very fast. Here is my code in cellForItemAt:
if (imageNotInCache) {
    DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
    if let thumb = imageFromPathAndCacheIt(path) {
      DispatchQueue.main.async {
          let updateCell = collectionView.cellForItem(at: indexPath) as! MyCustomCell? {
             updateCell.imageView.image = thumb
          }
   }
}

The problem is, sometimes I get updateCell as nil even it is on the screen (probably because scroll to fast).
I know we can add reloadData after adding the image, just like: Swift 3: Caching images in a collectionView, but I don't want to call reload so many times.
Thank you for interested in this question. Any ideas would be very appreciated!

A: There's definitely a compromise between accessing and manually updating the cell view content, and calling reloadData on the whole collection view that you could try.
You can use the func reloadItems(at: [IndexPath]) to ask the UICollectionView to reload a single cell if it's on screen.
Presumably, imageNotInCache means you're storing image in an in-memory cache, so as long as image is also accessible by the  func collectionView(UICollectionView, cellForItemAt: IndexPath), the following should "just work":
if (imageNotInCache) {
    DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
        if let thumb = imageFromPathAndCacheIt(path) {
            DispatchQueue.main.async {
                self.collectionView.reloadItems(at: [indexPath])
            }
        }
    }
}


Q: Dynamically generate GraphQL schema One of my application requires Graphql schema that can have fields added & resolved on the fly based on the data. for example need something like
type Data {
   email: [String]!
   col1 :[Int]!
   col2: [Int]!
 ...col3:

}

where col1 == nameOfColumnOne, col2=nameOfColumnTwo etc will & be added based on the data and possibly set on the fly.
I am kind of stuck on this and will appreciate some help on this one please.

A: Couldn't you just have a resolver columns that resolves a list of these columns that will grow over time? It makes more sense to me. I don't believe that you can achieve this modeling that you want.
you would have a type Column which defines what a column is supposed to be, and have:
type Data {
   email: [String]!
   columns: [Column]!
}

Hope it helps you :)


Q: Alterações no código foram apagadas dentro do VS CODE Boa noite! Acabei de fazer várias alterações em meu projeto da faculdade, então cliquei em Source Control para enviar para o git. Quando eu estava digitando no commit message, algo deu errado. Não sei se foi algum erro no vs code ou mesmo se apertei um botão ou cliquei em algo que não deveria sem perceber... O fato é que todas as alterações que eu tinha feito foram apagadas e os arquivos voltaram ao que estava antes de todo o trabalho ser feito.
Alguém sabe dizer o que pode ter acontecido e principalmente se é possível recuperar essa parte perdida do código? Nenhum arquivo foi excluído, apenas todas as alterações que eu fiz hoje no projeto se apagaram dentro do VS Code, enquanto eu tentava enviar para o github.
Desculpem se eu não tiver sido clara na explicação, mas realmente não tenho ideia do que aconteceu  para poder ser mais detalhada.

A: 1 - Você estava registrando as alterações (commits)?

se sim, use o comando "git status" para ver seu último registro :D


Q: Alternative to using PHP-GMP to populate two column table A page is using the PHP GNU Multiple Precision (GMP) to determine how many rows should end up in each column. While the code works, we would like to migrate the application to a new host that does not support the PHP5-GMP module. That said, what might be the best alternative to generating and populating a two column table that may not always have an even number of results? Further the table design is probably not the best so I am open to alternatives.
The code below taken from here gets us close but since it uses mysql_fetch_array, it places the items like:
a   b
c   d

instead of
a   c
b   d

Is there a way to have it display in the first example?
Newer code:

<?php
mysql_select_db("database",$db);
$cat= $_GET["cat"];
echo '
';
$q = mysql_query("SELECT * FROM name WHERE Field4 = '$cat'",$db);
while ($res = mysql_fetch_array($q)){
    echo '
' . $res['Field1'] . '
';
}
echo '
';
?>

Original code:

<?php
$result = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
$myrow3 = mysql_fetch_row($result);
$num_rows = mysql_num_rows($result);
$d3 = gmp_div_q("$num_rows", "2", GMP_ROUND_PLUSINF);
$i = 1;
$result8 = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
while ($myrow3 = mysql_fetch_row($result8))
    {
    if ($i <= gmp_strval($d3))
    {
        echo "
";
        echo '';
        echo "$myrow3[1]";
        echo "
";
        $i = $i + 1;
    }
        else
    {
    }
    }
?>

<?php
$result = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
$myrow3 = mysql_fetch_row($result);
$num_rows = mysql_num_rows($result);
$d4 = gmp_div_q("$num_rows", "2", GMP_ROUND_MINUSINF);
$d3 = gmp_div_q("$num_rows", "2", GMP_ROUND_PLUSINF);
$j = 1;
$result18 = mysql_query("SELECT * FROM name WHERE field4 = '$cat' ",$db);
while ($myrow3 = mysql_fetch_row($result18))
{
if ($j <= gmp_strval($d3))
{
$j=$j+1;
}
else
{
echo "
";
echo '';
echo "$myrow3[1]";
echo "
";
$j = $j + 1;
}
}
?>

A: If i read well, you use gmp_div_q for rounding only? Then, you should check round().
The only case, that round() cannot cover is GMP_ROUND_ZERO, but you don't use that (and you could cover it with a simple if).


Q: TFS2013 Web Access - Configuration for Stakeholders We use TFS2013 on premise. A request came up that when using Web Access, some members with Stakeholder access should only have limited rights when opening work items.
They should be able to edit Description, Acceptance Criteria, etc fields, but others should be read-only, such as Iteration, State, etc.
The only option I saw was about tags Create tag definition option under
Security >> Permissions, but that's not enough for me.
One idea was Customizing a process template, but this seems to be thin ice as our team doesn't have any experience with it and the things to avoid list is quite long.
The best workaround approach so far is to reference the TFS ClientLibrary from Program Files (x86)\Microsoft Visual Studio 12.0\Common7\IDE\ReferenceAssemblies\v2.0\ and create a custom website which implements only the required features (for example when opening a work item, State would be a Label instead of a DropDownList).
The drawback of this solution is that it would keep the whole WebAccess portal hidden, including its nice features.
So my question in short: is there a way to make certain fields read-only on the work item form for stakeholder members?
UPDATE
Eventually I went towards Template Customization using TFS Power Tools 2013. Now I have to following problem:
Applying rules for certain fields work just fine, but in case the field type is TreePath, saving the template gives the following error

TF26062: Rule '< READONLY for="[Global]\Stakeholders" />' is not
  supported for the field 'System.AreaPath'.
There were validation errors. Continuing to save may cause the file to
  become unloadable, do you want to continue?

According to this answer from 2009: "there are some particular fields which can't be applied rules for"
Any suggestions how to go on?

A: You can choose the work item types to make some fields read only.
You will never need to be careful to not mark field read only that are needed for adding items. That would include area and iteration. Use witadmin.exe to export the desired work item and add read only clauses only for those in the stakeholder group.
You would be better with a permissive model. Allow everything and tell them what bout to change. Then have an alert for changes to those fields by stakeholders.


Q: Is custom membership provider the thing that really worth to follow? After long tries to get answer to my question "Should I write custom MembershipProvider implementation or make my own custom system?" on SO I decided that it's not so bad to go MembershipProvider's way and start writing my membership provider. But at the time I feel some trouble.
For instance, in my system there's no user names. The emails are user names. So the CreateUser method should look like this:
public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
{
    bool userExists = GetUser(email);
    if (userExists) {
        status = MembershipCreateStatus.DuplicateEmail;
        return null;
    }
    bool? tryExists = regTryExists(email);
    if (tryExists.HasValue && tryExists.Value && !userExists)
    {
        UserRepository.CreateUser(email, password);
        status = MembershipCreateStatus.Success;
        return GetUser(email);
    }

    return null;
}

Also, thus I don't need GetUserNameByEmail,FindUsersByName methods:
public override string GetUserNameByEmail(string email)
{
    return email;
}

public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
{
    throw new NotImplementedException();
}

So here I don't need username, passwordQuestion, passwordAnswer, isApproved arguments.
Also, in my system there is no user questions, so I don't need such methods as
public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
{
    return false;
}
public override string ResetPassword(string username, string answer)
{
    throw new NotImplementedException();
}

And this is just a part of waste and cumbersome membership system. It's not so realiable as I want.
So the question is Is it really worth to go with MembershipProvider? Could you please bring me over? Is there good advantages for MembershipSystem that makes it really value system?

A: Using the MembershipProvider essentially boils down to the "build or buy" decision any developer (or dev mgr) has to make: build it from scratch, or buy off-the-shelf (or in this case, use a pre-existing tool).
With that in mind... admittedly, the MembershipProvider isn't perfect - it's a bit clunky, and probably has too much (or too little) of what you'll need - but it's 85% of the way there for most implementations. And as alluded to by others, building your own authentication system from scratch just isn't worth the time or effort. This is a solved problem; use your development energy to solve more urgent and relevant business problems, not re-inventing the wheel!
Remember this axiom: unless you can gain a direct competitive advantage from developing something from scratch, you are (usually) better off using an existing tool for the job (buy, don't build).

A: Some advantages of the ASP.NET membership provider API:

*

*You don't have to reinvent the wheel. New comers on your project will be familiar with a well-known API.

*There are already implementations (SQL Server, Active Directory mostly) available you can re-use or start from.

*It's visually integrated with ASP.NET (Login Controls, etc.)

*You can use the built-in ASP.NET administration tool to create users & roles (it's in fact a good way to check your provider works fine, as it should work with the tool)

*It can be integrated with  the .NET (not only ASP.NET) Identity / Principal classes, and can be used to support the PermissionAttribute system (with the associated Role Provider). Although it technically lives in System.Web.dll, you can in fact use it in non-web systems.

*One last thing but quite interesting: you can also use ASP.NET membership providers in WCF services

A: Well MembershipProvider is indeed useful. The complete ASP.Net security infrastructure is build around it. Lot of the control can directly interact with this infrastructure such as Login, LoginStatus. So it does have it's advantage.
But it also has it's fair share of problem due to its fat interface. It's breaking the interface segregation principle and hence is a little cumbersome to use. I believe the advantages outweigh the penalty we pay here. So as long there are simple workarounds there are no harms using it. Building your own security infrastructure is not a trivial task either.

A: It sounds like the default MembershipProvider does everything you need it to do.
Therefore I would definitely recommend creating a UserBusinessclass that wraps the MembershipProvider and only exposes the features you use.
This makes it easy to use the great features of the MembershipProvider but also simplifies the interface for your needs.

A: I used custom provider first but now switched out completely.
I kept just a principle where things like when to lock user, how to hash password, etc
I was fine with custom provider until I needed multi-tenant support with different databases. And last drop was my attempt to unit test WCF service that used membership provider. Now I have my MembershipService and life is good. I still have data structure almost identical to original, but in .NET I use my code


Q: Ruby on rails on bigrock hosting I am using bigrock hosting
i want to learn ror
i have putty access with ssh
what i have done is
rails new appname -d mysql
Using # Set by Administrator # Ruby on Rails support depends on this script # Do NOT modify unless you know what you're doing export GEM_HOME=/home/user/ruby/gems export GEM_PATH=$GEM_HOME:/opt/ruby/lib/ruby/gems/1.9.1 export PATH=$GEM_HOME/bin:/opt/ruby/bin:$PATH from /home/user/.railsrc

i am getting error
   run  bundle install
/home/user/ruby/gems/gems/bundler-1.7.2/lib/bundler.rb:302: warning: Insecure world writable dir /home/user/public_html/apps in PATH, mode 040777
Fetching gem metadata from https://rubygems.org/............
Resolving dependencies...
Using rake 10.4.2
Using i18n 0.7.0

Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.

        /opt/ruby/bin/ruby extconf.rb
creating Makefile

make
compiling generator.c
make: execvp: gcc: Permission denied
make: *** [generator.o] Error 127

Gem files will remain installed in /home/user/ruby/gems/gems/json-1.8.2 for inspection.
Results logged to /home/user/ruby/gems/gems/json-1.8.2/ext/json/ext/generator/gem_make.out
An error occurred while installing json (1.8.2), and Bundler cannot continue.
Make sure that `gem install json -v '1.8.2'` succeeds before bundling.
         run  bundle exec spring binstub --all
/home/user/ruby/gems/gems/bundler-1.7.2/lib/bundler/runtime.rb:222: warning: Insecure world writable dir /home/user/public_html/apps in PATH, mode 040777
/home/user/ruby/gems/gems/bundler-1.7.2/lib/bundler/runtime.rb:222: warning: Insecure world writable dir /home/user/public_html/app in PATH, mode 040777
Warning: You're using Rubygems 1.8.23 with Spring. Upgrade to at least Rubygems 2.1.0 and run `gem pristine --all` for better startup performance.
* bin/rake: spring inserted
* bin/rails: spring inserted

bundle install will cause this error
Fetching gem metadata from https://rubygems.org/............
Resolving dependencies...
Using rake 10.4.2
Using i18n 0.7.0
/home/user/ruby/gems/gems/bundler-1.7.2/lib/bundler.rb:302: warning: Insecure world writable dir /home/user/public_html/apps in PATH, mode 040777
Gem::Installer::ExtensionBuildError: ERROR: Failed to build gem native extension.
    /opt/ruby/bin/ruby extconf.rb

creating Makefile
make
compiling generator.c
make: execvp: gcc: Permission denied
make: *** [generator.o] Error 127
Gem files will remain installed in /home/user/ruby/gems/gems/json-1.8.2 for inspection.
Results logged to /home/user/ruby/gems/gems/json-1.8.2/ext/json/ext/generator/gem_make.out
An error occurred while installing json (1.8.2), and Bundler cannot continue.
Make sure that gem install json -v '1.8.2' succeeds before bundling.
please help me to run a app in bigrock hosting


Q: Is it necessary to pre-defined variables in prepared statement? I have the following prepared statement:
            $stmt = $conn->prepare("SELECT * FROM `users` WHERE user LIKE ? ");
            $stmt->bind_param("s", $filtered_form['user']);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows > 0) {
               $stmt->bind_result($id, $user, $pass, $first, $last, $type, $email);
               $stmt->fetch();
               $stmt->close();
            }
            if ($pass === $filtered_form['pass']) {
               $_SESSION['id'] = $id;
               $_SESSION['user'] = $user;
               $_SESSION['first'] = $first;
               $_SESSION['last'] = $last;
               $_SESSION['email'] = $email;
               $_SESSION['type'] = $type;
               header("Location:index.php");
               exit;
            } else {
               return "Incorrect password";
            }

however Visual Studio says there is a problem that the variables $id, $user, $pass, $first, $last, $type, $email are not defined. I added the variables like this:
            $stmt = $conn->prepare("SELECT * FROM `users` WHERE user LIKE ? ");
            $stmt->bind_param("s", $filtered_form['user']);
            $stmt->execute();
            $stmt->store_result();
            if ($stmt->num_rows > 0) {
               $id  = "";
               $user = "";
               $pass = "";
               $first = "";
               $last = "";
               $type = "";
               $email = "";
               $stmt->bind_result($id, $user, $pass, $first, $last, $type, $email);
               $stmt->fetch();
               $stmt->close();
            }
            if ($pass === $filtered_form['pass']) {
               $_SESSION['id'] = $id;
               $_SESSION['user'] = $user;
               $_SESSION['first'] = $first;
               $_SESSION['last'] = $last;
               $_SESSION['email'] = $email;
               $_SESSION['type'] = $type;
               header("Location:index.php");
               exit;
            } else {
               return "Incorrect password";
            }

And the problem goes away. Upon reviewing the PHP documentation, I cant find examples where the variables must be defined first, yet visual studio still shows it as an error. Any idea why this is?

A: Nope, it is not necessary when variables are passed by reference, which is the case here. So it's Visual Studio who is wrong here.
However, you are using obsoleted techniques here, and can get rid of these false positive warnings and reduce the amount of code at once:
        $stmt = $conn->prepare("SELECT * FROM `users` WHERE user = ? ");
        $stmt->bind_param("s", $filtered_form['user']);
        $stmt->execute();
        $row = $stmt->get_result()->fetch_assoc();
        if ($row and password_verify($filtered_form['pass'], $row['pass']) {
           $_SESSION['user'] = $row;
           header("Location:index.php");
           exit;
        } else {
           return "Incorrect password";
        }

as you can see, get_result() gives you a much better result (pun not intended) than store_result(), letting you to store the user information in a single variable, so it won't litter the $_SESSION array.
And num_rows() proves to be completely useless (as it always happens).
An important note: you should never ever store passwords in plain text. Alwas shore a hashed password instead.


Q: How to use selectindexchange to show or hide a dropdown/combo box in powershell I am trying to create a GUI that has several combo boxes. I want to keep 2 of them hidden until a selection is made in another.
The account type combo is blank - both are hidden
Combobox account type select "Clinical" and the Division combo box appears
combobox account type "MSO" selected and the Department Combobox appears
Here is the code
    ##Type of account drop down
$acctype = New-Object System.Windows.Forms.Label
$acctype.Text = "Account Type"
$acctype.Location  = New-Object System.Drawing.Point(10,140)
$acctype.Size = New-Object System.Drawing.size(100,20)
$form.Controls.Add($acctype)

#Acctype Dropdown
$cbacctype = New-Object System.Windows.Forms.Combobox
$cbacctype.Width = 200
$cbacctype.Location = New-Object system.drawing.point(120,140)
$cbacctype.Items.Add("Clinical")
$cbacctype.Items.Add("MSO")

##################################################################################################
## Location drop down
##location text
$loc = New-Object System.Windows.Forms.Label
$loc.Text = "Location"
$loc.Location  = New-Object System.Drawing.Point(10,230)
$loc.Size = New-Object System.Drawing.size(100,20)
$form.Controls.Add($loc)

#location Dropdown
$cbloc = New-Object System.Windows.Forms.Combobox
$cbloc.Width = 200
$cbloc.Location = New-Object system.drawing.point(120,230)

###################################################################################################
## Provider/Divison selection - if possabile make only visiable when account type "Clinical" selected
##division text
$division = New-Object System.Windows.Forms.Label
$division.Text = "Division"
$division.Location  = New-Object System.Drawing.Point(10,260)
$division.Size = New-Object System.Drawing.size(100,20)
$form.Controls.Add($division)

#Division Dropdown
$cbdivision = New-Object System.Windows.Forms.Combobox
$cbdivision.Width = 200
$cbdivision.Location = New-Object system.drawing.point(120,260)

###################################################################################################
## MSO Department Drop Down - if possabile make only visiable when account type "MSO" selected
##department text

$depart = New-Object System.Windows.Forms.Label
$depart.Text = "Department"
$depart.Location  = New-Object System.Drawing.Point(10,290)
$depart.Size = New-Object System.Drawing.size(100,20)
$form.Controls.Add($depart)

#Department Dropdown
$cbdepart = New-Object System.Windows.Forms.Combobox
$cbdepart.Width = 200
$cbdepart.Location = New-Object system.drawing.point(120,290)


Q: Lex's incorrect algorithm for lookahead operators In "modern compiler implementation in Java" by Andrew Appel he claims in an exercise that:

Lex has a lookahead operator / so that the regular expression abc/def matches abc only when followed by def (but def is not part of the matched string, and will be part of the next token(s)). Aho et al. [1986] describe, and Lex [Lesk 1975] uses, an incorrect algorithm for implementing lookahead (it fails on (a|ab)/ba with input aba, matching ab where it should match a). Flex [Paxson 1995] uses a better mechanism that works correctly for (a|ab)/ba but fails (with a warning message on zx*/xy*. Design a better lookahead mechanism.

Does anyone know the solution to what he is describing?

A: "Does not work how I think it should" and "incorrect" are, not always the same thing. Given the input
aba

and the pattern
(ab|a)/ab

it makes a certain amount of sense for the (ab|a) to match greedily, and then for the /ab constraint to be applied separately. You're thinking that it should work like this regular expression:
(ab|a)(ab)

with the constraint that the part matched by (ab) is not consumed. That's probably better because it removes some limitations, but since there weren't any external requirements for what lex should do at the time it was written, you cannot call either behavior correct or incorrect.
The naive way has the merit that adding a trailing context doesn't change the meaning of a token, but simply adds a totally separate constraint about what may follow it. But that does lead to limitations/surprises:
 {IDENT}  /* original code */

 {IDENT}/ab   /* ident, only when followed by ab */

Oops, it won't work because "ab" is swallowed into IDENT precisely because its meaning was not changed by the trailing context. That turns into a limitation, but maybe it's a limitation that the author was willing to live with in exchange for simplicity. (What is the use case for making it more contextual, anyway?)
How about the other way? That could have surprises also:
 {IDENT}/ab  /* input is bracadabra:123 */

Say the user wants this not to match because bracadabra is not an identifier followed by (or ending in) ab. But {IDENT}/ab will match bracad and then, leaving abra:123 in the input.
A user could have expectations which are foiled no matter how you pin down the semantics.
lex is now standardized by The Single Unix specification, which says this:

r/x
  The regular expression r shall be matched only if it is followed by an occurrence of regular expression x ( x is the instance of trailing context, further defined below). The token returned in yytext shall only match r. If the trailing portion of r matches the beginning of x, the result is unspecified. The r expression cannot include further trailing context or the '$' (match-end-of-line) operator; x cannot include the '^' (match-beginning-of-line) operator, nor trailing context, nor the '$' operator. That is, only one occurrence of trailing context is allowed in a lex regular expression, and the '^' operator only can be used at the beginning of such an expression.

So you can see that there is room for interpretation here. The r and x can be treated as separate regexes, with a match for r computed in the normal way as if it were alone, and then x applied as a special constraint.
The spec also has discussion about this very issue (you are in luck):

The following examples clarify the differences between lex regular expressions and regular expressions appearing elsewhere in this volume of IEEE Std 1003.1-2001. For regular expressions of the form "r/x", the string matching r is always returned; confusion may arise when the beginning of x matches the trailing portion of r. For example, given the regular expression "a*b/cc" and the input "aaabcc", yytext would contain the string "aaab" on this match. But given the regular expression "x*/xy" and the input "xxxy", the token xxx, not xx, is returned by some implementations because xxx matches "x*".
In the rule "ab*/bc", the "b*" at the end of r extends r's match into the beginning of the trailing context, so the result is unspecified. If this rule were "ab/bc", however, the rule matches the text "ab" when it is followed by the text "bc". In this latter case, the matching of r cannot extend into the beginning of x, so the result is specified.
  As you can see there are some limitations in this feature.

Unspecified behavior means that there are some choices about what the behavior should be, none of which are more correct than the others (and don't write patterns like that if you want your lex program to be portable). "As you can see, there are some limitations in this feature".


Q: Xpath to click on Eye Icon In my application, i have to perform click operation on an Eye icon to view the documents but i am unable to generate proper xpath to locate that icon.
Below is the image of HTML code.I am unable to copy paste the code hence attaching the image.

Salary Slips

Below is the code tried but i am no such element error.
IWebElement salaryeyeicon = driver.FindElement(By.XPath("//*[@id='DocSelected-1']/span/span/i"));
            salaryeyeicon.Click();

(OR)

 IWebElement salaryeyeicon = driver.FindElement(By.XPath("//div[@id='DocSelected-1']//span[@class='col-xs-10 dl-no-padding']//i[@class='document-icon-eye dl-padding-right-10 pull-right']"));
     salaryeyeicon.Click();

Kindly suggest the right way to locate the element.

A: The problem with your first xpath is probably that the i element is not nested in any span elements.
Maybe it is not necessary to specify the full path to the element, because it's class document-icon-eye is more or less sufficient identificator in your concrete scenario. You could use something like this:
//div[@id='DocSelected-1']//i[contains(@class, 'document-icon-eye')]

I suggest you to use the built in xpath search tool in the browser developer tools. Pasting the candidate xpath in the search field (Ctrl  + F in the Elements view) will quickly show you if the xpath provided will work properly. Probably this could save you a lot of time from successive trial and error compilations and executions of your code.
After the edit the correct versions of your xpaths would be:
//div/i

//div[@id='DocSelected-1']//i[@class='document-icon-eye dl-padding-right-10 pull-right']


Q: Does Tailscale log the IPs of devices which are connected on your account? I know a lot of VPNs say they don’t log IPs, but then have other situations internally. I’m not even sure entirely how Tailscale works on the server-side, does one device connect to Tailscale servers connecting to another device, or do the devices somehow connect directly using the software package and only send status updates to Tailscale? I need to know the level of security/privacy it’s offering.

A: Tailscale appears to be a VPN network built on wireguard.   As its a cloud based VPN server, and they run the servers the issue if logging is thee same as with any VPN provider.
Further, they actively advise they do logging (and let you see it) - "Tailscale’s central logging service has controllable retention periods and each node just logs some metadata about how your internal mesh is established, not Internet usage or personal information. (Read our privacy policy for more.)"   - as per https://tailscale.com/blog/how-tailscale-works/
If you are looking for a "no logs" VPN, this is not for you. They make that pretty clear in their Privacy Policy - https://tailscale.com/privacy-policy


Q: Symfony2 Docrine ODM: dynamic collection name I'm using MongoDB Doctrine ODM on a Symfony 2 project. In the documents classes the mapping metadata are specified by annotations.
For example:
    /**
     * @MongoDB\Document(collection="statistiche")
     */

The collection name in this way is hardcoded. I want to have dynamical collection name parameter, that can be readed from global parameters.yml Symfony file (and, consequently, can be configured by user). How can I perform this goal? Thanks.

A: Then don't use the annotation but use yaml from your metadata definition.
Documentation and Example
But be aware that every metadata definition (be it per annotation, yaml or whateever) usually is loaded only once and cached for performance reasons in production.
That means that you usually have to clear your cache to use an updated metadata definition.
Another issue to consider is when you rename an already existing document/attribute. This might require some migration activities to avoid unexpected behaviour.


Q: Laravel 5.6 how to read text file line by line Without Laravel I can use simple code to read text file by line:
$file = fopen("whatever/file.txt", "r") or exit("Unable to open file!");

while(!feof($file)) {
   echo fgets($file). "
";
}

fclose($file);

With Laravel this simple thing becomes overwhelming due to local file storage location.
I.e. I can get file contents with Storage::get('whatever/file.txt') method, but how to get just a file and then read it in a loop?
I've tried to use File::get('whatever/file.txt') method but get an error: File does not exist at path.
How to read file from local storage (not public) line by line with Laravel?

A: You can get your file like this:
$file = fopen(storage_path("whatever/file.txt"), "r");

This will result in a path similar to this
'/var/www/storage/whatever/file.txt' or '/var/www/foo/storage/whatever/file.txt' if you are serving multiple websites from the same server, it will depend on your setup, but you get the gist of it. Then you can read your file;
while(!feof($file)) {
    echo fgets($file). "
";
}

fclose($file);

A: You need to know where your file lives. You also need a path to get there.
E.g., if your file is located in the storage folder, you could do
File::get(storage_path('whatever/test.txt'));
dd($contents);

A: Laravel v 9.0 update
File::lines('whatever/file.txt')->each(function ($line) {
    $this->info($line);
}

A:     $files = ExamFile::where('exam',$code)->get();
    foreach ($files as $file)
    {
        $content = fopen(Storage::path($file->url),'r');

        while(!feof($content)){

            $line = fgets($content);

            echo $line."
";
        }

        fclose($content);
    }

You can use it like this. It works for me.

A: Hope it will help
  File::get(storage_path('whatever/file.txt'));

A: So confusing!
My file was in the folder storage/app/whatever/file.txt but Laravel storage("whatever/file.txt") method recognizes it as storage/whatever/file.txt path.
As I said before it is overwhelming and confusing a lot.
So, fopen('storage/app/whatever/file.txt') works for me.


Q: Make round edged button in WPF I want to make my button round edged. My button code is as follows:-
<Button Grid.Column="1" Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}" HorizontalAlignment="Center"  BorderThickness="1" Foreground="White" FontFamily="Arial,Helvetica,sans-serif" Width="85"  Background="#6F933D" BorderBrush="#48671E" CommandParameter="11" Command="{Binding AuditCommand}" Visibility="{Binding ViewModel.IsCompleteAccessible}" Margin="38,0,60,0" Height="24" VerticalAlignment="Bottom">Complete</Button>

Please Help.
Thanks

A: Try this
<Window.Resources>
        <Style x:Key="test" TargetType="Button">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="Button">
                        <Border Name="ButtonBorder" CornerRadius="10" BorderThickness="1" BorderBrush="Gray" Background="LightGray">
                            <ContentPresenter Content="{TemplateBinding Content}" HorizontalAlignment="Center" VerticalAlignment="Center"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </Window.Resources>
    <Grid>
        <Button Content="Button" Style="{StaticResource test}" Margin="0,137,0,0"  />
<Grid>


Q: How do I create a custom login page in Lightning using Napili template Napili automatically assigns login to its own Login page. The template does not appear to allow use of a Custom Login page. Also, the assigned Login page does not import the CMS Connect headers and footers. I need to be able to either customize the login page template to include the CMS Connect content or assign the login to a custom page of my choosing that uses the Customer service template.

A: You don't create your own login page, you modify the existing one by using your own components and (if you like) your own theme and layout.
See https://help.salesforce.com/articleView?id=networks_custom_login_self_reg_lightning.htm&type=5

Each community comes with a default set of Login pages: Check
  Password, Forgot Password, Login, Login Error, Register. Each has a
  standard Lightning component that drives this functionality. You can
  add code logic to customize the login experience per your company and
  community’s requirements.
From Setup, enter Lightning Components in the Quick Find box, then
  select Lightning Components under Develop. From the list of
  components, click on the one you want to customize. For example, to
  customize the login experience, click loginForm. On the Lightning
  component detail page, click Developer Console. Follow the
  instructions in the code to expose the component in Community Builder.
  Add custom code logic and save your changes as a new custom component.
  Go back to Community Builder in your community and bring up the Login
  page from the list of pages. The custom component you created should
  display in the list of components.


Q: getting detailed SQL logs from Heroku Cedar Stack What exactly needs to happen in order to get detailed SQL logs out of heroku cedar?
On our dev platform the log trail gives us lots of information including insite into the SQL which is being executed by activerecord. In production the information is much less detailed.
What do i need to do to get this SQL information when i run
heroku logs --tail

Is there a setting i need to send to heroku or something i need to put into my rails code?
Thanks!

A: Heroku's Logplex contains all logging statements from your application - there is no filtering of any kind.
By default, Rails does not log SQL statements in production so you'll need to bump your log level in production.rb to a level that is more suitable.
http://guides.rubyonrails.org/debugging_rails_applications.html#log-levels


Q: apache server serving index.html instead of index.php, after changing the file preference inside the dir.conf file I changed the file preference inside the dir.conf file:
$sudo nano /etc/apache2/mods-enabled/dir.conf

<IfModule mod_dir.c>
    DirectoryIndex index.php index.html index.cgi index.pl index.xhtml index.htm
</IfModule>

This means that index.php will get first preference, right?
In /var/www/html i have two files i.e index.html and index.php.
But when i visit my ip_address in my browser, the index.html is being served instead of index.php. Am i missing out something?

A: Change your dir.conf file :
<IfModule mod_dir.c>
        DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
</IfModule>


Q: Regex JavaScript overlapping matches If I have a string like fooba and I want to catch both foo and fooba how can I do? If I use foo|fooba it cathes only the first foo and not fooba.

A: Use lookaheads (zero-width assertion) for both patterns:
(?=(foo))(?=(fooba))

RegEx Demo


Q: how to download bitbucket code to new machine I am using git and my code is in bitbucket. I changed my laptop. I want to know the steps to set up entire thing in my new laptop. By the way, I am using ubuntu, ubuntu commands will be helpful.
Thanks.

A: Use git clone and clone from your bitbucket repository.


Q: Can I (or should I) use a MacBook charger on my iPhone? I recently got a MacBook with the USB-C charger. It comes with a 29-watt power brick, and I was wondering if I should use this to charge my iPhone. I've heard that the iPad power brick (I think 10 watts) charges the phone faster. I don't expect to be able to charge the phone proportionally faster, but would the MacBook brick damage the phone? I would rather only have to carry around one charging brick around campus. Also, I have a USB to USB-C converter.

A: This video shows that you can use MacBook 12" 29W USB-C Power Adapter with iPad and iPhone.
https://www.youtube.com/watch?v=fWzbaH24Q0Y

A: Unless there is some reason to the contrary that I'm not aware of, yes, you can use your MacBook charger with your iPhone. The power adapter will only convert as much power as is drawn, and the iPhone will only draw as much power as it needs.
(Note that it is not a good idea to charge your MacBook with an iPhone or iPad charger!)

A: Yes, at least for the iPhone 6S using the Apple USB-C to Lighning 2m cable. I just started using it this week with mine and haven't had any issues.
For a few years I've charged my iPhone with an iPad charger. Not sure if the 29W charger is faster, but at least it seems just as fast.
Also, I heard in a podcast about videos warning about USB-C to USB converters. As long as you trust the one you have and it's not sketchy, I think it should be OK.

A: My Macbook Pro 13inch Late 2016 61W USB-C Power brick says output: 20.3V/3A, 9V/3A or 5.2V/2.4A.
So yes you can charge your iphone with the Macbook charger.
The people at the Apple store just don't know what they are selling.

A: Using a USB-C to USB-A adapter and a USB-A to Lighting cable to your MacBook charger means your iPhone gets no more power than using a common 12 watt USB-A charger, both cases means the phone sees 5 volts @ 2.4 amps.
With the MacBook 29 watt charger and a USB-C to Lightning cable the iPhone sees more power but Apple doesn't say how much more.  It's safe or Apple would not allow it.  I charge my iPhone from my 61 watt and 87 watt MacBook chargers regularly with nothing wrong that I can see.
If you wish to carry around just one charger then I would suggest getting something bigger to charge both.  With the phone plugged into the laptop, and the laptop plugged into the charger there's potential to charge both more quickly with a power powerful power supply.
A quick look at the Apple store shows me that Apple discontinued all but three USB-C chargers, 30W, 61W, and 96W.  This makes a bit of sense because there's not much need to keep a 87 watt supply around when it's going to be about the same size, mass, and cost of their 96 watt supply.  It's really impossible to get a supply that's too big because the phone and laptop will take only so much power and a bigger supply isn't going to damage anything.  Too small though and you will be waiting for your devices to charge when you would not have to with a larger charger.
With a 30 watt charger being the default for either device it would seem logical that to charge both at the same time with their maximum charge rate it would take the 61 watt charger.  The MacBook will pass power just fine to the phone so both can charge quickly.  Charging either alone with the charger will be fine as well.
If a new charger is something that you might not see a need for at this time then that's fine, the charger you have will not overheat or anything.  The phone and laptop are smart enough to share the power and still charge, if just more slowly than with a larger charger.

A: Yes you can. https://support.apple.com/en-us/HT208137

You can fast charge your iPhone 8 and later up to 50 percent battery in around 30 minutes.
Fast charging works when you use an Apple USB-C to Lightning cable and one of these adapters:

*

*Apple 18W, 20W, 29W, 30W, 61W, 87W, or 96W USB-C Power Adapter

*A comparable third-party USB-C power adapter that supports USB Power Delivery (USB-PD)


Q: Compact Lie group bi-invariant metric Let $G$ be a compact Lie group and $\left\langle ,\right\rangle $
be a left invariant metric on $G$; $\omega$ be a positive differential
$n$-form on $G$ which is left invariant. Consider the metric $(,)$
on $G$ given by:
$$
\left(u,v\right)=\int_{G}\left\langle (dR_{x})_{y}u,(dR_{x})_{y}v\right\rangle _{yx}\omega$$
 It's not too hard to show that this is left-invariant but I'm wondering
how to show that $\left(,\right)$ is right-invariant?

A: Given $u, v \in T_yG$ arbitrarily,
$$(d(R_g)_yu, d(R_g)_yv)_{yg} = \int_G \left\langle d(R_x)_{yg}(d(R_g)_yu),~ d(R_x)_{yg}(d(R_g)_yv) \right\rangle_{ygx}~\omega,$$
by definition. The Chain Rule implies that $d(R_x)_{yg}d(R_g)_y = d(R_x \circ R_g)_y = d(R_{gx})_y$, so the above expression becomes
$$\int_G \left\langle d(R_{gx})_yu,~ d(R_{gx})_yv \right\rangle_{y(gx)}~\omega.$$
Now, if you define $f: G \rightarrow \mathbb{R}$ by $f(x) = \langle d(R_x)_yu,~d(R_x)_yv \rangle_{yx}$, what we have is
$$\int_G f(gx) ~\omega = \int_G L_g^*(f\omega) = \int_G fw,$$
where the first equality holds because $\omega$ is left-invariant and the last equality is the Change of Variables Theorem.

A: There is a problem of  the above answer:
$$
\int_G <d(R_x)_{yg}d(R_g)_y u, d(R_x)_{yg}d(R_g)_y v>_{ygx} \omega(gx)=\int_G f(gx)\omega(gx)\neq \int_G {L_{g}^{*}} f(x) L_{g}^{*}\omega (x)=
$$
Because
$$
L_{g}^{*}f(x)=<d(L_g)_{yx}d(R_{x})_{y}u,d(L_g)_{yx}d(R_x)_{y}v>_{gyx}
$$
But
$$
f(gx)=<d(R_{gx})_{y} u, d(R_{gx})_{y} v)>_{ygx}
$$


Q: A query on asynchronous response for Servlet request In context of Servlet request/response I read somewhere that:
Using a different thread to do work required by a request will, as you expect, allow the response to be sent immediately.

I am just wondering when a Servlet thread is handing over the actual processing to another thread then that means that it does not have the expected response with it at that point of time anyways, then what is the value in sending the immediate but meaningless response back to the browser?
Could someone please give me a valuable usecase for it.

A: That quote is talking about a scenario where you can return a meaningful response without actually finishing all the work required by the request. For instance you might upload a file to be processed and respond immediately with a processing ID, but pass the processing to another thread. Later on the client could make another request with that ID to find out if processing completed.
An asynchronous servlet scenario would hand off processing to another thread to do the work while blocking the request. But the blocked request would not tie up a servlet request thread during processing like a normal synchronous servlet request.
Suppose you had a single threaded processor and 10 requests were made at the same time. With a synchronous servlet that waited for the processing to finish, you'd have 10 blocked request threads + 1 processor thread. But with an asynchronous servlet, you'd have 0 blocked threads + 1 processor thread. That's a pretty significant gain.