text:
Q: Making an image stick to the bottom of the webpage hey guys, I have a web page in which I have an ad at the bottom of the page, now I want it that whenever a user scrolls down the page the ad should remain in the bottom only and also visible, something like sticky ad.... how could I achieve this?
Thanks in advance.

A: CSS Fixed positioning.
You can read about CSS positioning in general on the w3c. See http://www.w3.org/TR/CSS2/visuren.html#fixed-positioning for fixed positioning in particular.
An example:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>making an image stick to the footer of the webpage.</title>

This is my add

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum faucibus gravida lorem, id molestie lectus tempus rhoncus. Curabitur vel augue ut metus scelerisque hendrerit at at libero. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Morbi hendrerit mattis tristique. Suspendisse fermentum justo in sem euismod pretium aliquet at erat. Phasellus lorem tellus, mollis in dictum sed, iaculis eu massa. Vestibulum iaculis aliquam massa, in porttitor lectus placerat vel. Pellentesque pharetra, orci non pretium porttitor, dolor justo placerat nisi, ut posuere sem enim id lorem. Vestibulum congue gravida enim, in faucibus sapien condimentum id. Nulla consequat arcu eu magna porta at consectetur nisl suscipit. Praesent pellentesque venenatis placerat. Suspendisse potenti. Pellentesque elementum auctor nibh sit amet mattis. Pellentesque rutrum porttitor libero, ac interdum tellus ultrices ultricies. Donec vehicula luctus nulla, eget cursus magna condimentum vitae. Aliquam eu enim mauris. Donec feugiat pulvinar nunc a dignissim. Aliquam placerat semper velit, eu venenatis tellus euismod vitae. Sed vitae justo massa, in luctus libero. Maecenas justo libero, fermentum semper ornare vitae, pulvinar eget magna.

Cras augue tellus, dignissim eu dapibus et, porttitor non sapien. Maecenas augue mauris, pulvinar id congue sit amet, pellentesque in dui. Sed ac fringilla nisi. Nam sit amet odio sed sem fringilla cursus. Nullam nibh mauris, ullamcorper ut facilisis ut, pellentesque ut nunc. Nulla ultricies iaculis sapien a eleifend. Curabitur pulvinar, velit et egestas aliquet, felis est luctus libero, in ultricies quam massa a tortor. Quisque vehicula imperdiet risus vitae accumsan. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed vel adipiscing nunc. Quisque consectetur mattis volutpat. Morbi viverra rutrum ante quis vehicula. Vivamus placerat bibendum mi eu auctor. Phasellus porta pharetra sagittis. Pellentesque id dui nec velit aliquam dignissim. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque pellentesque velit a mi mattis a consequat orci gravida. Morbi vel placerat sapien. Vivamus turpis ante, rutrum a ullamcorper sit amet, interdum ut tellus.

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum augue arcu, aliquam vel elementum vel, iaculis ut lorem. Curabitur id nisi ac ipsum auctor sodales ut nec arcu. Vestibulum vitae risus in mi elementum mattis. Nulla imperdiet mattis enim, a ultricies magna fringilla eget. Maecenas vitae lacus sit amet eros cursus molestie at et dui. Morbi aliquam sagittis tellus ac placerat. Pellentesque vitae ante vitae sem imperdiet convallis. Donec sit amet tortor a ligula mollis dictum sit amet at purus. Sed ac sodales leo.

Sed vel est nec elit volutpat auctor. Mauris consequat, nulla eget accumsan euismod, neque dui ultricies justo, non vulputate elit felis non lorem. Donec venenatis pretium mauris quis interdum. Quisque vel augue at odio varius dignissim. Etiam tincidunt nunc nec diam faucibus faucibus. Praesent eget ligula vel nunc eleifend pharetra. Fusce pretium nisl libero. Nunc lacinia, ligula sed luctus sollicitudin, nulla nisl adipiscing odio, ac elementum nisl odio eget metus. Sed non eleifend massa. Praesent dictum neque non sapien fermentum pulvinar. Etiam vestibulum cursus elit eu vehicula. Vivamus et nunc lectus. Aliquam ac vestibulum nibh. Quisque a est nibh, id fringilla nisi. Pellentesque tristique euismod lectus. Vivamus dictum nibh eu ligula consequat sit amet viverra nunc posuere. Maecenas vitae erat ipsum. Aliquam a tempor velit. Donec eleifend neque id dui blandit vel eleifend risus lobortis. Aliquam erat volutpat.

In hac habitasse platea dictumst. Aenean facilisis orci sed ligula rhoncus condimentum. Aliquam lacus sapien, congue et commodo fringilla, tempus id neque. Donec vitae purus tortor. Nunc scelerisque rutrum lacinia. Ut est libero, tincidunt vel vulputate id, gravida non velit. Morbi et dolor sit amet turpis hendrerit consequat. Morbi ut felis adipiscing est eleifend lobortis. Cras vitae enim diam, et mattis dui. Proin volutpat risus sed nunc facilisis eleifend. Nunc eu interdum ipsum.

Ut fermentum interdum lectus pellentesque aliquet. In tincidunt turpis sit amet velit egestas condimentum auctor leo elementum. Maecenas fermentum sem at risus laoreet luctus sed id diam. Cras porttitor lacinia leo, porttitor condimentum eros mollis non. Phasellus tempus quam vulputate sapien scelerisque ultricies. Cras nunc sapien, rutrum vitae porttitor at, hendrerit a augue. Fusce eget felis nulla, at condimentum libero. Aliquam porta suscipit scelerisque. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur massa metus, faucibus sit amet sagittis ut, interdum non mi. Sed lacinia interdum pharetra. Integer pellentesque facilisis euismod. Vestibulum posuere, lorem quis dapibus viverra, sapien ipsum tempus nulla, vel cursus nibh ante nec arcu. Nullam feugiat elementum est eget gravida. Nam venenatis odio nec nulla faucibus vel ultrices metus mattis. Vestibulum ut rhoncus orci. Quisque nisl dolor, lobortis rutrum dapibus ac, pharetra ultricies tortor. In eu ante non est semper mattis. Fusce cursus, nulla eu pellentesque semper, arcu erat rutrum justo, sed condimentum velit ipsum eget elit. Fusce consectetur lacinia nibh lacinia scelerisque.

Vestibulum non nisi orci, a pulvinar enim. Curabitur gravida orci eget mauris laoreet non dignissim velit adipiscing. Vivamus vel ipsum risus. Duis bibendum tempus accumsan. Proin mollis pellentesque ullamcorper. Praesent ac lectus magna. Morbi condimentum vehicula rutrum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras magna erat, euismod ut viverra ac, molestie a nisl. Aenean auctor, urna in venenatis accumsan, risus erat commodo nunc, porttitor sagittis sapien metus non mauris. Maecenas eget commodo dui. Maecenas mi metus, fermentum vitae lacinia sed, tristique vitae nunc. Morbi sed nulla nec orci vestibulum condimentum congue vitae leo. Pellentesque risus felis, euismod at convallis id, auctor nec purus. Pellentesque id ipsum augue, ullamcorper commodo arcu. Sed rutrum placerat dui et sollicitudin. Cras vel odio nunc.

In in nibh erat, vitae semper odio. Suspendisse feugiat turpis in leo consectetur gravida. In hac habitasse platea dictumst. Praesent vehicula ultrices ligula non tempor. Vivamus cursus mauris vel lacus malesuada aliquam. Maecenas egestas volutpat velit vitae fringilla. Vivamus rhoncus gravida faucibus. Nulla viverra iaculis lorem, ac adipiscing enim sodales eget. Duis cursus lacus nec odio molestie vulputate. Maecenas in risus at mi bibendum lobortis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed mollis, quam in volutpat sagittis, ante ipsum auctor metus, bibendum mollis eros nunc ac massa.

Nullam facilisis lacinia magna, et semper ante pellentesque laoreet. Aenean vel turpis augue. Pellentesque eget quam eu sapien gravida fringilla at at dui. Vivamus posuere, massa condimentum laoreet aliquet, nulla metus mollis mi, in blandit libero ante quis nulla. Aenean luctus massa faucibus sem consectetur eu viverra turpis vestibulum. Suspendisse pharetra scelerisque posuere. Nulla adipiscing urna at lacus euismod nec feugiat odio ornare. In hac habitasse platea dictumst. Duis tempor tellus eget turpis tempus consectetur. Donec odio enim, vestibulum sit amet tristique quis, adipiscing eu massa. Nulla interdum scelerisque diam vitae accumsan. Nullam diam sem, tempus sed tempus ut, tincidunt vitae felis. Praesent viverra mattis rutrum.

Praesent consectetur, leo non aliquam molestie, nibh nunc tempus odio, in ullamcorper sapien tortor id dui. Maecenas vitae pretium eros. Praesent orci magna, feugiat a tincidunt eget, rutrum eu risus. Curabitur volutpat nunc eu turpis accumsan aliquet. Donec eu purus a diam cursus pellentesque sit amet suscipit dolor. Fusce sit amet leo non dui sollicitudin consequat nec eget justo. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Praesent viverra mattis justo, non gravida urna cursus semper. Cras feugiat leo eget tellus porttitor at lobortis tellus sodales. Proin aliquet mi ut orci dictum congue. Maecenas vitae metus sit amet velit fermentum hendrerit eu non metus. Curabitur varius, turpis id tempus mattis, mi elit consectetur nisi, nec pharetra ipsum metus sed lacus. Nullam eget nunc diam. Proin a mi eget augue pretium tempus. Aliquam egestas laoreet elit, et viverra purus posuere quis. Donec laoreet urna augue. Maecenas id magna leo. Mauris vel lacus nibh, nec sodales tortor.

Aenean a sem ut augue faucibus dapibus. Vivamus imperdiet, urna eget egestas malesuada, diam libero pretium ligula, a ultricies purus elit ac ligula. Nunc vulputate, justo vitae suscipit adipiscing, orci ante dictum lectus, ac euismod leo nisl vitae est. Ut mattis, mi a feugiat adipiscing, eros nibh rhoncus lectus, eget aliquam urna neque id tortor. Nunc tristique sapien eu leo cursus ultricies aliquam risus posuere. Cras sodales laoreet augue ut fringilla. Etiam eleifend libero et elit commodo at venenatis nulla viverra. Nunc eu auctor risus. Phasellus vitae urna at sem pellentesque posuere nec at tortor. Cras porta malesuada risus, vitae porttitor velit ultricies eu. Nam dolor tortor, iaculis sed imperdiet nec, mollis ut dui. Aenean in metus neque. Sed tempor nulla et quam blandit facilisis. Proin sem tellus, faucibus id gravida at, dapibus auctor leo. Integer ornare, risus et ultricies pretium, magna nulla hendrerit quam, vitae viverra mauris dui eu magna. Aliquam vel erat quis libero feugiat fringilla porttitor in turpis. Phasellus vulputate accumsan facilisis.

Duis vehicula lobortis porta. Vestibulum auctor augue in odio adipiscing laoreet. Nunc arcu ligula, eleifend at ullamcorper blandit, porttitor quis sem. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Mauris condimentum quam at lacus tempus scelerisque. Aliquam molestie consectetur dapibus. Quisque eget nisl ut purus tincidunt imperdiet a varius ante. Cras a urna odio, vitae lacinia nisl. Cras non lectus eu libero interdum accumsan. Fusce non tincidunt magna. Mauris at tortor quis lorem viverra congue.

Proin et sapien justo, auctor aliquam justo. Etiam elementum scelerisque augue. Nam tristique rutrum ante, ac accumsan sem lobortis ut. Integer eros elit, euismod non sollicitudin non, pellentesque vitae purus. Nam diam diam, vestibulum lobortis malesuada ac, pretium sit amet orci. Proin feugiat nunc lacinia metus congue et tincidunt sapien posuere. Sed urna felis, dignissim in volutpat vel, ullamcorper vel nunc. Sed eu odio metus, nec facilisis velit. Mauris pharetra mauris a nibh lacinia ut pulvinar leo sollicitudin. Quisque rutrum orci nunc. Praesent orci tellus, consequat ut semper non, gravida sit amet elit. Aenean ornare dui nec risus auctor non varius risus dignissim.

Nulla erat nunc, facilisis quis laoreet id, aliquet at ipsum. Nam nulla risus, elementum eget tempus vitae, ultrices ac magna. Donec at mauris id libero mollis vehicula egestas interdum nisl. Suspendisse in vehicula nulla. Integer enim magna, adipiscing ac dignissim in, hendrerit et est. Curabitur at risus nisl. Sed ornare nulla fringilla sapien fringilla nec tincidunt sapien rutrum. Donec in ligula vitae arcu imperdiet aliquam eu et urna. Curabitur congue, sapien at posuere consequat, ipsum risus sodales erat, non vestibulum sem libero nec nisi. Sed nec egestas erat. Pellentesque lobortis massa sed sem tincidunt in fringilla mi tincidunt. Curabitur imperdiet, erat non accumsan pulvinar, nisi magna gravida tortor, nec consectetur nulla turpis id lectus. Praesent lacinia auctor felis, nec varius nunc iaculis sed. Nunc eget tempor est. Nullam luctus ligula sed velit auctor elementum. Proin sit amet malesuada magna. Morbi venenatis augue et arcu eleifend mattis a nec erat.

Aliquam erat volutpat. Integer fringilla urna et lorem tincidunt porttitor. Sed varius posuere neque, sit amet pulvinar mauris faucibus quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nec ultrices nulla. Phasellus id justo leo. Aliquam consequat dui at neque ultrices placerat. Phasellus porttitor, nibh sit amet posuere tempus, magna turpis aliquet ante, at mattis leo purus et ante. Aenean semper varius risus non suscipit. Nullam at nisi orci, sed cursus leo. Phasellus vel purus a est rutrum volutpat.

varius neque non mauris aliquet mattis quis at nunc. Nunc quis turpis quis metus vehicula laoreet. Praesent faucibus interdum congue. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Phasellus accumsan mauris quis ante sollicitudin tempus blandit ligula semper. Sed aliquam porta ante, ac egestas leo sollicitudin quis. Aliquam ornare magna in diam rhoncus ut mattis nibh rutrum. Ut erat mi, cursus ac auctor et, tincidunt sed nibh. Nulla quam magna, dignissim non venenatis vitae, ullamcorper fermentum purus. Vivamus tempor bibendum ipsum vel mollis. Morbi vel lectus a arcu tristique ornare non in enim.

Proin non lorem lorem, nec dictum elit. Sed lectus purus, convallis et convallis sed, ornare et quam. Suspendisse potenti. Praesent non sem felis, a laoreet ipsum. Maecenas consectetur, neque eget lacinia sollicitudin, neque augue ultricies nunc, sit amet sollicitudin metus metus non ipsum. Integer molestie tristique faucibus. Proin sed mi sed elit egestas vehicula. Nam ac nulla vitae magna facilisis porttitor vitae ac justo. Vivamus tincidunt quam ac neque elementum quis ultrices magna ornare. Suspendisse vitae sapien leo, quis porttitor libero. Sed leo nulla, euismod in ullamcorper at, suscipit sit amet lacus. Fusce aliquet, augue ut pellentesque dictum, orci ligula aliquam felis, sed bibendum nulla dui sed elit. Sed suscipit lorem nec arcu convallis tincidunt.

Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed dictum ipsum a purus mollis feugiat. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam iaculis sodales sapien vitae vestibulum. Cras sed elit quis diam viverra scelerisque. Proin non arcu non libero vehicula consectetur quis vel felis. Aliquam erat volutpat. Cras at vulputate tortor. Cras sagittis sodales leo sit amet tristique. Curabitur eu justo ac risus mattis fringilla nec vitae dolor. Mauris pharetra gravida leo, a dapibus odio aliquet eget. Vestibulum id orci neque, eu posuere neque. Mauris in varius leo. Pellentesque tempor interdum tempor. Maecenas aliquet, dolor sed venenatis vestibulum, nisl metus accumsan sapien, eu molestie dui nulla in ligula. Nam venenatis leo at nisl porttitor placerat placerat elit ultricies.

Donec ullamcorper, arcu eu pulvinar feugiat, elit velit tincidunt justo, sit amet porttitor leo tortor eu neque. In id odio eu mauris tristique sodales. Etiam erat erat, consequat a venenatis id, viverra eget nibh. Nam sollicitudin volutpat commodo. Nunc nulla arcu, commodo at interdum sit amet, tempor placerat ante. Nulla pellentesque, arcu non gravida rhoncus, tortor elit congue nibh, id tristique arcu enim ac turpis. Morbi vitae tellus lectus. Praesent ante odio, sagittis at interdum eu, dapibus vehicula metus. Mauris nisi nisi, pharetra ac hendrerit eu, luctus nec enim. Nam in dignissim orci. Vivamus lacinia, nisl in ornare imperdiet, nisi massa semper dui, in tristique sem neque et velit.

Vestibulum sodales placerat massa, sed iaculis purus mattis blandit. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sit amet tortor in purus congue dictum. Donec a bibendum libero. Fusce a dui ullamcorper est hendrerit imperdiet eget nec dui. Nunc in eros a orci sagittis rutrum in sed massa. Nam convallis nisl vel nisl fermentum porttitor dignissim tellus vehicula. Phasellus sed velit velit. Sed at nisl vel risus viverra commodo. Nullam orci sem, porta quis accumsan vel, pharetra et augue. Vestibulum ut orci ut purus bibendum fringilla. Integer pretium ultrices lectus, et accumsan metus tempor varius. Etiam sit amet iaculis eros.

A: CSS Position: Fixed;
Css can be a tricky beast, especially when you add IE into the mix.


text:
Q: Clicking on button is not adding inline style using draft.js I am trying to add a rich text editor using draft.js to a react project. I have been able to add it and also handle keyboard commands by following their docs. I have also added two buttons to do bold and italics but the problem is that when am clicking on the button the editor state doesn't change and no inline style is being added but if I select the text and click on the button the style is added to that text. I can't understand where am I doing wrong.
import React, { Component } from 'react';
import {Editor, EditorState, RichUtils} from 'draft-js';
import './App.css';

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {editorState: EditorState.createEmpty()};
        this.onChange = (editorState) => this.setState({editorState});
        this.handleKeyCommand = this.handleKeyCommand.bind(this);
    }

    handleKeyCommand(command, editorState) {
        const newState = RichUtils.handleKeyCommand(editorState, command);
        if (newState) {
            this.onChange(newState);
            return 'handled';
        }
        return 'not-handled';
    }

    _onBoldClick() {
        this.onChange(RichUtils.toggleInlineStyle(
            this.state.editorState, 'BOLD'));
    }

    _onItalicClick() {
        this.onChange(RichUtils.toggleInlineStyle(
            this.state.editorState, 'ITALIC'));
    }

    render() {
        return (

Text formatting using Draft.js

                    <button className="btn" onClick={this._onBoldClick.bind(this)}>B</button>
                    <button className="btn" onClick={this._onItalicClick.bind(this)}>I</button>

                    <Editor
                        editorState={this.state.editorState}
                        handleKeyCommand={this.handleKeyCommand}
                        onChange={this.onChange}
                        isCollapsed="true"
                    />

        );
    }
}

A: This happens because by default onClick causes Editor to lose focus. To resolve this, do the following:
  _onBoldClick (e) {
    e.preventDefault()
    this.onChange(RichUtils.toggleInlineStyle(
            this.state.editorState, 'BOLD'))
  }

  _onItalicClick (e) {
    e.preventDefault()
    this.onChange(RichUtils.toggleInlineStyle(
            this.state.editorState, 'ITALIC'))
  }

and change onClick to onMouseDown:
<button className='btn' onMouseDown={this._onBoldClick.bind(this)}>B</button>

<button className='btn' onMouseDown={this._onItalicClick.bind(this)}>I</button>

Additional Note
Always include Draft.css at the top:
import 'draft-js/dist/Draft.css'

From the documentation:

This CSS should be included when rendering the editor, as these styles set defaults for text alignment, spacing, and other important features. Without it, you may encounter issues with block positioning, alignment, and cursor behavior.

A: you can try like this in react 16 with hooks,
just pass e and it will work,
import React, { useEffect, useState } from 'react';
import ReactDOM from 'react-dom';
import {Editor, EditorState, RichUtils} from 'draft-js';
import 'draft-js/dist/Draft.css';
import './MyEditor.css'

export default function MyEditor() {

  const [editorState, setEditorState] = React.useState(
    () => EditorState.createEmpty(),
  );

  // tried with onclick (but not working as expected) so used mousedown event
  const _onBoldClick = () => {
    setEditorState(RichUtils.toggleInlineStyle(editorState, 'BOLD'))
  }
  const _onBoldMouseDown = (e) => {
    e.preventDefault();
    setEditorState(RichUtils.toggleInlineStyle(editorState, 'BOLD'))
  }

  const _onItalicMouseDown = (e) => {
    e.preventDefault();
    setEditorState(RichUtils.toggleInlineStyle(editorState, 'ITALIC'))
  }

  const _onUnderlineMouseDown = (e) => {
    e.preventDefault();
    setEditorState(RichUtils.toggleInlineStyle(editorState, 'UNDERLINE'))
  }

  return(

        <button onMouseDown={ e => { _onBoldMouseDown(e) } }>B</button>
        <button onMouseDown={ e => { _onItalicMouseDown(e) } }>I</button>
        <button onMouseDown={ e => { _onUnderlineMouseDown(e) } }>U</button>

          <Editor
            textAlignment="left" placeholder="Enter something here"
            editorState={editorState} onChange={setEditorState} />

  )

}

//ReactDOM.render(<MyEditor />, document.getElementById('container'));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Disable PyCharm auto whitespace format after refactoring Can someone once and for all point me to the way on how to disable PyCharm auto formatting for code refactoring? The examples like the following have wasted me big time as I have to refactor -> auto format -> manual format back... I tried to disable all options under Editor/General/Smart Keys, but with not luck...
Before refactoring:

After refactoring (change variable name a to x). Notice the removal/addition of white space before x/}:

But I expect to simply get this instead, and now I have to manually format it to like this:

A: Googled around and figured that there is NO way to turnoff this autoformat feature of PyCharm. Learning Sublime as IDE now.


text:
Q: How to map a servlet call from a JSP page using form action? I have a JSP page named Welcome_2.html and in its form action I have invoked a servlet like this :
<form action="/servlets/MyFirstServlet" method="post" id="form_id">

The servlet "MyFirstServlet" is under
     WEB-INF
     classes
     servlets
     MyFirstServlet
and the jsp is under the folder
     HTML
which is in the same level like WEB-INF
i.e. inside practice I have 3 folders
     HTML
     META-INF
     WEB-INF
in web.xml I have the following snippet
    <servlet>
    <servlet-name>MyFirstServlet</servlet-name>
    <servlet-class>servlets.MyFirstServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>MyFirstServlet</servlet-name>
    <url-pattern>/servlets/MyFirstServlet</url-pattern>
</servlet-mapping>

Why the servlet is not being invoked? I am clicking on the HTML page on my browser and trying to invoke the servlet ... I am just a beginner
pardon me for my poor intellect.

A: Change your jsp form to ,
<form action="/servlets/MyFirstServlet" method="post" id="form_id">

to match the url pattern in your web.xml
<servlet-mapping>
    <servlet-name>MyFirstServlet</servlet-name>
    <url-pattern>/servlets/MyFirstServlet</url-pattern>
</servlet-mapping>

This line <url-pattern>/servlets/MyFirstServlet</url-pattern> refers that url's matching the pattern will invoke the MyFirstServlet
Read the Oracle Tutorial before you configure your web.xml elements
Hope this helps !!

A: If you use tomcat 7 , you don't need to care about that. For example :
In your servlet :
@WebServlet("/myFirstServlet")

public class LoginPage extends HttpServlet {

   // your code

}

In your html :
<!-- here you write myFirstServlet in the action tag -->
<form id="somethingGoesHere" action="myFirstServlet" method="post" >

A: As your form action is "/servlets/First"
so your url pattern should be
<url-pattern>/servlets/First</url-pattern>

A: Unless your app is deployed as ROOT.war, all your URLs will be relative to http://myserver/webapp. So my guess is that you should rather use relative URLs. As your JSP is in HTML, you would need to write:
<form action="../servlets/MyFirstServlet" method="post" id="form_id">


text:
Q: Pywinauto ValueError I have several python scripts that run using pywinauto. Everything was going great until this morning where I now have this same error on all of them. Is this a pywinauto bug or have I made a mistake somewhere.
23:54:14   File "C:\jenkins_workspace\workspace\regression neo sl110\utilities\regression\Regression.py", line 141, in <module>
23:54:14     run_pgm(args.program, abspath_cfg, abspath_pgm, abspath_output, args.test)
23:54:14   File "C:\jenkins_workspace\workspace\regression neo sl110\utilities\regression\Regression.py", line 98, in run_pgm
23:54:14     result = Auto_Regression.pgm_manage(app, output)
23:54:14   File "C:\jenkins_workspace\workspace\regression neo sl110\utilities\regression\Auto_Regression.py", line 145, in pgm_manage
23:54:14     app.AquisitionError.OK.Click()
23:54:14   File "C:\Python27\lib\site-packages\pywinauto\application.py", line 229, in __getattr__
23:54:14     ctrls = _resolve_control(self.criteria)
23:54:14   File "C:\Python27\lib\site-packages\pywinauto\application.py", line 792, in _resolve_control
23:54:14     criteria)
23:54:14   File "C:\Python27\lib\site-packages\pywinauto\timings.py", line 339, in WaitUntilPasses
23:54:14     func_val = func(*args)
23:54:14   File "C:\Python27\lib\site-packages\pywinauto\application.py", line 558, in _get_ctrl
23:54:14     findwindows.find_window(**criteria[0]))
23:54:14   File "C:\Python27\lib\site-packages\pywinauto\findwindows.py", line 60, in find_window
23:54:14     windows = find_windows(**kwargs)
23:54:14   File "C:\Python27\lib\site-packages\pywinauto\findwindows.py", line 204, in find_windows
23:54:14     best_match, wrapped_wins)
23:54:14   File "C:\Python27\lib\site-packages\pywinauto\findbestmatch.py", line 457, in find_best_control_matches
23:54:14     name_control_map = build_unique_dict(controls)
23:54:14   File "C:\Python27\lib\site-packages\pywinauto\findbestmatch.py", line 435, in build_unique_dict
23:54:14     ctrl_names = get_control_names(ctrl, controls)
23:54:14   File "C:\Python27\lib\site-packages\pywinauto\findbestmatch.py", line 292, in get_control_names
23:54:14     non_text_names = GetNonTextControlName(control, allcontrols)
23:54:14   File "C:\Python27\lib\site-packages\pywinauto\findbestmatch.py", line 207, in GetNonTextControlName
23:54:14     if ctrl_.IsVisible() and ctrl_.WindowText() and ctrl_.can_be_label]
23:54:14   File "C:\Python27\lib\site-packages\pywinauto\controls\HwndWrapper.py", line 262, in WindowText
23:54:14     return handleprops.text(self)
23:54:14   File "C:\Python27\lib\site-packages\pywinauto\handleprops.py", line 58, in text
23:54:14     buffer_ = ctypes.create_unicode_buffer(length)
23:54:14   File "C:\Python27\lib\ctypes\__init__.py", line 310, in create_unicode_buffer
23:54:14     buftype = c_wchar * init
23:54:14 ValueError: Array length must be >= 0, not -1067052991

A: I am one of pywinauto's committers and ran into the same problem; I uploaded a new version (0.4.2) of pywinauto that should fix this problem to our home page.


text:
Q: Explanation of confidence interval from R function boot.ci I used boot function in R to do bootstrap for 40 times and used boot.ci to get the "normal" confidence interval. The following is my R code:
1. Define the statistic used in boot function

uni_boot <-function(data,indices,vari){
  d = data[indices,]
  unifit = coxph(as.formula(paste('Surv(time, status)~', vari))
                ,data = d)
  # return hazard ratio
  summary(unifit)$coef[2]
}

2.Bootstrap

r1 <- boot(data = data, statistic = uni_boot, R = 40,
        vari = variable)
r2 <- boot.ci(boot.out = r1, type = "norm")

Then, I examine the following things
Result of r1 object:

original     bias    std. error
t1* 1.053145 0.03274176   0.1714448

Result of r2 object

Intervals :
Level      Normal
95%   ( 0.684,  1.356 )
Calculations and Intervals on Original Scale

The bootstrap sample mean would be mean(r1$t) 1.085887 which is original plus the bias. However, when I examine the the formula used to calculate the bootstrap interval. It is original-bias-V^1/2*Z(1-alpha) or original-bias-V^1/2*Z(alpha).
I followed the formula and did the calculation:

1.053145-0.03274176+1.96*0.1714448 got me the upper bound 1.356
1.053145-0.03274176-1.96*0.1714448 got me the lower bound 0.684

My understanding of the confidence interval would be the bootstrap mean in the middle of the boot CI. However, the boot CI midpoint here turns to be 1.024. Sometimes, the boot CI from boot.ci wouldn't cover the bootstrap mean mean(r1$t).
Anything I understand wrongly?

A: Yes, the right way to correct for bias with bootstrapping is to subtract the bias from the value obtained on the original sample. When you get stuck thinking about bootstrapping, remember the guiding principle:

The population is to the sample as the sample is to the bootstrap samples.

Your value from the original sample is 1.053; you perform bootstrap resamples from the original sample and find a mean value of 1.086. The mean from the bootstrap samples was thus 0.033 higher than the value from the original sample: a bias of +0.033.
Applying the above principle, you use that bias value to estimate that the value from the original sample is 0.033 higher than the population value. So the bias-corrected estimate of the population value is 1.02.
The CI based on bootstrapping are supposed to represent the CI in the original population, while the values from the bootstrapped samples themselves are doubly biased from the population values (once from the original sample versus the population, and then again from the bootstrapped samples versus the original sample). With bias, you thus shouldn't be alarmed that the values obtained from the bootstrapped samples are beyond the final CI estimates for the population.
Issues of confidence intervals from bootstrapping can be even trickier; the "normal" confidence intervals assume symmetry about the (bias-corrected) mean, an assumption that might not best describe the situation in practice. With bias and asymmetry some other frequently used bootstrapping-based estimates of confidence intervals can be misleading. I struggled with these issues extensively until I forced myself to apply the above guiding principle systematically.


text:
Q: tfs problem. Cannot open solution file i have this project in TFS, and someone else from another computer changed the solution file's name. Now when i try to open it, i cant. It gives ne this error -
"This project (xxx.sln) cannot be opened from source control because it was created by a version of Microsoft Visual Studio that is incompatible with this one.
If this is the case, you may be able to open it from source control using that version of Microsoft Visual Studio, and then use Microsoft Visual Studio to open the local copy."
I dont have a local copy cause i deleted it. Reason being i wanted to get eveything new from the server. How can i open this project now?

A: Right-click on the project in Source Control explorer, choose 'get specific version'
In the dialog that opens, choose latest version' and check the box that says you want to overwrite the local file even if your workspace already has the latest version.
That way, you'll have the file you deleted on your local disk again.
If you still can't open it in visual studio, open the file in notepad and see if the version of the file matches up with your version of visual studio
That should look something like this:
Microsoft Visual Studio Solution File, Format Version 10.00

10.00 = VS2008
11.00 = VS2010
If it doesn't match your version of VS, it was opened in another version of VS and converted.

A: *

*Open Visual Studio

*Open Source Control Explorer (View -> Other Windows -> SOurce Control)

*Right click on the folder in Source Control where you solution is

*Start the Get latest command

You now have the latest version of you solution file and you can open it again


text:
Q: How to merge two worksheets entirely -- with varying spreadsheet names, format, and worksheet titles Alright so i'm working on making a "catch all" spreadsheet of sorts.
I work with customers who give us schedules, all in varying formats and appearances, but all in excel (.xlsx).
The goal is to be able to make an "excel tool" if you will, that with a click of a button i can navigate to the schedule i was given, and import it into the tool. Then from that tool, i can continue to use other VBA scripts (which i already have put together) to grab from other excel worksheets and therefore make the tool into a nicely put file with multiple sheets, including all of the customer information.
The problem i'm encountering is that i receive schedules from the customer with absolutely no consistency. They give the schedules random names, they sometimes don't use tables, and they rename the sheets all sorts of stuff. So far i've only been able to find a method to automate the merging of two spreadsheets, but it only works if the schedule has the same location, and names.
Any idea of any workaround on this?
Possibly a vba script that will open windows explorer, allow me to choose the excel sheet i need, and just import everything into the tool, all formatting and sheets regardless of the name(s) and quantity?

A: Alright, so i've got:
     Sub HC_import()
            Dim wb1 As Workbook, wb2 As Workbook, wb3 As Workbook
            Dim Ret1
            Dim Ret2

            Set wb1 = ActiveWorkbook

            On Error Resume Next

            '~~> Get the Health Check File
            Ret1 = Application.GetOpenFilename("Excel Files (*.xls*), *.xls*", _
            , "Please select the HC File")
            If Ret1 = False Then Exit Sub

            Set wb2 = Workbooks.Open(Ret1)

            '~~> Copy STNHC Data from Health Check File
        wb2.Activate
        Sheets("STNHC").Select
        ActiveSheet.ShowAllData
        ActiveSheet.ListObjects(1).Unlist
        Range("A1").Select
        Range(Selection, Selection.SpecialCells(xlLastCell)).Select
        Selection.Copy

            '~~> Paste STNHC Data to Tool
        wb1.Activate

            Sheets.Add After:=ActiveWorkbook.Sheets(1)
            ActiveSheet.Name = "HEALTH_CHECK"
            Sheets("HEALTH_CHECK").Select
            Range("A1").Select
            Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks _
                :=False, Transpose:=False
            Application.CutCopyMode = False

        '~~> Copy PatchETL Data to Tool
        wb2.Activate
        Sheets("PatchETL").Select
        ActiveSheet.ShowAllData
        Range("A:I").Select
        Selection.Copy
End Sub

This works well, assuming the sheet is always called "STNHC" -- i need something that works similary; but that will work regardless of what the sheets are called.

A: This is incredibly vague, however if I understand you correctly...  What if you take all of the excel files, put them in 1 folder, then write a simple vbs script to rename all files containing ".xls" in said folder to a consistent file name, then have the script go through the same files to rename all of the sheets to what you need i.e. "STNHC".  Then your files will be consistent to work with your existing tool?


text:
Q: Command line connect to wireless network does not work on ubuntu 10.04 My Dear All the Greatest Lords,
Some expert listed the details of connecting to a wireless network as,
This is a step-to-step guide for connecting to a WPA/WPA2 WiFi network via the Linux command line interface. The tools are:

wpa_supplicant
iw
ip
ping
iw is the basic tool for WiFi network-related tasks, such as finding the WiFi device name, and scanning access points. wpa_supplicant is the wireless tool for connecting to a WPA/WPA2 network. ip is used for enabling/disabling devices, and finding out general network interface information.

The steps for connecting to a WPA/WPA2 network are:

Find out the wireless device name.
$ /sbin/iw dev
phy#0
    Interface wlan0
        ifindex 3
        type managed
The above output showed that the system has 1 physical WiFi card, designated as phy#0. The device name is wlan0. The type specifies the operation mode of the wireless device. managed means the device is a WiFi station or client that connects to an access point.

Check that the wireless device is up.
$ ip link show wlan0
3: wlan0: (BROADCAST,MULTICAST) mtu 1500 qdisc noop state DOWN mode DEFAULT qlen 1000
    link/ether 74:e5:43:a1:ce:65 brd ff:ff:ff:ff:ff:ff
Look for the word "UP" inside the brackets in the first line of the output.

In the above example, wlan0 is not UP. Execute the following command to bring it up:

$ sudo ip link set wlan0 up
[sudo] password for peter:
Note: you need root privilege for the above operation.

If you run the show link command again, you can tell that wlan0 is now UP.

$ ip link show wlan0
3: wlan0: (NO-CARRIER,BROADCAST,MULTICAST,UP) mtu 1500 qdisc mq state DOWN mode DEFAULT qlen 1000
    link/ether 74:e5:43:a1:ce:65 brd ff:ff:ff:ff:ff:ff
Check the connection status.
$ /sbin/iw wlan0 link
Not connected.
The above output shows that you are not connected to any network.

Scan to find out what WiFi network(s) are detected
$ sudo /sbin/iw wlan0 scan
BSS 00:14:d1:9c:1f:c8 (on wlan0)
        ... sniped ...
    freq: 2412
    SSID: stanford
    RSN:     * Version: 1
         * Group cipher: CCMP
         * Pairwise ciphers: CCMP
         * Authentication suites: PSK
         * Capabilities: (0x0000)
        ... sniped ...
The 2 important pieces of information from the above are the SSID and the security protocol (WPA/WPA2 vs WEP). The SSID from the above example is stanford. The security protocol is RSN, also commonly referred to as WPA2. The security protocol is important because it determines what tool you use to connect to the network.

Connect to WPA/WPA2 WiFi network.
This is a 2 step process. First, you generate a configuration file for wpa_supplicant that contains the pre-shared key ("passphrase") for the WiFi network.

$ sudo -s
[sudo] password for peter:
$ wpa_passphrase stanford >> /etc/wpa_supplicant.conf
...type in the passphrase and hit enter...
wpa_passphrase takes the SSID as the single argument. You must type in     the passphrase for the WiFi network stanford after you run the command. Using that information, wpa_passphrase will output the necessary configuration statements to the standard output. Those statements are appended to the wpa_supplicant configuration file located at /etc/wpa_supplicant.conf.

Note: you need root privilege to write to /etc/wpa_supplicant.conf.

$ cat /etc/wpa_supplicant.conf
# reading passphrase from stdin
network={
    ssid="stanford"
    #psk="testtest"
    psk=4dfe1c985520d26a13e932bf0acb1d4580461dd854ed79ad1a88ec221a802061
}
The second step is to run wpa_supplicant with the new configuration file.

$ sudo wpa_supplicant -B -D wext -i wlan0 -c /etc/wpa_supplicant.conf
-B means run wpa_supplicant in the background.

-D specifies the wireless driver. wext is the generic driver.

-c specifies the path for the configuration file.

Use the iw command to verify that you are indeed connected to the SSID.

$ /sbin/iw wlan0 link
Connected to 00:14:d1:9c:1f:c8 (on wlan0)
    SSID: stanford
    freq: 2412
    RX: 63825 bytes (471 packets)
    TX: 1344 bytes (12 packets)
    signal: -27 dBm
    tx bitrate: 6.5 MBit/s MCS 0

    bss flags:  short-slot-time
    dtim period:    0
    beacon int: 100
Obtain IP address by DHCP
$ sudo dhclient wlan0
Use the ip command to verify the IP address assigned by DHCP. The IP address is 192.168.1.113 from below.

$ ip addr show wlan0
3: wlan0:  mtu 1500 qdisc mq state UP qlen 1000
    link/ether 74:e5:43:a1:ce:65 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.113/24 brd 192.168.1.255 scope global wlan0
    inet6 fe80::76e5:43ff:fea1:ce65/64 scope link
        valid_lft forever preferred_lft forever
Add default routing rule.
The last configuration step is to make sure that you have the proper routing rules.

$ ip route show
192.168.1.0/24 dev wlan0  proto kernel  scope link  src 192.168.1.113
The above routing table contains only 1 rule which redirects all traffic destined for the local subnet (192.168.1.x) to the wlan0 interface. You may want to add a default routing rule to pass all other traffic through wlan0 as well.

$ sudo ip route add default via 192.168.1.254 dev wlan0
$ ip route show
default via 192.168.1.254 dev wlan0
192.168.1.0/24 dev wlan0  proto kernel  scope link  src 192.168.1.113
ping external ip address to test connectivity
$ ping 8.8.8.8
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_req=1 ttl=48 time=135 ms
64 bytes from 8.8.8.8: icmp_req=2 ttl=48 time=135 ms
64 bytes from 8.8.8.8: icmp_req=3 ttl=48 time=134 ms
^C
--- 8.8.8.8 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2000ms
rtt min/avg/max/mdev = 134.575/134.972/135.241/0.414 ms
The above series of steps is a very verbose explanation of how to connect a WPA/WPA2 WiFi network. Some steps can be skipped as you connect to the same access point for a second time. For instance, you already know the WiFi device name, and the configuration file is already set up for the network. The process needs to be tailored according to your situation.

Thoroughly followed the above tutorial, I failed to connect the wireless router.
(working as root)
......
#wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant.conf -D wext
#iw wlan0 link
Not connected.

Even I disable the WPA authentication using,
iwconfig wlan0 essid XXXXXXXXXXXXX

of no avail.
But the GNOME wireless tray is functioning(can select, connect, disconnect etc.)
Thank you a lot in advance.

A: Latest wpa_supplicant is able to do all the job itself.
The wpa_supplicant option you wrote seem to me ok.
But please, check the options in the file "/etc/wpa_supplicant.conf", if it readable and is well written (ssid,wpa,password correct....)


text:
Q: EF Core Many to Many Join Table with Extra Properties Not Working I want to have this join table which has 2 foreign keys but also adds some other properties:
[Serializable]
public class GroceryItemGroceryStore
{
    [Key, Column(Order = 0), Required]
    public int GroceryItemId { get; set; }
    [Key, Column(Order = 1), Required]
    public int GroceryStoreId { get; set; }

    public virtual GroceryItem GroceryItem { get; set; }
    public virtual GroceryStore GroceryStore { get; set; }

    [Required]
    public int NotInEstablishmentCount { get; set; }
    [Required]
    public int InEstablishmentCount { get; set; }
    [Required]
    public double Price { get; set; }
}

Which joins these entities:
public class GroceryItem : VeganItem<GroceryItemTag, GroceryStore>
{
    public GroceryItem(string name, string brand, string description, string image)
    {
        this.Name = name;
        this.Brand = brand;
        this.Description = description;
        this.Image = image;
    }

    [Required]
    public string Name { get; set; }
    [Required]
    public string Brand { get; set; }
    [Required]
    public string Description { get; set; }
    public string Image { get; set; }
    public virtual ICollection<GroceryItemGroceryStore> GroceryItemGroceryStores { get; set; }
}

[Serializable]
public abstract class VeganItem<VeganItemTagType, EstablishmentType>
{
    public int Id { get; set; }
    [Required]
    public int IsNotVeganCount { get; set; }
    [Required]
    public int IsVeganCount { get; set; }
    [Required]
    public int RatingsCount { get; set; }
    [Required]
    public int Rating { get; set; }
    [Required]
    public List<VeganItemTagType> Tags { get; set; }
    //[Required]
    public List<EstablishmentType> Establishments { get; set; }
    [Required]
    public int CurrentRevisionId { get; set; }
}

and these entities:
[Serializable]
public class GroceryStore : Establishment<GroceryItem>
{
    public GroceryStore(string name, string placeId, string street, string suburb, string city, string streetNumber)
    {
        this.Name = name;
        this.PlaceId = placeId;
        this.Street = street;
        this.StreetNumber = streetNumber;
        this.City = city;
        this.Suburb = suburb;
    }
}

[Serializable]
public abstract class Establishment<VeganItemType>
{
    public int Id {get; set;}
    [Required]
    public string Name {get; set;}
    [Required]
    public string PlaceId {get; set;}
    [Required]
    public string Street {get; set;}
    public string Suburb {get; set;}
    public string City {get; set;}

    public List<VeganItemType> VeganItems {get; set;}
    public string StreetNumber {get; set;}
}

So I try to specify my join table as the table to use when defining my many-to-many relationship in my database context:

builder.Entity<GroceryItem>()
    .HasMany(p => p.Establishments)
    .WithMany(p => p.VeganItems)
    .UsingEntity(j => j.ToTable("GroceryItemGroceryStores"));

Something is not quite right because I get this error when I run dotnet ef migrations add InitialCreate:

Cannot use table 'GroceryItemGroceryStores' for entity type
'GroceryItemGroceryStore' since it is being used for entity type
'GroceryItemGroceryStore (Dictionary<string, object>)' and potentially
other entity types, but there is no linking relationship. Add a
foreign key to 'GroceryItemGroceryStore' on the primary key properties
and pointing to the primary key on another entity typed mapped to
'GroceryItemGroceryStores'.

Where am I going wrong?
EDIT - Problem with inserting data
The tables have all been created successfully. But, GroceryItemGroceryStores table and GroceryStores table do not get any insertions after inserting a GroceryItem which has an establishment on it.
Following is the payload being sent to add a GroceryItem which should also add a GroceryStore and GroceryItemGroceryStore:
{
    "name": "yummy fofod",
    "brand": "goodfoobdgffe",
    "description": "dfsad",
    "establishments": [{
        "name": "Macdonalds",
        "street": "Beach Rd",
        "placeId": "fsadfsdfsdfsdfsadfsadfsdf"
    }],
    "tags": [
        {
            "name": "sdf",
            "id": "9",
            "iconCodePoint": 23145
        }
    ]
}

And this is the controller that handles the above payload request:
[HttpPost]
public async Task<ActionResult<GroceryItem>> PostGroceryItem(GroceryItem groceryItem)
{
    _context.GroceryItems.Add(groceryItem);
    await _context.SaveChangesAsync();

    return CreatedAtAction("GetGroceryItem", new { id = groceryItem.Id }, groceryItem);
}

A: The presence of the following two properties -
public virtual GroceryItem GroceryItem { get; set; }
public virtual GroceryStore GroceryStore { get; set; }

in the GroceryItemGroceryStore model has already put GroceryItem and GroceryStore in a many-to-many relationship through the joining entity GroceryItemGroceryStore.
Then your relation configuring code is trying to create a new many-to-many relation between them, but trying to use the same joining entity. That's where the problem is, and that's exactly what the error message is saying.
Remove the configuration code, and it should work automatically.
If you want to configure the relationship manually, then change it to -
builder.Entity<GroceryItemGroceryStore>()
    .HasOne(p => p.GroceryItem)
    .WithMany(p => p.GroceryItemGroceryStores)
    .HasForeignKey(p=> p.GroceryItemId);

builder.Entity<GroceryItemGroceryStore>()
    .HasOne(p => p.GroceryStore)
    .WithMany()
    .HasForeignKey(p=> p.GroceryStoreId);

Or, even better would be adding the following property -
public virtual ICollection<GroceryItemGroceryStore> GroceryItemGroceryStores { get; set; }

to the GroceryStore model, and changing the config to -
builder.Entity<GroceryItemGroceryStore>()
    .HasOne(p => p.GroceryItem)
    .WithMany(p => p.GroceryItemGroceryStores)
    .HasForeignKey(p=> p.GroceryItemId);

builder.Entity<GroceryItemGroceryStore>()
    .HasOne(p => p.GroceryStore)
    .WithMany(p=> p.GroceryItemGroceryStores)
    .HasForeignKey(p=> p.GroceryStoreId);

EDIT:
You should remove the Establishments property from the VeganItem model and the VeganItems property from the Establishment model. Otherwise, they will create a separate many-to-many relationship through a separate joining table.
EDIT - For inserting data
Follow the steps below -

*

*Create a new GroceryStore (e.g. newStore) from your payload

*Insert it to the database

*Create a new GroceryItem (e.g. newItem) from the payload

*Do the following -

newItem.GroceryItemGroceryStores = new List<GroceryItemGroceryStore>
{
    new GroceryItemGroceryStore { GroceryStoreId = newStore.Id }
};

_context.GroceryItems.Add(newItem);
await _context.SaveChangesAsync();


text:
Q: PHP MWS Samples set up, returning a blank screen. I've successfully pulled reports with my authentication in scratchpad, set up the samples given by amazon "amazon-mws-v20090101-php-2015-06-18.V316922310" configured ".config.inc.php" and picked the correct endpoint within the given samples such as "GetReportListSample.php"  if I have an error or Mock() it will show feedback. But when I try to run it all that comes back is a blank page within my browser. Am i doing something wrong or is there another way to display the data received from this request?
Thanks.


text:
Q: Change PC local group members from Active Directory Domain Controller? Our environment is based on a Windows Server 2003, and more than a hundred computers in the domain.
These computers have the usual domain user in the local Administrator group of the respective computer.
Is there a way to remove them remotely, lets say, from the Domain Controller?
Also we need to remove them from another group which controls access to antivirus configuration, so we need to remove them from both.

A: Yes. When a computer is joined to a domain, it becomes possible to remotely manage it.
From a server, go to Start->Administrative Tools->Computer Management.
Click on the top left where it says Local Computer. Now right-click this, and select "Connect to remote computer"
Enter the computername from the computer you want to manage, and click OK. The screen will now load the info from the remote computer.
Here you can unvold Groups to change the local groups such as Administrators, etc.
Do note that even though changing the groups, the changes will only becoming effective after a restart.
You can also remotely manage the registry. Start Regedit, and from menu file, select connect to remote machine.

A: You can either do it with a script (assuming the computers firewall won't block it) or with a GPO (if they all are under the same OU or group).
You can use both options for other groups as well (would require some editing respectively, of course).


text:
Q: A good approach for saving Strapi logs into a log file? I am looking for a simple approach in order to store the logs from my Strapi app into a file rather than just receiving them in the console.
From documentations I couldn't find a good way to achieve that. Do you have any suggestion?

A: Well you can use any of the loggers of your choice like Winston, Simple Node Logger Etc. I've personally used Simple Node Logger.
So, firstly create a helpers folder in the root of your strapi project. Then create a logger.js file in it. Add the following code to the logger file.
// helpers/logger.js
const simpleLogger = require('simple-node-logger');

const logger = simpleLogger.createRollingFileLogger({
  logDirectory: 'logs/',
  fileNamePattern: 'strapi_log_<DATE>.log',
  dateFormat: 'YYYY.MM.DD',
});

module.exports = logger;

Next, create the /logs folder in the root of your project. Finally, require the logger in your controller or service file and log messages to the log files. Simple Node Logger will handle the process of rolling log files and log filenames on daily basis for you.
// api/restaurants/controller/index.js
const logger = require('../../../helpers/logger');

module.exports = {
  async someFindMethod(ctx){
    logger.info('Log information to log files');
    logger.error('Log error to log files');
    return 'Hello World!';
  }
}

Output
## logs/strapi_log_2021.10.14.log
11:14:36.048 INFO  Log information to log files
11:14:36.048 INFO  Log error to log files

Sidenote:
To avoid server restarts on changes in log file, you need to ignore the folder by adding watchIgnoreFiles: ['**/logs/**'] to your config/server.js file in Strapi v3 (Check here) or to you config/admin.js file if your on Strapi v4 (Check here).


text:
Q: Powershell remote backup monitoring issue I have put together a script to check around my servers on the Backup using get-wbsummary.
Some reason the session is not really working and I am loosing this, could someone give me a hint where did I go wrong?
Thank you in advance for all the comments, if you feel that there is a better solution please don't hesitate to share, I am here to learn too.
 $serverlist=@("bla","bla","bla")

$command={$lastback = get-wbsummary | Select-object -property lastsuccessfulbackup}

$lastdate=@()
foreach ($svrs in $serverlist) {
  $sess=Enter-PSSession -ComputerName $svrs
  Invoke-command -session $sess -ScriptBlock $command
  remove-pssession -session $sess

  $object=New-Object PSObject -Property @{
   Severname=$svrs;
   Lastbackup=$lastback
  }
 $lastdate+=$object
}

Error message is:
Invoke-Command: cannot validate argument on parameter 'Session' because it is null.
EDIT:
With some help - thank you @Eris - please find the working code below for others to look at it:
 $serverlist=@("bla","bla","bla")

$command={get-wbsummary | Select-object -property lastsuccessfulbackuptime, currentoperationstatus}
$lastdate=@()

foreach ($svrs in $serverlist) {
  $sess=New-PSSession -ComputerName $svrs

  $lastback=Invoke-command -session $sess -ScriptBlock $command
 remove-pssession -session $sess
  $object=New-Object PSObject -Property @{
   Severname=$svrs;
   Lastbackup=$lastback.lastsuccessfulbackuptime;
   Progress=$lastback.currentoperationstatus;
  }
 $lastdate+=$object
}
$lastdate


text:
Q: linkBuilder React native Не верно показывает всплывающюю ссылку внизу экрана.
Неправильная ссылка:
Правильная ссылка:

Использую ReactNavigation, а так же использую useLinkBuilder, заполняю параметры useLinkBuilder name и params, и записываю эту созданную ссылку внутрь проперти to у компоненты Link. Также прописан linking, вот так он выглядит:. Неправильно показывает ссылку скорее всего из за того, что внутри Basket нет screen Products, но если я указываю ему такой screen и обязательно с ключем exact: true, выдадет ошибку Found conflicting screens with the same pattern.
Буду рад любой помощи!


text:
Q: Counting up recursively and using +1 vs ++ I have a basic question about recursion and how the difference of +1 and ++ affects the result.
Why is it that this code:
var arrayLoop = function(idx){
  if(idx < 5){
    console.log(idx);
     return arrayLoop(idx+1);
   }
};
arrayLoop(0);

will work just fine, but this:
var arrayLoop = function(idx){
  if(idx < 5){
    console.log(idx);
    return arrayLoop(idx++);
  }
};
arrayLoop(0);

results in an infinite loop?

A: i++ is an expression that increments 'i' but returns the value before the increment. You can use ++i to achieve your desired result.

A: In the second example you have used ++ operator as post-increment, so you are using idx++ and not ++idx.
What happens is that with post-increment the expression is evaluated with the value before the increment, then it is increment. You can see it like sort of (mind that's not semantically identical, it's just to give you the idea):
return arrayLoop(idx);
idx = idx + 1;

So you can see that method is always invoked with 0 as argument.
The pre-increment ++idx operator would invert the operations:
idx = idx + 1;
return arrayLoop(idx);


text:
Q: Why isn't WM_NCACTIVATE message sent to a Window with its SizeToContent set to Height I've written a WndProc to know if current Window is flashing. It is as follows:
    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        var retVal = IntPtr.Zero;

        switch (msg)
        {
            case (int)WindowsMessages.NCACTIVATE:
                retVal = WindowsNative.DefWindowProc(hwnd, WindowsMessages.NCACTIVATE, new IntPtr(1), new IntPtr(-1));
                IsFlashing = (int)wParam == 0;
                break;
        }

        return retVal;
    }

Now this is working perfectly with any Window except for when their SizeToContent property is set to Height (I haven't tested WidthAndHeight but I assume it won't work either); in which case, the WM_NCACTIVATE message is not sent to the Window at all. All of my windows are using custom look and feel (using WPF WindowChrome). Do you possibly know the reason or can help me with this problem?

A: In theory, WM_NCACTIVTE message events are not blocked for no reason.
If you can, I suggest you redefine WM_NCACTIVATE.
like this:
    private const uint WM_NCACTIVATE = 0x0086;

    private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
    {
        var retVal = IntPtr.Zero;

        switch (msg)
        {
            case (int)WindowsMessages.NCACTIVATE:
            retVal = WindowsNative.DefWindowProc(hwnd, WindowsMessages.NCACTIVATE, new IntPtr(1), new IntPtr(-1));
            IsFlashing = (int)wParam == 0;
            break;
        }

    return retVal;
    }

Hope to help you.


text:
Q: How to change order of elements in a dijit.form.Select I'm using Dojo 1.5 to create a dijit.form.Select with some data from a datastore. The issue I'm finding is that I want the select to show the elements ordered by the identifier, but the select is ginving them ordered by the label. How can I avoid this behaviour?. Another issue I'm finding is that when I set the store, I initialized the store to select one of the elements, but it is selecting the first one. The code is a follows:
dojo.require("dijit.form.Select");
dojo.require('dojo.data.ItemFileReadStore');

dojo.addOnLoad(function(){

var boxContent = {"identifier":"idBox","items":[{"accessLevel":"FULL_ACCESS",
"boxName":"My Documents","boxType":"PERSONAL","idBox":1512,"numberFiles":9,
"userDisplayName":"Jose Luis Martinez Avial","userName":"MIAMARA"},
{"accessLevel":"FULL_ACCESS","boxName":"12312312","boxType":"PERSONAL",
"idBox":17100,"numberFiles":0,"userDisplayName":"Jose Luis MartinezAvial",
"userName":"MIAMARA"}],"label":"boxName"};

var myStore = new dojo.data.ItemFileReadStore({data: boxContent });

var   boxCombo= new dijit.form.Select({
    name: 'select2' }).placeAt(dojo.body());
   boxCombo.setStore(myStore,1512);

})

It is available in http://jsfiddle.net/m9ucX/1/
Thanks for your help.

A: Just in case anyone comes looking, this question was also asked (and has been answered) on the dojo-interest mailing list:

I think you'll get what you want if you just set sortByLabel: false on
  your Select.

Source:
http://mail.dojotoolkit.org/pipermail/dojo-interest/2011-February/052328.html


text:
Q: Accounting for non-linear trend in SOME samples of a linear mixed model using quadratic I have the following data: Pine Forest Biomass ~ Age | Plot:

 Each black curve represents whole-plot biomass for each individual plot
I want to formally examine this trend using mixed effects model (using lme4 function in R).
Thus far, I created a mixed model with random intercepts and slopes:
lme4(Biomass ~ I(Age - 51) + (1 + I(Age - 51) | Plot), data = dat, REML = F)

I added additional predictors to the model to better explain some of the trend:
lmer(Biomass ~ I(Age - 51) * LossRate + I(Age - 51) * I(scale(PineStems)) + (1 + I(Age - 51)|Plot),data = dat, REML = F)

*

*where LossRate is biomass lost per year due to mortality and PineStems are the number of pine stems in a given plot in a given year.

This model seems to perform just fine (based on significant 95% bootstrapped CIs for coefficient estimates and for CIs for the whole model). However, it doesn't account for the downward curve you can see in some plots.
I was thinking I could account for this curve by incorporating a quadratic term for age (i.e., I(scale((Age - 51)^2))  [we'll call it "Age^2"]
However, I'm not sure the best way to do this....
I'm pretty sure that I need to add a random effect for Age^2 since only some plots have the curve, but do I also need to add Age^2 as a fixed effect?

*

*Adding it as both a fixed and random effect improves the AIC of the model a lot (vs. no Age^2 term), but adding just the random Age^2 (without Age^2 as a fixed effect) improves the model even more.

*In general, does adding a squared "time" predictor as a random effect but not adding it as a fixed effect make sense??  (read: "Can I do that??")
Further, I expect the largest impact of PineStems on the model as being the main driver causing the downward slope in biomass in mature plots. In other words, I mostly expect PineStems to drive the Age^2 term (so that as PineStems decreases to a certain point, the trend line turns downward). How can I additionally add that to my model? Just simply by creating an interaction (Age^2 * PineStems)? Or does the model make this connection on its own?


text:
Q: C# boolean Value always returns false yet it is true in the database I have the followin Code in Model class which has a data type
'bool'
public class MiscellaneousSettings
    {
        public string Name { get; set; }
        public string Account_No { get; set; }
        public bool Percantage { get; set; }

        public decimal default_amount { get; set; }
        public string type { get; set; }

    }

Then the code for controller where I get the data which I will display in view I am using dapper ORM to fetch and send the data to the database
and consume the sp
[Authorize]
        public ActionResult Index()
        {
            try
            {
                using (sqlConnection)
                {

                    var list_charge = sqlConnection.Query<MiscellaneousSettings>("get_miscellaneous_charges",
                        new {  }, commandType: CommandType.StoredProcedure).ToList();

                    return View(list_charge);

                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

Then the code for index View which shows 'No' for the boolean value while in the Database it shows the true value.
@foreach (var item in Model)
            {

                        @Html.DisplayFor(modelItem => item.Name)

                        @Html.DisplayFor(modelItem => item.Account_No)

                        @Html.YesNo(item.Percantage)

                        @Html.DisplayFor(modelItem => item.default_amount)

                        @Html.DisplayFor(modelItem => item.type)

                        @Html.ActionLink("Edit", "Edit", new {id=item.type}) |
                        @Html.ActionLink("Delete", "#", new { /* id=item.PrimaryKey */ })

            }

I used the htm helper extenseion for decorating booolean
values in the view to read Yes or No
instead of checkboxes
 public static class HtmlHelperExtension
    {
        public static MvcHtmlString YesNo(this HtmlHelper htmlHelper, bool yesNo)
        {
            var text = yesNo ? "Yes" : "No";
            return new MvcHtmlString(text);
        }
    }


text:
Q: Algorithm to test isomorphism between two finitely presented modules Given two finitely presented left (or right) $R$-modules, specified by free presentations, is there an algorithm to determine if they are isomorphic and produce an isomorphism? This is of course possible if $R$ is a PID (or more generally an elementary divisor ring) via the Smith normal form. But how about other types of rings? For example, how about $R = K[x_1, \ldots, x_n]$ for a field $K$?
I saw that Macaulay2 checks if a randomly generated homomorphism between the modules is an isomorphism, and in affirmative case this solves the problem. But in my tests over several rings a random homomorphism is almost never an isomorphism (it is over $\mathbb{Q}$, but not over general rings, not even over $\mathbb{Z}$). So I don't understand what they are doing in Macaulay2.


text:
Q: Is it possible to use speech recognition in a SpriteKit app using swift? I am using SpriteKit to build an app.  The other functionality of the Scene is all done through SpriteKit.  I want to add speech recognition to the scene so that when the user touches the microphone button node, the words they say are matched against the correct word they needed to say to move on.  Is this possible on SpriteKit?  The code below is the function I am using but it is not causing anything to happen.
func recordAndRecognizeSpeech() {
    let node = audioEngine.inputNode
    let recordingFormat = node.outputFormat(forBus: 0)
    node.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { buffer, _ in
        self.request.append(buffer)
    }
    audioEngine.prepare()
    do {
        try audioEngine.start()
    } catch {
        self.sendAlert(message: "There has been an audio engine error.")
        return print(error)
    }
    guard let myRecognizer = SFSpeechRecognizer() else {
        self.sendAlert(message: "Speech recognition is not supported for your current locale.")
        return
    }
    if !myRecognizer.isAvailable {
        self.sendAlert(message: "Speech recognition is not currently available. Check back at a later time.")
        // Recognizer is not available right now
        return
    }
    recognitionTask = speechRecognizer?.recognitionTask(with: request, resultHandler: { result, error in
        if let result = result {

            let bestString = result.bestTranscription.formattedString
            self.labelNode.text = bestString

            var lastString: String = ""
            for segment in result.bestTranscription.segments {
                let indexTo = bestString.index(bestString.startIndex, offsetBy: segment.substringRange.location)
                lastString = bestString.substring(from: indexTo)
            }
            self.checkPhrase(resultString: lastString)
        } else if let error = error {
            self.sendAlert(message: "There has been a speech recognition error.")
            print(error)
        }
    })
}

Below is the code I am using for when the mic node gets touched and nothing happens when I run it:
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let touch = touches.first else { return }
    let location = touch.location(in: self)

    if micButton.contains(location) {
        if isRecording == true {
            audioEngine.stop()
            recognitionTask?.cancel()
            isRecording = false
        } else {
            self.recordAndRecognizeSpeech()
            isRecording = true
        }

    }

A: You can use the instance method requestRecordPermission(_:) to request the user's permission for audio recording.
Try something like:
if (session.respondsToSelector("requestRecordPermission:")){
    AVAudioSession.sharedInstance().requestRecordPermission({(granted: Bool)-> Void in
        if granted {
            println("granted")
            session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
            session.setActive(true, error: nil)
            self.recorder ()
        }else{
            println("not granted")
        }
    })
}   session.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
        session.setActive(true, error: nil)
            self.recorder ()
        } else{
            println("not granted")
        }
     })
}


text:
Q: How can I find out the width of an image that hasn't been styled in JavaScript (in IE)? Imagine you have the following
    img = document.createElement("img");
    img.src = "MahImage.jpg";
    x.appendChild(img);

What can I do to find out the Width and Height of the image without using jQuery?
I am currently using .width , which works fine for any intelligent browser, but I have to find out a way to make IE happy

A: After image load's you can access to properties width and height.
For example:
alert(img.height + img.width);

Also you can get image dimensions using properties clientHeight and clienWidth
To know if image loaded use onload hanler.
For example
img = document.createElement("img");
img.src = "MahImage.jpg";
img.onload = imageproperties;
x.appendChild(img);

function imageproperties() {
    alert(img.height + img.width);
}

A: You can access the width and height properties of the image, but they will only return a useful value once the image has loaded; so you'll only want to access them inside the onload event of the image (or give it a reasonable time to load).
img = document.createElement("img");
img.onload = function () {
    this.height;
    this.width;
};
img.src = "MahImage.jpg";
x.appendChild(img);

You can see this working here: http://jsfiddle.net/aS7a7/

A: This is tricky because you cant find the height/width of an image until after it is done loading.  This means you'll need a callback attached to the load of the image:
var img = document.createElement("img");
img.src = "MahImage.jpg";
img.onload = imageReady;
x.appendChild(img);

var imageReady = function() {
  alert(img.height);
  alert(img.width);
}

A: You need to wait until the image will be loaded. Here is the code (tested in Chrome):
img = document.createElement("img");
img.src = "http://google.ru/logos/2011/Albert_Szent_Gyorgyi-2011-hp.jpg";
img.onload = function(){
    console.log(img.width, img.height);
}
document.getElementsByTagName('body')[0].appendChild(img);


text:
Q: Juju bootstrap failed in running machine configuration I am deploying the MAAS and JUJU as well as OpenStack. At present, I have installed MAAS(2.5), added all nodes and commissioned them by following the guide. However, when I install the JUJU via conjure-up, everything went great until juju bootstrap. Actually, the conjure-up can set the status of juju controller to deploying 18.04...
In MAAS dashboard as well as starting deploy the OS to JUJU controller node. After deployment finishing, the JUJU still tills me "Awaiting.." and are running machine configuration scripts.
log output:
Creating Juju controller "conjure-up-cloud-maas-ff8-357" on cloud-maas-ff8
Looking for packaged Juju agent version 2.5.0 for amd64
Launching controller instance(s) on cloud-maas-ff8...
- cxh7md (arch=amd64 mem=8G cores=4)
Installing Juju agent on bootstrap instance
Fetching Juju GUI 2.14.0
Waiting for address
Attempting to connect to 192.168.2.1:22
Connected to 192.168.2.1
Running machine configuration script...

A: Sorry to hear that you're having difficulty, Kevin. The error message from Juju isn't very helpful:

Running machine configuration script...

This means that the machine is installing its software via cloud-init. At this stage, there is no output for Juju to interpret.
To learn more about how to fix the situation, you need to access the machine directly. That means using SSH to log in to the machine and monitoring the cloud-init output yourself.
ssh cloud-maas-ff8 # you may need to
cd /var/log
less cloud-init-output.log

That will present you with a large log file that starts something like this:
Cloud-init v. 18.4-0ubuntu1~18.04.1 running 'init-local' at Sun, 19 May 2019 08:11:30 +0000. Up 1.00 seconds.
Cloud-init v. 18.4-0ubuntu1~18.04.1 running 'init' at Sun, 19 May 2019 08:11:33 +0000. Up 4.00 seconds.
...

If your work policies permit it, you should paste your output to paste.ubuntu.com for further help.


text:
Q: Smallest Perfect Cube ending in 888 Find the Smallest Perfect cube ending in 888
My Try: First of all its cube root should have Last digit as $2$.
Now if $x888$ is a Perfect Cube Then $$x888=888+1000x=8(111+125x)$$ which means $111+125x$ should be a Perfect cube.
Need a small Hint to Proceed Further

A: You've already figured out the ones digit of the root is $2$.
So, the number $(10x + 2)^3 = 1000x^3 + 600x^2 + 120x + 8$ ends with $...888$.
This number modulo $10$ is obviously $8$. So, you remove the $8$ and divide by $10$. Now you got $100x^3 + 60x^2 + 12x$. This number has to end in $...88$.
Now, $100x^3 + 60x^2 + 12x \equiv 12x \,\, (\textrm{mod}\ 10)$
So, $12x$ has to end in an $8$ and thus, $x$ either ends in $4$ or $9$. So, now we've narrowed down possibilities to $x = 4, 9, 14, 19, 24 ...$ If you check these numbers, you find that $x = 19$ is the answer.
Thus, the smallest perfect cube to end in 888 is 192. (Remember the root is $10x + 2$)

EDIT: If you want to do a bit more work, you can figure out the following:
$60x^2$ will always end in $...60$ for $x$ that ends in $4$ or $9$. (If it isn't immediately obvious, work at it a bit more).
Which means that, $12x$ must end in $...28$ to get the desired $...88$ - this narrows down to ALL numbers whose cubes end in $...888$, which are $19,44,69,94$.
Here, an interesting pattern emerges.
All numbers of the form $250x + 192$ (where $x$ is a non-negative integer) are roots of perfect cubes ending in $...888$.

A: From where you left it:
$$a^3\equiv 111\equiv -14\pmod{125}$$
This implies:
$$a^3\equiv 11\pmod{25}$$
You have $4^3\equiv14\equiv-11\pmod{25}$, so $a\equiv -4\equiv 21\pmod{25}$.
Trying possible values of $a$ (21,46,71,96,141) with a calculator, you can find $96^3\equiv 111\pmod{125}$ and $192^3=7077888$.

A: I would continue digit by digit. You know that the ones digit of the root is 2.
Now try all possible tens digits and find out which one(s) yield the a cube whose last two digits are 88.
For each of your solutions, then, try all possible hundreds digits.
Now you have all three-digit numbers whose cube is 888 modulo 1000. Take the smallest of those and cube it.


text:
Q: Using _url Absolute Links with ActionController full page caching We have a rails 3 application (3.2.12) on which we wish to implement full page caching (Using ActionController caches_page)
We are using _url url helpers everywhere in the application, and this is causing the links in all of the cached pages (in production) to have the domain: http://0.0.0.0/
We have canonical links on several pages that require the domain in the links, so we can't easily switch to _path url helpers.
I've scoured Google and StackOverflow and can't find an answer for this.
I'm not passing in any options to caches_page
The pages are essentially like so:
class SomeController < ApplicationController
  caches_page :index, :other_action

  def index
  end

  def other_action
  end
end

How do I make the links in the generated cache pages have the correct domain?

A: Perhaps you are caching the pages locally (with them written to the "public" directory), and then deploying everything including the "public" directory to the production site, causing the development pages to be served from production.


text:
Q: Defining an abbreviation for `align` To save myself some keystrokes, I tried to define an abbreviation for \begin{align} and \end{align}
\documentclass[reqno, 11pt]{article}

\usepackage{amsmath, amsfonts, mathtools, amsthm}
\usepackage{fullpage}

\newcommand{\ba}{\begin{align*}}
\newcommand{\ea}{\end{align*}}

\title{Article Template}
\author{You}

\begin{document}
\maketitle

\section*{3}
\ba
e=mc^2
\ea
\end{document}

For some reason, the abbreviation for \begin{align} seems to work, but the abbreviation for \end{align} does not. I thought perhaps that \ea was already in use, but tweaking the name didn't change anything. Any ideas?


text:
Q: Egopay payment gateway api callback url not getting response I am getting this message "This param is required - 'product_id'" in callback success url.
<?php
require('EgoPaySci.php');
try {
    $oEgopay = new EgoPaySci(array(
        'store_id'          => 'STORE ID',
        'store_password'    => 'STORE PASSWORD'
    ));
    $sPaymentHash = $oEgopay->createHash(array(
        'amount'    => '3.00',
        'currency'  => 'USD',
        'description' => 'My payment',
        'cf_1' => 'My custom data'
    ));
} catch (EgoPayException $e) {
    die($e->getMessage());
}
?>
<form action="<?php echo EgoPaySci::EGOPAY_PAYMENT_URL; ?>" method="post">
    <input type="hidden" name="hash" value="<?php echo $sPaymentHash ?>" />
    <input type="submit" value="Confirm Payment" />
</form>

For detail please check this https://www.egopay.com/developers.html
Thanks


text:
Q: how to fetch specific collection from mongodb in django I have clouded the mongodb collection for my project in Amazon server.
I am new to mongodb queries. When I connect and look in 'robomongo' tool, I can see that there two databases A and B. I want to access the one collection named 'wl_c' under B in view function in django and convert to JSON data.
I do not know how to do even though I tried,
from pymongo import Connection
server = '000.00.000.00'
port = 00000
conn = Connection(server,port)

def mongo(request):
  mdb = conn.events.polls_post.find({})
  data = json.dumps(mdb)
  return HttpResponse(data, mimetype="application/json")

got
Type error mdb is not json serializable

A: find({}) returns cursor. You need to get the items. Either cast to list or iterate over the result.
Something like:
mdb = conn.events.polls_post.find({})
mdb_list = list(mdb)
json.dumps(mdb_list)

Look here


text:
Q: How To Sign WCF Message With Certificate Using HTTPS Transport with Client Certificate EDIT:
I finally determined that IClientMessageInspector does not seem to reflect message signing so when I was actually getting a signature in my request I didn't know it.  So now for my new, real question...
How can I configure a WCF client to present both the SSL client cert and sign the SOAP Header?
var myBinding = new BasicHttpBinding();
myBinding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
myBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;

This will result in the header having a timestamp that's signed.  However, the client cert is no longer presented and I don't get past SSL.  If I change the second line to:
myBinding.Security.Mode = BasicHttpSecurityMode.Transport;

Then I get past SSL but my SOAP header no longer has the signing block.
Is there any way I can get ahold of HttpWebRequest so that I can manually attach the SSL Client cert like so?
webRequest.ClientCertificates.Add(certLoader.Load(@"c:\somecert.pfx"));

Original Question
I am working on a WCF client that needs to interop with a service provided by a third party that's using a Forum Sentry network appliance to secure access.  They require SSL with a client cert at the transport level as well as an o:Security element with signature using an cert in the header.  I'm able to achieve one or othe other with standard bindings, but I can't seem to get both to happen simultaneosly.  Ideally, they want the message signed with a different cert from the SSL client cert but they said we could use the same cert for both the SSL client authentication and to sign the message.
I'm willing to do anything at this point to get this working including using a CustomBinding if necessary.
I can get the SSL part working using the following:
var myBinding = new BasicHttpBinding();
myBinding.Security.Mode = BasicHttpSecurityMode.Transport;
myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
var url = "https://blah.com/services/somservice";
EndpointAddress ea = new EndpointAddress(url);
var client = new SoapClient(myBinding, ea);
var certLoader = new CertificateLoader("password");
client.ClientCredentials.ClientCertificate.Certificate = certLoader.Load(@"c:\somecert.pfx");
var resp = client.somemethod(ref profile, new RequestType { version = RequestTypeVersion.Item100 });

A: please publish a sample working soap (e.g. one the vendor provided). btw there are much more drastic moves than using a custom binding :)
Edit: to use both transport and message security you need custom binding. Google for "wcf binding converter" to do this automatically. In the custom binding instead of http element change it to https and use attribute requirevlientcertificate. Sorry for spelling I'm on mobile
EDIT:
var c = new CustomBinding();
MessageSecurityVersion version = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
var sec = SecurityBindingElement.CreateCertificateOverTransportBindingElement(version);
c.Elements.Add(sec);
c.Element.Add(new TextMessageEncodingBindingElement() { MessageVersion = MessageVersion.Soap11 };)
c.Elements.Add(new HttpsTransportBindingElement() { RequireClientCertificate = true });

A: This is ugly but gets the job done.  If you look at the elements of each of these custom bindings in the debugger, you'll see that even though both have an HttpsTransportBindingElement at the bottom of their stack, the TransportWithMessageCredential instance will have RequireClientCertificate set to false and a couple of other private memebers relating to the certificate set to false.  The Transport instance will have these members set to true.  This is clearly bug in WCF, IMO.
The code below takes the "good" HttpsTransportBindingElement from the customTransportSecurityBinding and replaces the "bad" one in the customMessageCredentialBinding.  You then pass the modified customMessageCredentialBinding into your client constructor.
    var transportSecurityBinding = new BasicHttpBinding();
    transportSecurityBinding.Security.Mode = BasicHttpSecurityMode.Transport;
    transportSecurityBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
    transportSecurityBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
    var customTransportSecurityBinding = new CustomBinding(transportSecurityBinding);

    var messageCredentialBinding = new BasicHttpBinding();
    messageCredentialBinding.Security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential;
    messageCredentialBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;
    messageCredentialBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;
    var customMessageCredentialBinding = new CustomBinding(messageCredentialBinding);

    // replace transport binding element from message credential binding with the transportSecurityBinding transport binding
    // which will include the cert for SSL mutual auth.
    customTransportSecurityBinding.Elements[customTransportSecurityBinding.Elements.Count - 1] = customMessageCredentialBinding.Elements[customMessageCredentialBinding.Elements.Count - 1];

var client = new SomeSoapClient(customTransportSecurityBinding, ea);

A: In case if anyone looking for app.config version of custom binding for the above answer:
<bindings>
      <customBinding>
        <binding name="SignedMessageBinding">
          <security messageSecurityVersion="WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10" />
          <textMessageEncoding messageVersion="Soap11" />
          <httpsTransport requireClientCertificate="true"  />
        </binding>
      </customBinding>
</bindings>


text: Q: ($\binom{n+m}{n} \% p$). Where, $p$ is prime and $n, m, p$ are very large? $1 \le n,m \le 10^9$ and $p = 10^9 + 7$. This can be simply solved using factorials but it will take a lot of time. Lucas theorem is also inappropriate as $p$ is very large. Can this be approached in a more efficient way ?


text:
Q: Why can't i call Contains method from my array? Arrrg!I am running into what i feel is a dumb issue with a simple script i'm writing in powershell. I am invoking a sql command that is calling a stored proc, with the results i put it a array. The results look something like this:
Status                                       ProcessStartTime                            ProcessEndTime
------                                       ----------------                            --------------
Expired                                      May 22 2010  8:31PM                         May 22 2010  8:32PM

What i'm trying to do is if($s.Contains("Expired")) , report failed. Simple...? :( Problem i'm running into is it looks like Contains method is not being loaded as i get an error like this:
Method invocation failed because [System.Object[]] doesn't contain a method named 'Contains'. At line:1 char:12
+ $s.Contains <<<< ("Expired")
    + CategoryInfo          : InvalidOperation: (Contains:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound
So, what can i do to stop powershell from unrolling it to string? Actual ps script below -
$s = @(Invoke-Sqlcmd -Query "USE DB
       GO
       exec Monitor_TEST_ps 'EXPORT_RUN',NULL,20" `
       -ServerInstance testdb002\testdb_002
      )

if ($s.Contains("Expired"))
{
    Write-Host "Expired found, FAIL."
}
else
{
    Write-Host "Not found, OK."
}

A: Simply put, $s is a .NET array (you're use of @() ensures that) and you're attempting to invoke a method (Contains) which doesn't exist on this .NET type.
The simplest way to resolve your problem is to use the PowerShell's -contains operator which has the benefits of working against arrays directly and doing case-insenstive compares e.g.:
if ($s -contains 'expired') { ... }

A: The reason you see the method is Get-Members is powershell is trying to be helpful and unrolling the collection. If you have an array with multiple types of items, it shows you the members for each type (like if you 'ls' (Get-ChildItem) and there are FileInfos and DirectoryInfos in the directory you are in, and you pipe ls | gm, it will show you members of FileInfos and also another group of members of DirectoryInfos):
(7) C:\ -» ls

    Directory: C:\

Mode                LastWriteTime     Length Name
----                -------------     ------ ----
d----         5/28/2010   8:19 AM            .hg
d----         5/13/2010   3:37 PM            Build
…
-a---         4/22/2010  11:21 AM       2603 TODO.org

(8) C:\ -» ls | gm

   TypeName: System.IO.DirectoryInfo

Name                      MemberType     Definition
----                      ----------     ----------
Mode                      CodeProperty   System.String Mode{get=Mode;}
Create                    Method         System.Void Create(System.Security.AccessControl.Direct...
…

   TypeName: System.IO.FileInfo

Name                      MemberType     Definition
----                      ----------     ----------
Mode                      CodeProperty   System.String Mode{get=Mode;}
AppendText                Method         System.IO.StreamWriter AppendText()
…

What I usually do, to make sure I am not looking at unrolled members, is try "$s.GetType().Name" first to see what I am dealing with. In your case, it's clearly and array, since you initialized it like "$s = @(Invo" (the @ = it's an array.)
To find out if an array contains an item, you can use the -contains operator:
(9) C:\ -» @(1,2,3) -contains 1
True

I think you've got an array of strings, so you can use a string literal, like:
(10) C:\ -» @("Stuff","you've","got","might have","Expired") -contains "Expired"
True

But if the expired isn't an exact match (you were looking for an element that contains expired, like "Connection Expired 1/1/2010") you need to find matches and check the count, I think:
(23) C:\ -» @("Stuff","you've","got","might have","Connection Expired 1/1/2010") -contains "Expired"
False
(24) C:\ -» @("Stuff","you've","got","might have","Connection Expired 1/1/2010") | ?{$_.Contains("Expired")}
Connection Expired 1/1/2010
(33) C:\ -» $xs = @("Stuff","you've","got","might have","Connection Expired 1/1/2010") | ?{$_.Contains("Expired")}
(34) C:\ -» $xs.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     String                                   System.Object

(35) C:\ -» $xs
Connection Expired 1/1/2010

In this case, there is only one match, so powershell unrolled it to a string. Jerk. If there are more than 1 matches, however:
(36) C:\ -» $xs = @("Stuff","you've","got","might Expired  have","Connection Expired 1/1/2010") | ?{$_.Contains("Expired")}
(37) C:\ -» $xs.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

(38) C:\ -» $xs
might Expired  have
Connection Expired 1/1/2010

Now it's an array.
Luckily, both string and array have a length property:
(39) C:\ -» $xs.Length
2
(40) C:\ -» "Bob".Length
3

So you can check the length of your results that contain "Expired" to see if there are any expired's:
(41) C:\ -» $xs = @("Stuff","you've","got","might Expired  have","Connection Expired 1/1/2010") | ?{$_.Contains("Expired")}
(42) C:\ -» if ($xs.Length -gt 0) { Write-Host "Whoas, stuff's expired, dog." }
Whoas, shit's expired, dog.

(maybe someone has a better way to check if a collection contains an item that satisifies some predicate (like LINQ's Any)?)


text:
Q: error 6003: The value for column 'IsPrimaryKey' in table 'TableDetails' is DBNull I did the reverse engineering and I can not load my entities from my SQL Server database:

One or more errors occurred while loading schema information.
  Error 6003: The value for column 'IsPrimaryKey' in table 'TableDetails' is DBNull. Specified cast is not valid.


text:
Q: Wordpress media upload memory size problem I have a problem with upload files to wordpress system.
If i tried to upload a test.jpg file with size of arround 80 KB, than i get the follow error:
Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 8388616 bytes) in /var/www/vhosts/*****/httpdocs/wp-includes/wp-db.php on line 1890

I have tried to put follow code in wp-config.php
define( 'WP_MAX_MEMORY_LIMIT' , '512M' );

But without success.
On the server log after uploaded the test file I get this error:
AH01071: Got error 'PHP message: PHP Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 20480 bytes) in /var/www/vhosts/*****/httpdocs/wp-includes/wp-db.php on line 1889\n', referer: https://*********/wp-admin/media-new.php

Now i have put an other backup so I got an other error:
WordPress databasefout: [Duplicate entry '0' for key 'PRIMARY']
INSERT INTO `x9i8Z_icl_translations` (`element_type`, `language_code`, `trid`) VALUES ('post_attachment', 'nl', '7526')

Notice: Trying to get property of non-object in /var/www/vhosts/***********/httpdocs/wp-content/plugins/sitepress-multilingual-cms/classes/media/duplication/class-wpml-media-attachments-duplication.php on line 201

Notice: Trying to get property of non-object in /var/www/vhosts/***********/httpdocs/wp-content/plugins/sitepress-multilingual-cms/classes/media/duplication/class-wpml-media-attachments-duplication.php on line 201
0

Its strange because on the old version it works good, but if i put all the database data on a new schema it doesnt work any more :(

A: You need to setup upload_max_size via wp-config.php file.
@ini_set( 'upload_max_size' , '512M' );
It is better to increase the max execution time with the upload size. So, your final output will look like this.
@ini_set( 'upload_max_size' , '512M' );
@ini_set( 'post_max_size', '512M');
@ini_set( 'max_execution_time', '2400' );


text:
Q: How to increase uiswitch Thumb size I was trying to increase thumb size of a UISwitch I was trying to increase thumb size by set on the image but the image is not showing.
I try this:
uiSwitch.onImage = UIImage(named: "sing")

i want switch like this
here is image

A: if let thumbView = try (mySwitch.subviews[0].subviews[3] as? UIImageView) {
       thumbView.transform = CGAffineTransform(scaleX:1.5, y: 1.5)
   }

A: Create extension :
extension UISwitch {

func increaseThumb(){
    if let thumb = self.subviews[0].subviews[1].subviews[2] as? UIImageView {
        thumb.transform = CGAffineTransform(scaleX:1.5, y: 1.5)
    }
  }
}

Use:
 customSwitch.increaseThumb(

A: If you want exactly as image you refered https://github.com/JunichiT/JTMaterialSwitch
If you want to increase the only the thumb size of the UISwitch itself, you can't. You must increase the size of UISwitch.


text:
Q: Web Widget using html, js and bootstrap I am building a web widget using javascript only and not using iframe. I want my web widget not to use page's css. I cant use custom css and also don't want to use iframe as it will not be user friendly.
How can i restrict my web widget not to use page's css. As my web widget will return html code and that html uses that page css.

A: There is a thing like CSS reset: https://meyerweb.com/eric/tools/css/reset/
It basically resets all css properties for a given subtree.


text:
Q: Pass data upstream to app component Is it possible to pass data two or more levels upstream from Child Component to App Component?

A: Use a shared service like explained in https://angular.io/docs/ts/latest/cookbook/component-communication.html
Provide the service once at the root component and it is avialable throughout the application and you can use it (for example also with observables) to communicate in both directions, similar to an event bus.


text:
Q: "Message/letter was read?" - Sentence help! I am writing an essay and it needs to be in formal language, I am referring to a letter/message and I am supposed to quote it for the readers, but before jumping right into quoting that letter, I like to make an introducing comment like, "The letter was read as follows," I know I'm confusing "is as follows" into it, but I like to have it in the same shade, just grammatical and perhaps formal.
Like, "The message was read as.."
Can someone with a better understanding of the English language and its idioms help me, please?

A: Here are two common ways to write it.

The message read: "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch . . . ."

Or

The message read as follows: "It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch . . . ."


text:
Q: question about the convergence of a function I'll start off with what I know:
I know that if I have two functions f(x) and g(x)
if:
$$
\int_0^\infty f(x) < \int_0^\infty g(x)
$$
If g(x) converges as the values function approaches infinity, I know that f(x) also converges.
Here's my question:
If f(x) < g(x), and f(x) does not converge, does that mean that g(x) also does not converge?

A: If $f(x)$ converges, you don't know anything about $g(x)$
If $f(x)$ diverges, then certainly $g(x)$ diverges


text:
Q: Webpack bootstrap.css npm module fails parsing with ExtractTextLoader + css_loader I am learning to use node as a front end build tool and am struggling with including bootstrap into a css bundle file to include within a web page.
I have a loader for LESS and a loader for CSS, as well as loaders for FONTS, and requiring any of those from my own sources seem to work properly translating CSS into my bundle files, but as soon as I
require('bootstrap/dist/css/bootstrap.css')

or
require('../../node_modules/bootstrap/dist/css/bootstrap.css')

I get the following error during webpack:
ERROR in ./~/bootstrap/dist/css/bootstrap.css?root=/~/bootstrap/dist/
Module parse failed: <my project root>/node_modules/bootstrap/dist/css/bootstrap.css?root=/node_modules/bootstrap/dist/ Unexpected token (7:5)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (7:5)

I checked out bootstrap.css from the bundle, and line7, char5 seems to be the " " space between html and { first css rule in the file after a block comment which is perfectly valid CSS... ? I can even copy the entire content of that file into one of my local source files (common/style.less) and it will parse just fine and be included in the bundle. I simply can't include it from the node_modules location. Why?
My app.js entry point looks like this:
import 'babel-polyfill';

// common frameworks
require('expose?$!jquery');
require('expose?jQuery!jquery');
require('bootstrap/dist/js/bootstrap.js');

// common styles
require('bootstrap/dist/css/bootstrap.css');
require('./common/style.less');

// common images
var images = require.context('./common/images/', true, /.*\.(png|gif|bmp|jpg|jpeg|ico)$/);
images.keys().forEach(images);

// modules
require('./modules/landing');

webpack.config.js:
const webpack = require('webpack');
var path = require('path');
var minimize = process.argv.indexOf('--minimize') !== -1;
var ExtractTextPlugin = require('extract-text-webpack-plugin');

var CssBundler = new ExtractTextPlugin('[name].css', {
  allChunks: true
});

var BUILD_DIR = path.resolve(__dirname, '../webroot/assets');
var APP_DIR = path.resolve(__dirname, './src');

config = {
  entry: {
    'camo' : APP_DIR + '/Camo/index',
    'frontend': APP_DIR + '/Frontend/index'
  },
  output: {
    path: BUILD_DIR,
    publicPath: '/assets/',
    filename: '[name].bundle.js'
  },
  module: {
    loaders: [
    {
      test: /\.js$/,
      exclude: /node_modules/,
      loader: 'imports?this=>window!babel-loader'
    },
    {
      test: /\.css$/,
      include: APP_DIR,
      loader: CssBundler.extract("style-loader", "css-loader")
    },
    {
      test: /\.less/,
      include: APP_DIR,
      loader: CssBundler.extract("style-loader", "css-loader!less-loader")
    },
    {
      test: /\.(png|jpg|gif|bmp|ico)$/,
      include: APP_DIR,
      loader: 'url-loader?limit=8192!file?name=/images/[name].[ext]'  // inline base64 URLs for <=8k images, direct URLs for the rest]
    },
    {
      test: /\.(eot|svg|ttf|woff|woff2)$/,
      loader: 'file?name=/fonts/[name].[ext]'
    },
    {
      test: /\.handlebars$/,
      loader: "handlebars-loader"
    }]
  },
  plugins: [
    CssBundler
  ]
};

if (minimize) {
  config.plugins.push(
    new webpack.optimize.UglifyJsPlugin({
      compress: {
        warnings: false
      },
      output: {
        comments: false
      }
    })
  )
}

module.exports = config;

A: I finally fixed this. Notice my INCLUDE paths. for css, it includes only my /src folder, which by nature excludes node_modules since it's sibling to it. If I change my include for css to be the app root directory, the proper loader handles the css for bootstrap.css and it properly builds! whew.