text:
Q: Mockito - Mocking Silhouette always throws NullPointerException I'm using play framework 2.5 and silhouette library with scala 2.11.
And writing test code using play specs2 and mockito.
Now, I've been trying mock to throw an exception.
But, the mock always throws NullPointerException before it's called.
Here's the target of test code.
class TestController @Inject() (
  ...
  silhouette: Silhouette[DefaultEnv]) extends Controller {

  def target() = silhouette.SecuredAction.async { implicit request =>
    try {
      silhouette.env.authenticatorService.discard(request.authenticator, Ok)
    } catch {
      case t: Throwable =>
        Future.successful(InternalServerError(...))
    }
  }
}

Test code as below.
class TestControllerSpec extends PlaySpecification with Mockito {
  ...
  trait Context extends Scope {
    val mockTest = mock[Silhouette[DefaultEnv]]

    // This always throws a NullPointerException.
    mockTest.env.authenticatorService.discard(any[JWTAuthenticator], any[Result])(any[RequestHeader]) throws new AuthenticatorDiscardingException("AuthenticatorDiscardingException")

    lazy val appMock = new GuiceApplicationBuilder()
      .overrides(new FakeModule)
      .overrides(bind[Silhouette[DefaultEnv]].toInstance(mockTest))
      .build
  }
  ...
}

I've got error messages as following.
[error]      java.lang.NullPointerException: null (TestControllerSpec.scala:123)
[error] controllers.TestControllerSpec$$anonfun$29$Context$1$$anonfun$40.apply(TestControllerSpec.scala:123)
[error] controllers.TestControllerSpec$$anonfun$29$Context$1$$anonfun$40.apply(TestControllerSpec.scala:123)
[error] controllers.TestControllerSpec$$anonfun$29$Context$1$class.$init$(TestControllerSpec.scala:123)
[error] controllers.TestControllerSpec$$anonfun$29$$anonfun$apply$16$$anonfun$apply$18$$anon$32.<init>(TestControllerSpec.scala:393)
[error] controllers.TestControllerSpec$$anonfun$29$$anonfun$apply$16$$anonfun$apply$18.apply(TestControllerSpec.scala:393)
[error] controllers.TestControllerSpec$$anonfun$29$$anonfun$apply$16$$anonfun$apply$18.apply(TestControllerSpec.scala:393)


text:
Q: TypeError: Cannot read property 'style' of null This has been asked many times, I've found many other questions like this. None of which has helped me. I can't find the problem in my code and it's about to drive me insane.
Most answers say that there is a typo on my id name. However, I've changed the id name quite a few times and pasted it to no avail.

    Click here

    <textarea class="w250p h100p"></textarea>

 Click Here

Javascript. I've tried this with straight JS and jQuery both. Neither of which work.

There is something messed up and I can't find it. I've been working on this for about 2hrs now. Much too long for such a simple stupid mistake. Please help me.

A: Line should be:

And you should add a letter to the beginning so that it is valid.
http://reference.sitepoint.com/html/core-attributes/id
UPDATE:
The id is valid for HTML5 per comment from @Ian.
http://mathiasbynens.be/notes/html5-id-class

A: <div id"123222"

should be
<div id="something-123222"

Check the comments about ID's not being numbers

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to get varchar as byte[] using DataReader in Ado.Net? how to get varchar as byte[] data using DataReader in Ado.Net? We have tried the following code.
if (!objDataReader.IsDBNull(i))
                  {
                                long len = objDataReader.GetBytes(i, 0, null, 0, 0);

                                byte[] buffer = new byte[len];
                                objDataReader.GetBytes(i, 0, buffer, 0, (int)len);

                  }

But the above code gives the error ("Unable to cast object of type 'System.String' to type 'System.Byte[]'.")
Update:
When value for a column is null and i remove dbnull condition then executing following lines of code gives an error as "Unable to cast object of type 'System.DBNull' to type 'System.Byte[]"
long len = objDataReader.GetBytes(i, 0, null, 0, 0);
byte[] buffer = new byte[len];
objDataReader.GetBytes(i, 0, buffer, 0, (int)len);

A: A varchar field should be storing text, not raw bytes. If you want to store opaque binary data, use image or binary.
If you want to get the bytes which represent some text in a particular encoding, you can use Encoding.GetBytes - but you'll need to specify the encoding, e.g. Encoding.UTF8.GetBytes(text). However, that may not be how it's represented in the database. The point is that it's text data, so the exact binary representation shouldn't matter, so long as you can accurately reproduce the Unicode string.
What are you storing in this field?


text:
Q: JAXB and Guice: How to integrate and visualize? I find using JAXB together with Guice possible, but challenging: Both libraries "fight" for control over object creation, you have to be careful to avoid cyclic dependencies, and it can get messy with all the JAXB Adapters and Guice Providers and stuff. My questions are:

*

*How do you deal with this configuration? What general strategies / rules of thumb can be applied?

*Can you point me to a good tutorial or well written sample code?

*How to visualize the dependencies (including the Adapters and Providers)?

A: For some sample code, some example work was done here: http://jersey.576304.n2.nabble.com/Injecting-JAXBContextProvider-Contextprovider-lt-JAXBContext-gt-with-Guice-td5183058.html
At the line that says "Wrong?", put in the recommended line.
I looks like this:
@Provider
public class JAXBContextResolver implements ContextResolver<JAXBContext> {

    private JAXBContext context;
    private Class[] types = { UserBasic.class, UserBasicInformation.class };

    public JAXBContextResolver() throws Exception {
         this.context =
       new JSONJAXBContext(
         JSONConfiguration.natural().build(), types);
     }

    public JAXBContext getContext(Class<?> objectType) {
        /*
        for (Class type : types) {
            if (type == objectType) {
                return context;
            }
        } // There should be some kind of exception for the wrong type.
        */
        return context;
    }
}

//My resource method:

    @GET
    @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
    public JAXBElement<UserBasic> get(@QueryParam("userName") String userName) {
        ObjectFactory ob = new ObjectFactory();
        UserDTO dto = getUserService().getByUsername(userName);
        if(dto==null) throw new NotFoundException();
        UserBasic ub = new UserBasic();
        ub.setId(dto.getId());
        ub.setEmailAddress(dto.getEmailAddress());
        ub.setName(dto.getName());
        ub.setPhoneNumber(dto.getPhoneNumber());
        return ob.createUserBasic(ub);
    }

//My Guice configuration module:

public class MyServletModule extends ServletModule {

    public static Module[] getRequiredModules() {
        return new Module[] {
                new MyServletModule(),
                new ServiceModule(),
                new CaptchaModule()
         };
    }

    @Override
    protected void configureServlets() {
        bind(UserHttpResource.class);
        bind(JAXBContextResolver.class);
        serve("/*").with(GuiceContainer.class);
    }
}


text:
Q: How do I put a scrollPane on a BoxLayout? I would like to have my JFrame that has a BoxLayout be able to have a scroll pane so I could just keep adding in Groups like if it was a receipt or invoice printer. Is there a way to add a ScrollPane?
Question: How to add a ScrollPane to the JFrame?
Code, originally seen here:
import java.awt.EventQueue;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.GroupLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

/** @see https://stackoverflow.com/a/8504753/230513 */
public class GroupPanel extends JPanel {
    private static final long serialVersionUID = 1L;
    private JLabel label1     = new JLabel("Primary:");
    private JTextField field1 = new JTextField(16);
    private JLabel label2     = new JLabel("Secondary:");
    private JTextField field2 = new JTextField(16);
    private JLabel label3     = new JLabel("Tertiary:");
    private JTextField field3 = new JTextField(16);
    JScrollPane sp = new JScrollPane();

    public GroupPanel(int n) {
        this.setBorder(BorderFactory.createTitledBorder("Panel " + n));
        GroupLayout l = new GroupLayout(this);
        this.setLayout(l);
        l.setAutoCreateGaps(true);
        l.setAutoCreateContainerGaps(true);
        l.setHorizontalGroup(l.createSequentialGroup()
            .addGroup(l.createParallelGroup(GroupLayout.Alignment.TRAILING)
                .addComponent(label1)
                .addComponent(label2)
                .addComponent(label3))
            .addGroup(l.createParallelGroup(GroupLayout.Alignment.LEADING)
                .addComponent(field1)
                .addComponent(field2)
                .addComponent(field3))
        );

        l.setVerticalGroup(l.createSequentialGroup()
            .addGroup(l.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(label1)
                .addComponent(field1))
            .addGroup(l.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(label2)
                .addComponent(field2))
            .addGroup(l.createParallelGroup(GroupLayout.Alignment.BASELINE)
                .addComponent(label3)
                .addComponent(field3))
        );

        sp.setToolTipText("test");
        sp.add(this);
    }

    private static void display() {
        JFrame f = new JFrame("GroupPanel");
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.getContentPane().setLayout(new BoxLayout(f.getContentPane(), BoxLayout.Y_AXIS));
        f.getContentPane().add(new GroupPanel(1));
        f.getContentPane().add(new GroupPanel(2));
        f.getContentPane().add(new GroupPanel(3));
        f.getContentPane().add(new GroupPanel(4));
        f.getContentPane().add(Box.createVerticalGlue());
        f.pack();
        f.setLocationRelativeTo(null);
        f.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                display();
            }
        });
    }
}

A: Simply enclose all the components into JPanel first and then add it into JScrollPane and finally add JScrollPane into JFrames content pane.
Sample code:
JPanel panel = new JPanel();
JScrollPane scrollPane = new JScrollPane(panel);

panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
panel.add(new GroupPanel(1));
panel.add(new GroupPanel(2));
panel.add(new GroupPanel(3));
panel.add(new GroupPanel(4));
panel.add(Box.createVerticalGlue());

f.getContentPane().add(scrollPane);

screenshot;


text:
Q: How to handle MonoDroid uncaught exceptions globally and prevent application from crash I'm trying to implement valid exception handling in my monodroid app which is written with Xamarin.Android plugin for Visual Studio.
I'm trying to handle 2 types of exceptions:

*

*at foreground (UI) thread

*at background (threadpool) thread

In both cases at global handler I'm want to:

*

*Logging - (submitting analytics event)

*User Notification - (alert)

After certain investigation I have found some answers here, here and here but nothing except AndroidEnvironment.UnhandledExceptionRaiser and AppDomain.UnhandledException was proposed and it doesn't work in all cases.
I created short sample where I'm trying to use both handlers:
AppDomain.CurrentDomain.UnhandledException += (s,e)=>
{
    System.Diagnostics.Debug.WriteLine("AppDomain.CurrentDomain.UnhandledException: {0}. IsTerminating: {1}", e.ExceptionObject, e.IsTerminating);
};

AndroidEnvironment.UnhandledExceptionRaiser += (s, e) =>
{
    System.Diagnostics.Debug.WriteLine("AndroidEnvironment.UnhandledExceptionRaiser: {0}. IsTerminating: {1}", e.Exception, e.Handled);
    e.Handled = true;
};

And then on button click I added the following code to raise both types of exceptions:
//foreground exception
throw new NullReferenceException("test nre from ui thread.");
//background exception
ThreadPool.QueueUserWorkItem(unused =>
{
    throw new NullReferenceException("test nre from back thread.");
});

As a result I have different behavior for both types of exceptions:

*

*foreground:

*

*both handlers are raised

*it is impossible to prevent app from being
crashed - it will be crashed any way (e.Handled = true is just ignored)

*background:

*

*only the second handler is raised

*app doesn't crash

In my case I couldn't wrap every user action in try-catch, especially background tasks.
I have business login which should be interrupted in case of error and it is exactly what I expect from runtime. Same time I want to handle those exception on the top level in one place, log them (based on my our business rules) and continue app execution.
How to handle both exception and still have ability to keep app alive (prevent crash).
You can find complete code sample here:
https://dl.dropboxusercontent.com/u/19503836/UnhandledException.zip
Thank you for your advice. Any help appreciated.
TIA!

A: These event handlers aren't designed to let you recover from the exception, they're a last resort to give you an opportunity to do something like writing to an error log before the application is terminated.
You've mentioned that you want to log errors - that should work fine, but displaying an error to the user might not be possible because your Application will have reached a point where it is not even able to do that.
As the comment on your question mentions, it is a bad idea to handle exceptions like this.
While you might have a very specific expectation of when this is going to be called, your App could throw an exception at any point - and for any reason. It's impossible to design it so that it handles everything correctly.
Even if you could write something to deal with any exception safely, your App will still be terminated because of the unhandled exception.
The Microsoft documentation for AppDomain.CurrentDomain.UnhandledException gives some more information on this:
http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx

A: @Daveoc64 - I disagree with you (and others) that have stressed that global handling of uncaught exceptions is a bad idea - i'd say its a necessity for UI applications. It doesn't negate proper exception handling at the method level (i.e where you can handle and recover from specific exceptions in which context is very important as you stressed) - but it's used in addition to it, as sometimes, when an exception occurs, there is no recovery for the application. Therefore putting a try / catch in code to catch an exception that you cannot recover from is pointless - as whatever you put inside that catch block - you'd have to copy and put inside all other catch blocks for the same sort of unrecoverable errors - i.e display a prompt to the user and gracefully exit.. Why repeat that sort of handling throughout the entire code base over and over again - its rediculous - a global exception handler to cater for that kind of concern makes much more sense!


text:
Q: Is there some search engine SDK or API that I can use for local search? I have many documents located on my disk and I want to build a search engine to search through them.
I know Google Desktop Search or Bing Desktop Search could do that. But I want to know if there's some SDK/API to do that so I can do some customization.
What I want to achieve, is that I can provide a document and the local search engine will return all the documents similar to it.

A: In general there are Lucene and Solr that can help to solve search related needs in Java (I guess you are using Java based on the tag GWT).
But I don't know how to do a search by example with these tools. I think you have to extract the relevant information of the document to construct a search based on it.


text:
Q: Click Event in Jquery is not firing I have a list tag in HTML like this ...

<a id="teams" class="first" href="#"

Now as per my requirement ,I want to fire a click event on this anchor link.Here is the code that i am trying but click event is not getting fired..
      $(document).ready(function () {

            $("teams").click(function(event) {
                  alert("hello");
            });

        });

Here is the Demo Fiddle..
Fiddle
Please tell me where i am wrong ..Thanks in advance..

A: The selector that you meant as id selector was wrong. Please see here to know more about jquery selectors.
Try,
  $("#teams").click(function(event) {
     alert("hello");
  });

DEMO

A: While accessing ids use #. And while accessing class use ..
Here's your udpated fiddle : http://jsfiddle.net/qax4t/2/

A: You have incorrect selector. You Should be using id selector #:
$("#teams").click(function(event) {
              alert("hello");
        });

or for using class selector:
$("a.first").click(function(event) {
              alert("hello");
        });

Demo

A: If you want to use an id selector you must precede the selector with #:

Description: Selects a single element with the given id attribute.

Code:
$("#teams").click(function(event) {
    alert("hello");
});

Demo: http://jsfiddle.net/IrvinDominin/8xJRe/
Side note, your  element markup is not well formed.

A: For access the id use '#'like this:
                 ('#team').click(function(){
                     //code here
                 })

For access the class use '.' like this
                  ('.team').click(function(){
                     //code here
                 })


text:
Q: mpdf - set headers and footers How to set headers and footer in PDF documents generated with mpdf?
$mpdf = new \Mpdf\Mpdf();
$mpdf->SetHTMLHeader('
Page: {PAGENO}
');
$mpdf->WriteHTML('
test
');
$mpdf->Output('test.pdf');

This writes test to the document but no header?
How can I add the total page number to the header like Page 1 of 3


text:
Q: Using ValidatesRequests trait in Laravel Here's the code from my AuthController:
public function postRegister(Request $request)
{
    $this->validate($request, [
        'name' => 'required|min:3',
        'email' => 'required|email|unique:users',
        'password' => 'required|min:5|max:15',
    ]);
}

If the validation fails I'm getting redirected to the previous page. Is there a way to pass additional data along with the input and the errors (which are handled by the trait)?
Edit: Actually, the trait does exactly what I want, except the additional data I want to pass. As @CDF suggested in the answers I should modify the buildFailedValidationResponse method which is protected.
Should I create a new custom trait, which will have the same functionality as the ValidatesRequests trait (that comes with Laravel) and edit the buildFailedValidationResponse method to accept one more argument or traits can be easily modified following another approach (if any exists)?

A: Sure you can, check the example in the documentation:
http://laravel.com/docs/5.1/validation#other-validation-approaches1
Using the fails(); method, you can flash the errors and inputs values in the session and get them back with after redirect. To pass other datas just flash them with the with(); method.
if ($validator->fails()) {
return back()->withErrors($validator)
->withInput()
->with($foo);
    }


text:
Q: Glitch in 'Cool text highlighting' This answer provides a fantastic "ragged text highlight". Unfortunately I'm getting a weird glitch with it:

I have literally taken the source code from the link and replaced the material between \begin{document} and \end{document} with
{replacing} \highlight{$g$} {by} \highlight{$g^{-1}$},

The MWE is however long because the original code is long:
\documentclass{minimal}
\usepackage{soul}
\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{decorations.pathmorphing}

\makeatletter

\newcommand{\defhighlighter}[3][]{%
  \tikzset{every highlighter/.style={color=#2, fill opacity=#3, #1}}%
}

\defhighlighter{yellow}{.5}

\newcommand{\highlight@DoHighlight}{
  \fill [ decoration = {random steps, amplitude=1pt, segment length=15pt}
        , outer sep = -15pt, inner sep = 0pt, decorate
        , every highlighter, this highlighter ]
        ($(begin highlight)+(0,8pt)$) rectangle ($(end highlight)+(0,-3pt)$) ;
}

\newcommand{\highlight@BeginHighlight}{
  \coordinate (begin highlight) at (0,0) ;
}

\newcommand{\highlight@EndHighlight}{
  \coordinate (end highlight) at (0,0) ;
}

\newdimen\highlight@previous
\newdimen\highlight@current

\DeclareRobustCommand*\highlight[1][]{%
  \tikzset{this highlighter/.style={#1}}%
  \SOUL@setup
  %
  \def\SOUL@preamble{%
    \begin{tikzpicture}[overlay, remember picture]
      \highlight@BeginHighlight
      \highlight@EndHighlight
    \end{tikzpicture}%
  }%
  %
  \def\SOUL@postamble{%
    \begin{tikzpicture}[overlay, remember picture]
      \highlight@EndHighlight
      \highlight@DoHighlight
    \end{tikzpicture}%
  }%
  %
  \def\SOUL@everyhyphen{%
    \discretionary{%
      \SOUL@setkern\SOUL@hyphkern
      \SOUL@sethyphenchar
      \tikz[overlay, remember picture] \highlight@EndHighlight ;%
    }{%
    }{%
      \SOUL@setkern\SOUL@charkern
    }%
  }%
  %
  \def\SOUL@everyexhyphen##1{%
    \SOUL@setkern\SOUL@hyphkern
    \hbox{##1}%
    \discretionary{%
      \tikz[overlay, remember picture] \highlight@EndHighlight ;%
    }{%
    }{%
      \SOUL@setkern\SOUL@charkern
    }%
  }%
  %
  \def\SOUL@everysyllable{%
    \begin{tikzpicture}[overlay, remember picture]
      \path let \p0 = (begin highlight), \p1 = (0,0) in \pgfextra
        \global\highlight@previous=\y0
        \global\highlight@current =\y1
      \endpgfextra (0,0) ;
      \ifdim\highlight@current < \highlight@previous
        \highlight@DoHighlight
        \highlight@BeginHighlight
      \fi
    \end{tikzpicture}%
    \the\SOUL@syllable
    \tikz[overlay, remember picture] \highlight@EndHighlight ;%
  }%
  \SOUL@
}
\makeatother

\begin{document}
 {replacing} \highlight{$g$} {by} \highlight{$g^{-1}$},
\end{document}

A: I can't think of a quick way to modify and record the highlighted text length since I don't know much about SOUL. So, I modified the random steps decoration since it's quite short to include in the preamble.
\documentclass{article}
\usepackage{soul}
\usepackage{tikz}
\usepackage{lipsum}

\usetikzlibrary{decorations.pathmorphing,calc}

\makeatletter
\pgfdeclaredecoration{highlighted random steps}{start}
{
  \state{start}[width=+0pt,next state=step,persistent precomputation=\pgfdecoratepathhascornerstrue]{}
  \state{step}[auto end on length=0.5\pgfdecorationsegmentlength, % This was 1.5 now 0.5
               auto corner on length=1.5\pgfdecorationsegmentlength,
               width=+\pgfdecorationsegmentlength]
  {
    \pgfpathlineto{
      \pgfpointadd
      {\pgfpoint{\pgfdecorationsegmentlength}{0pt}}
      {\pgfpoint{rand*\pgfdecorationsegmentamplitude}{rand*\pgfdecorationsegmentamplitude}}
    }
  }
  \state{final}
  {}
}

\newcommand{\defhighlighter}[3][]{%
  \tikzset{every highlighter/.style={color=#2, fill opacity=#3, #1}}%
}

\defhighlighter{yellow}{.5}

\newcommand{\highlight@DoHighlight}{
  \fill [ decoration = {highlighted random steps, amplitude=1pt, segment length=15pt},
        , outer sep = -15pt, inner sep = 0pt, decorate
        , every highlighter, this highlighter ]
        ([yshift=8pt]begin highlight) rectangle ([yshift=-3pt]end highlight);
}

\newcommand{\highlight@BeginHighlight}{
  \coordinate (begin highlight) at (0,0) ;
}

\newcommand{\highlight@EndHighlight}{
  \coordinate (end highlight) at (0,0) ;
}

\newdimen\highlight@previous
\newdimen\highlight@current
%\newdimen\highlight@horzdiff

\DeclareRobustCommand*\highlight[1][]{%
  \tikzset{this highlighter/.style={#1}}%
  \SOUL@setup
  %
  \def\SOUL@preamble{%
    \begin{tikzpicture}[overlay, remember picture]
      \highlight@BeginHighlight
      \highlight@EndHighlight
    \end{tikzpicture}%
  }%
  %
  \def\SOUL@postamble{%
    \begin{tikzpicture}[overlay, remember picture]
      \highlight@EndHighlight
      \highlight@DoHighlight
    \end{tikzpicture}%
  }%
  %
  \def\SOUL@everyhyphen{%
    \discretionary{%
      \SOUL@setkern\SOUL@hyphkern
      \SOUL@sethyphenchar
      \tikz[overlay, remember picture] \highlight@EndHighlight ;%
    }{%
    }{%
      \SOUL@setkern\SOUL@charkern
    }%
  }%
  %
  \def\SOUL@everyexhyphen##1{%
    \SOUL@setkern\SOUL@hyphkern
    \hbox{##1}%
    \discretionary{%
      \tikz[overlay, remember picture] \highlight@EndHighlight ;%
    }{%
    }{%
      \SOUL@setkern\SOUL@charkern
    }%
  }%
  %
  \def\SOUL@everysyllable{%
    \begin{tikzpicture}[overlay, remember picture]
      \path let \p0 = (begin highlight), \p1 = (0,0) in \pgfextra{%
        \global\highlight@previous=\y0%
        \global\highlight@current =\y1%
      }(0,0) ;
      \ifdim\highlight@current < \highlight@previous
        \highlight@DoHighlight
        \highlight@BeginHighlight
      \fi
    \end{tikzpicture}%
    \the\SOUL@syllable
    \tikz[overlay, remember picture] \highlight@EndHighlight ;%
  }%
  \SOUL@
}
\makeatother

\begin{document}
 {replacing} \highlight{$g$} {by} \highlight{$g^{-1}$}, \highlight{$\sin x \log x \tan x
\cos x$ some more text to see if it works over a linebreak.} And normal text continues.
\end{document}


text:
Q: Server Error: The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>) Neither the control to which I'm adding nor the control itself contain <%=%> or <% %> blocks. Why am I getting this? Here's my code-behind for the charts page which contains the offending line (marked with a comment), Charts.asx.cs:
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using Telerik.Web.UI;

namespace DashboardX.pages
{
    public partial class Charts : System.Web.UI.UserControl
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            // PROBLEM IS HERE!!!
            PlaceHolder1.Controls.Add(ColumnPanel);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            DataBind();
        }

        public void DownloadColumnChart(object sender, EventArgs e)
        {
            DownloadImage(sender, e, RadHtmlChart1, DropDownList1);
        }

        public void DownloadPieChart(object sender, EventArgs e)
        {
            DownloadImage(sender, e, RadHtmlChart2, DropDownList2);
        }

        public void DownloadBarChart(object sender, EventArgs e)
        {
            DownloadImage(sender, e, RadHtmlChart3, DropDownList3);
        }

        public void DownloadLineChart(object sender, EventArgs e)
        {
            DownloadImage(sender, e, RadHtmlChart4, DropDownList4);
        }

        ///
        /// Downloads an image of the given RadHtmlChart (with the given dropdown
        /// providing the format specification [PNG/PDF]) by launching Inkscape and
        /// passing some command line arguments.
        ///
        /// <param name="sender">Who ran this function?</param>
        /// <param name="e">Event data.</param>
        /// <param name="chart">The chart of which to generate an image.</param>
        /// <param name="ddl">The dropdown list with the format desired selected.</param>
        public void DownloadImage(object sender, EventArgs e, RadHtmlChart chart, DropDownList ddl)
        {
            //obtain the necessary settings for exporting the chart
            HtmlChartExportSettings currentSettings = new HtmlChartExportSettings();

            if (chart.Height != null && chart.Width != null)
            {
                currentSettings.Height = (int)chart.Height.Value;
                currentSettings.Width = (int)chart.Width.Value;
            }

            //decodes the SVG string saved from the client
            string svgText = HttpUtility.UrlDecode(svgHolder.Value);

            //create a temporary SVG file that Inkscape will use
            currentSettings.SvgFilePath = Server.MapPath("~/App_Data/temp.svg");
            System.IO.File.WriteAllText(currentSettings.SvgFilePath, svgText);

            //get the export format - png or pdf
            currentSettings.Extension = ddl.SelectedValue;

            //the output file Inkscape will use, hardcoded to use App_Data as a temporary folder
            currentSettings.OutputFilePath = (@"C:\chart." + currentSettings.Extension);

            //you can change the name of the file the user will receive here. Extension is automatically added
            currentSettings.ClientFileName = "chart";

            //the actual file is created
            HtmlChartExporter.ExportHtmlChart(currentSettings);

            //read the exported file and send it to the client
            byte[] fileForClient = HtmlChartExporter.ReadFile(currentSettings.OutputFilePath);
            Response.ContentType = HtmlChartExportSettings.ContentTypeList[currentSettings.Extension];
            Response.AddHeader("Content-Disposition", "attachment;filename=" + currentSettings.ClientFileName);
            Response.BinaryWrite(fileForClient);

            //delete the temporary files to avoid flooding the server
            File.Delete(currentSettings.OutputFilePath);
            File.Delete(currentSettings.SvgFilePath);

            svgHolder.Value = "";
        }
    }
}

Here's the code for the parents:

    <asp:PlaceHolder ID="PlaceHolder1" runat="server">
    </asp:PlaceHolder>
    <asp:PlaceHolder ID="PlaceHolder2" runat="server">
    </asp:PlaceHolder>
    <asp:PlaceHolder ID="PlaceHolder3" runat="server">
    </asp:PlaceHolder>
    <asp:PlaceHolder ID="PlaceHolder4" runat="server">
    </asp:PlaceHolder>

Here are the children:
<asp:Panel ID="ColumnPanel" runat="server" Height="405px" Width="450px" CssClass="left hidden">

            <asp:DropDownList ID="DropDownList1" runat="server">
                <asp:ListItem Text="PNG" Value="png" Selected="true"></asp:ListItem>
                <asp:ListItem Text="PDF" Value="pdf"></asp:ListItem>
            </asp:DropDownList>
            <asp:Button ID="Button1" runat="server" Text="Download Image" OnClick="DownloadColumnChart" OnClientClick="getSvgContent(this, 'RadHtmlChart1'); return false;" />

        <telerik:RadHtmlChart ID="RadHtmlChart1" runat="server" DataSourceID="SqlDataSource_TotalSales">
            <PlotArea>
                <Series>
                    <telerik:ColumnSeries DataFieldY="TotalSales">
                        <LabelsAppearance DataFormatString="{0:C}" Visible="false" />
                        <TooltipsAppearance DataFormatString="{0:C}" />
                    </telerik:ColumnSeries>
                </Series>
                <XAxis DataLabelsField="SubmitDate" MajorTickType="Outside" Step="1" MinorTickType="None">
                    <MinorGridLines Visible="false" />
                    <MajorGridLines Visible="false" />
                    <LabelsAppearance RotationAngle="-70" DataFormatString="{0}">
                    </LabelsAppearance>
                </XAxis>
                <YAxis>
                    <LabelsAppearance DataFormatString="${0}">
                    </LabelsAppearance>
                </YAxis>
            </PlotArea>
            <Legend>
                <Appearance Visible="false">
                </Appearance>
            </Legend>
        </telerik:RadHtmlChart>

</asp:Panel>
<asp:Panel ID="PiePanel" runat="server" Height="405px" Width="450px" CssClass="hidden">

            <asp:DropDownList ID="DropDownList2" runat="server">
                <asp:ListItem Text="PNG" Value="png" Selected="true"></asp:ListItem>
                <asp:ListItem Text="PDF" Value="pdf"></asp:ListItem>
            </asp:DropDownList>
            <asp:Button ID="Button2" runat="server" Text="Download Image" OnClick="DownloadPieChart" OnClientClick="getSvgContent(this, 'RadHtmlChart2'); return false;" />

        <telerik:RadHtmlChart ID="RadHtmlChart2" runat="server"
            Transitions="true" DataSourceID="SqlDataSource_TotalSales">
            <PlotArea>
                <Series>
                    <telerik:PieSeries DataFieldY="TotalSales" StartAngle="90">
                        <LabelsAppearance ClientTemplate="#=dataItem.SubmitDate#" Position="Circle"
                        DataFormatString="{0:C}">
                        </LabelsAppearance>
                        <TooltipsAppearance DataFormatString="{0:C}" />
                    </telerik:PieSeries>
                </Series>
                <XAxis DataLabelsField="SubmitDate" Visible="true">
                </XAxis>
                <YAxis>
                    <LabelsAppearance DataFormatString="{0:C}">
                    </LabelsAppearance>
                </YAxis>
            </PlotArea>
            <Legend>
                <Appearance Visible="false">
                </Appearance>
            </Legend>
        </telerik:RadHtmlChart>

</asp:Panel>
<asp:Panel ID="BarPanel" runat="server" Height="405px" Width="450px" CssClass="left hidden">

            <asp:DropDownList ID="DropDownList3" runat="server">
                <asp:ListItem Text="PNG" Value="png" Selected="true"></asp:ListItem>
                <asp:ListItem Text="PDF" Value="pdf"></asp:ListItem>
            </asp:DropDownList>
            <asp:Button ID="Button3" runat="server" Text="Download Image" OnClick="DownloadBarChart" OnClientClick="getSvgContent(this, 'RadHtmlChart3'); return false;" />

        <telerik:RadHtmlChart ID="RadHtmlChart3" runat="server" DataSourceID="SqlDataSource_TotalSales">
            <PlotArea>
                <Series>
                    <telerik:BarSeries DataFieldY="TotalSales">
                        <LabelsAppearance DataFormatString="{0:C}" Visible="false" />
                        <TooltipsAppearance DataFormatString="{0:C}" />
                    </telerik:BarSeries>
                </Series>
                <XAxis DataLabelsField="SubmitDate" MajorTickType="None" MinorTickType="None">
                    <MinorGridLines Visible="false" />
                    <MajorGridLines Visible="false" />
                    <LabelsAppearance RotationAngle="0" DataFormatString="{0}">
                    </LabelsAppearance>
                </XAxis>
                <YAxis>
                    <LabelsAppearance DataFormatString="${0}">
                    </LabelsAppearance>
                </YAxis>
            </PlotArea>
            <Legend>
                <Appearance Visible="false">
                </Appearance>
            </Legend>
        </telerik:RadHtmlChart>

</asp:Panel>
<asp:Panel ID="LinePanel" runat="server" Height="405px" Width="450px" CssClass="hidden">

            <asp:DropDownList ID="DropDownList4" runat="server">
                <asp:ListItem Text="PNG" Value="png" Selected="true"></asp:ListItem>
                <asp:ListItem Text="PDF" Value="pdf"></asp:ListItem>
            </asp:DropDownList>
            <asp:Button ID="Button4" runat="server" Text="Download Image" OnClick="DownloadLineChart" OnClientClick="getSvgContent(this, 'RadHtmlChart4'); return false;" />

        <telerik:RadHtmlChart ID="RadHtmlChart4" runat="server" DataSourceID="SqlDataSource_TotalSales">
            <PlotArea>
                <Series>
                    <telerik:LineSeries DataFieldY="TotalSales">
                        <LabelsAppearance DataFormatString="{0:C}" Visible="false" />
                        <TooltipsAppearance DataFormatString="{0:C}" />
                    </telerik:LineSeries>
                </Series>
                <XAxis DataLabelsField="SubmitDate" MajorTickType="Outside" MinorTickType="None">
                    <MinorGridLines Visible="false" />
                    <MajorGridLines Visible="false" />
                    <LabelsAppearance RotationAngle="-70" DataFormatString="{0}">
                    </LabelsAppearance>
                </XAxis>
                <YAxis>
                    <LabelsAppearance DataFormatString="${0}">
                    </LabelsAppearance>
                </YAxis>
            </PlotArea>
            <Legend>
                <Appearance Visible="false">
                </Appearance>
            </Legend>
        </telerik:RadHtmlChart>

</asp:Panel>


text:
Q: C# -> Python Encoding and Decoding Webcam Stream I've been having trouble figuring out how to pass a webcam image through a Named Pipe. Already accomplished getting the Server and Client to exchange data but can't figure out how to use the libraries to actually encode and decode an image properly. Right now my Python side just shows up as a Grey Image. Hopefully you could help guide me through this problem.
Here is my C# Block Encoding a Bitmap to a ByteArray and Passing it through a named Pipe:
public byte[] encodeImage(System.Drawing.Image imageIn)
    //Helper Function for turning Bitmap images into ByteArrays
    {
        using (var ms = new MemoryStream())
        {
            imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
            return ms.ToArray();
        }
    }

public void OnFrameReceive(object sender, NewFrameEventArgs eventArgs)
    {
        byte[] image_bytes;
        Console.WriteLine("Received new frame");
        Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
        image_bytes = encodeImage(bitmap);
        writeToPipe(image_bytes);
    }

public void writeToPipe(byte[] frame)
    {
        if (server.IsConnected)
        {
            MemoryStream memoryStream = new MemoryStream();
            using (BinaryWriter writer = new BinaryWriter(memoryStream))
            {
                Console.WriteLine("Wrting to pipe");
                writer.Write(frame);
                int bufferLength = (memoryStream.ToArray().Length);
                server.Write(memoryStream.ToArray(), 0, bufferLength);
            }
            memoryStream.Close();
        }
        else
        {
            Console.WriteLine("Not connected");
        }

And here is the Python side receiving that data and trying to decode it:
def init_pipe_signal():
    print("At init_pipe_signal")
    bufferSize = 921600
    arraySize = int(math.sqrt(bufferSize))
    i = np.arange(bufferSize).reshape(arraySize, arraySize)

    fileHandle = win32file.CreateFile("\\\\.\\pipe\\Demo", win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None)

    while True:
        response, data = win32file.ReadFile(fileHandle, bufferSize)

        if response == 0:
            try:
                frame = Image.frombytes("RGB", (480,640), data, decoder_name="raw")
                frame = np.array(frame)
                cv.imshow('Test',frame)

            except ValueError:
                print("Value Error Here")

        else:
            print("No pipe data")

Any guidance or help would be appreciated!

A: Got it! For those who are looking for the answer:
Here is my C# Side
        public byte[] encodeImage(System.Drawing.Image imageIn)
    //Helper Function for turning Bitmap images into ByteArrays
    {
        using (var ms = new MemoryStream())
        {
            imageIn.Save(ms, ImageFormat.Bmp);
            return ms.ToArray();
        }
    }

    public void OnFrameReceive(object sender, NewFrameEventArgs eventArgs)
    {
        byte[] image_bytes;
        Console.WriteLine("Received new frame");
        Bitmap bitmap = (Bitmap)eventArgs.Frame.Clone();
        image_bytes = encodeImage(bitmap);
        writeToPipe(image_bytes);
    }
    public void writeToPipe(byte[] frame)
    {
        if (server.IsConnected)
        {
            MemoryStream memoryStream = new MemoryStream();
            using (BinaryWriter writer = new BinaryWriter(memoryStream))
            {

                Console.WriteLine("Wrting to pipe");
                writer.Write(frame);

                //int bufferLength = (memoryStream.ToArray().Length/32)*32;
                int bufferLength = (memoryStream.ToArray().Length);
                server.Write(memoryStream.ToArray(), 0, bufferLength);
                Console.WriteLine(memoryStream.ToArray().Length);
            }
            /*
            Not sure if Memory Stream needs to be closed here (after every Write)
            or after every time the server finishes.
            Test performance for both
            */
            memoryStream.Close();
        }
        else
        {
            Console.WriteLine("NOPE NOT CONNECTED");
        }
    }

and here is the python decoding side:
def init_pipe_signal():
    print("At init_pipe_signal")
    bufferSize = 921654
    fileHandle = win32file.CreateFile("\\\\.\\pipe\\Demo", win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None)
while True:
    response, data = win32file.ReadFile(fileHandle, bufferSize)

    if response == 0:
        try:
            frame = np.array(Image.frombytes("RGB", (640, 480), data))
            frame = np.rot90(frame, 2)
            cv2.imshow("Test", frame)
            if cv2.waitKey(1) & 0xFF == ord('q'):
                break

        except ValueError:
            print("Value Error Here")

    else:
        print("No pipe data")


text:
Q: Session has value but is not recognised I was wondering why does the Session doesn't seem to remain it's value but it actually prints its value?
I print out the the value of the Session but when I access the same page on a different tab it doesn't recognize that it has a value.
Also when the page is refreshed Session becomes null...?
And another thing I'm not sure if what I did in the Log Out button is correct
This is what I have in my LogInController.php
<?php

class LogInController extends BaseController {
    public function actionLogIn() {
        $username = Input::get('username');
        $password = Input::get('password');
        if(($username == 'batman' and $password == '12345') or ($username == 'robin' and $password == '54321')){
            Session::put('username', $username);
            return Redirect::route('welcome')
                ->with('username', $username)
                ->with('title', 'Welcome!');

        }else {
            Session::flush();
            return Redirect::to('login')
                ->with('asterisk', 'Invalid username or password')
                ->with('title', 'Login');
        }
    }
    public function actionLogOut() {
        Session::flush();
        return View::make('login.formlogin')
            ->with('title', 'Login');
    }
}

Here's routes.php
Route::get('/', function()
    { return View::make('hello'); });

Route::get('login', array('as' => 'login', function ()
    { return View::make('login.formlogin')
        ->with('title', 'Login');
    }));

Route::post('login', array('uses'=>'LogInController@actionLogIn'));

Route::get('error', array('uses'=>'LogInController@actionLogOut'));

Route::get('welcome', array('as' => 'welcome', function ()
    { return View::make('login.uservalid'); }));

formlogin.blade.php
@extends('login.login')
@section('content')

Login

    {{ Form::open(array('method'=>'post')) }}

{{ Session::get('asterisk') }}

        {{ Form::label('username', 'Username:') }}
        {{ Form::text('username') }}

        {{ Form::label('password', 'Password:') }}
        {{ Form::password('password') }}

        {{ Form::submit('Log In') }}
    {{ Form::close() }}
@endsection

uservalid.php
@extends('login.layouts')
@section('content')

    {{ Form::open(array('method'=>'get')) }}
        welcome
        {{ Session::get('username') }}

        {{ Form::submit('Log Out') }}
    {{ Form::close(0) }}

@endsection

layouts.blade.php for uservalid.blade.php

    <title></title>

    @if(Session::has('username'))
        @yield('content')
    @else
        nothing to do here
    @endif

thanks,

A: I added
<?php
$username = Session::get('username');
?>

and
{{ Session::flash('username', $username) }}

in uservalid.php
so when page is refreshed it display the same page (which is correct) and also when page is open in new window, it doesn't log out or anything now unlike before
it kinda seem iffy to me though .. any suggestion/s ?

A: Really, you should probably be using the Auth class for something like this, you'll find it handles all the session-related authentication stuff for you.


text:
Q: the prep 'when' in the perfect tense
*

*This room had been cleaned when the last tenant moved out.

*This room has been cleaned when the last tenant moved out.

Are the two sentences correct? If they are, I want to make sure that the difference between the sentences is cleaning the room before and after moving out.

A: No, it isn't.
"Has been cleaned" implies that the cleaning was recent and the room is still clean.
"Had been cleaned" implies that the room was clean at the time being referred to (but could have got dirty since).
We would assume that the cleaning happened after the tenant left, but neither sentence says so definitively. You would have to say "had already been cleaned" if it happened before.

A: The second is not idiomatic: we don't use the present perfect with an expressed point in time. We can use it with a period of time, including that expressed by "since", so:

This room has been cleaned since the last tenant moved out.

is fine.
Sentence 1 is fine: the past perfect does not have that restriction.
But, as Kate Bunting says, neither makes clear whether the cleaning was before or after the moving out. An alternative to her suggestion is

The room had been cleaned before the last tenant moved out.

The simple past "was cleaned" would also be possible here, the difference being on whether the speaker was choosing to put temporal focus on the moving out or not.


text:
Q: Workaround for equality of nested functions I have a nested function that I'm using as a callback in pyglet:
def get_stop_function(stop_key):
    def stop_on_key(symbol, _):
        if symbol == getattr(pyglet.window.key, stop_key):
            pyglet.app.exit()
    return stop_on_key

pyglet.window.set_handler('on_key_press', get_stop_function('ENTER'))

But then I run into problems later when I need to reference the nested function again:
pyglet.window.remove_handler('on_key_press', get_stop_function('ENTER'))

This doesn't work because of the way python treats functions:
my_stop_function = get_stop_function('ENTER')
my_stop_function is get_stop_function('ENTER')  # False
my_stop_function == get_stop_function('ENTER')  # False

Thanks to two similar questions I understand what is going on but I'm not sure  what the workaround is for my case. I'm looking through the pyglet source code and it looks like pyglet uses equality to find the handler to remove.
So my final question is: how can I override the inner function's __eq__ method (or some other dunder) so that identical nested functions will be equal?
(Another workaround would be to store a reference to the function myself, but that is duplicating pyglet's job, will get messy with many callbacks, and anyways I'm curious about this question!)
Edit: actually, in the questions I linked above, it's explained that methods have value equality but not reference equality. With nested functions, you don't even get value equality, which is all I need.
Edit2: I will probably accept Bi Rico's answer, but does anyone know why the following doesn't work:
def get_stop_function(stop_key):
    def stop_on_key(symbol, _):
        if symbol == getattr(pyglet.window.key, stop_key):
            pyglet.app.exit()
    stop_on_key.__name__ = '__stop_on_' + stop_key + '__'
    stop_on_key.__eq__ = lambda x: x.__name__ == '__stop_on_' + stop_key + '__'
    return stop_on_key

get_stop_function('ENTER') == get_stop_function('ENTER')  # False
get_stop_function('ENTER').__eq__(get_stop_function('ENTER'))  # True

A: the solution is to keep a dictionary containing the generated functions around,
so that when you make the second call, you get the same object as in the first call.
That is, simply build some memoization logic, or use one of the libraries
existing with memoizing decorators:
ALL_FUNCTIONS = {}
def get_stop_function(stop_key):
    if not stop_key in ALL_FUNCTIONS:
        def stop_on_key(symbol, _):
            if symbol == getattr(pyglet.window.key, stop_key):
                pyglet.app.exit()
        ALL_FUNCTIONS[stop_key] = stop_on_key
     else:
        stop_on_key = ALL_FUNCTIONS[stop_key]
    return stop_on_key

A: You could create a class for your stop functions and define your own comparison method.
class StopFunction(object):

    def __init__(self, stop_key):
        self.stop_key = stop_key

    def __call__(self, symbol, _):
        if symbol == getattr(pyglet.window.key, self.stop_key):
            pyglet.app.exit()

    def __eq__(self, other):
        try:
            return self.stop_key == other.stop_key
        except AttributeError:
            return False

StopFunciton('ENTER') == StopFunciton('ENTER')
# True
StopFunciton('ENTER') == StopFunciton('FOO')
# False

A: You can generalize Bi Rico's solution to allow wrapping any functions up with some particular equality function pretty easily.
The first problem is defining what the equality function should check. I'm guessing for this case, you want the code to be identical (meaning functions created from the same def statement will be equal, but two functions created from character-for-character copies of the def statement will not), and the closures to be equal (meaning that if you call get_stop_function with two equal but non-identical stop_keys the functions will be equal), and nothing else to be relevant. But that's just a guess, and there are many other possibilities.
Then you just wrap a function the same way you'd wrap any other kind of object; just make sure __call__ is one of the things you delegate:
class EqualFunction(object):
    def __init__(self, f):
        self.f = f
    def __eq__(self, other):
        return (self.__code__ == other.__code__ and
                all(x.cell_contents == y.cell_contents
                    for x, y in zip(self.__closure__, other.__closure__)))
    def __getattr__(self, attr):
        return getattr(self.f, attr)
    def __call__(self, *args, **kwargs):
        return self.f(*args, **kwargs)

If you want to support other dunder methods that aren't required to go through getattr (I don't think any of them are critical for functions, but I could be wrong…), either do it explicitly (as with __call__) or loop over them and add a generic wrapper to the type for each one.
To use the wrapper:
def make_f(i):
    def f():
        return i
    return EqualFunction(f)
f1 = f(0)
f2 = f(0.0)
assert f1 == f2

Or, notice that EqualFunction actually works as a decorator, which may be more readable.
So, for your code:
def get_stop_function(stop_key):
    @EqualFunction
    def stop_on_key(symbol, _):
        if symbol == getattr(pyglet.window.key, stop_key):
            pyglet.app.exit()
    return stop_on_key


text:
Q: Logging on a website with python + selenium+ I have some problem getting the code to work. I want to scrape a website. So far I have used this :
from selenium import webdriver
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
chrome_options.add_argument('--no-sandbox')
chrome_options.add_argument('--disable-dev-shm-usage')
wd = webdriver.Chrome('chromedriver',chrome_options=chrome_options)
wd.get('https://ma-mbp.ra.rockwell.com/mediabin/action/iw.ui')
time.sleep(25)
print(wd.page_source) # results

Output is always the same.
I am not able to do the logging.

I can select non element


text:
Q: Disabled RadNumericTextbox not maintaining value after postback I have this javascript code:
var RadNumericTextBox1 = $find("RadNumericTextBox1");
RadNumericTextBox1.set_value(10);
RadNumericTextBox1.disable();

After postback in VB, Me.RadNumericTextBox1.Value = 0. How can I submit the new value?

A: you can use session variables to store value instead of this
var RadNumericTextBox1 = $find("RadNumericTextBox1");
session("RadNumericTextBox1")=10;
RadNumericTextBox1.set_value(session("RadNumericTextBox1"));

you can access the value to any where till the session get abondend


text:
Q: How to autogenerate Timestamp in SQLite RoomDatabase? I was creating entity class for RoomDatabase in Android Studio To define Table. I don't know how autogenerate timestamp in Entity. Is there any annotation available like @PrimaryKey(autogenerate=true)?
@Entity(tableName = "userTable")
public class DataEntity {
    @PrimaryKey(autoGenerate = true)
    private int id;
    @NonNull
    @ColumnInfo(name = "requirement")
    private String requirement;

    @NonNull
    @ColumnInfo(name = "timestamp")
    private String timestamp;

}

A: I hope this will help
@Entity(tableName = "userTable")
public class DataEntity {
    @PrimaryKey(autoGenerate = true)
    private int id;
    @NonNull
    @ColumnInfo(name = "requirement")
    private String requirement;

    @NonNull
    @ColumnInfo(name = "timestamp")
    private String timestamp = String.valueOf(TimeUnit.MILLISECONDS.toSeconds(System.currentTimeMillis()));

}


text:
Q: Вывод определенных строк из текстового файла 1. Как поставить ограничение чтобы скрипт выводил данные с 20 - 40 строки на листе?
2. Ссылка должна увеличиваться на 1-цу
<a href="./top_100/radio_1
<a href="./top_100/radio_2
<a href="./top_100/radio_3 и т.д.
(В данном случае выводит только <a href="./top_100/radio_2
echo '
';

$fn = fopen("./top_100/radio.txt","r") or die("fail to open file");

while($row = fgets($fn)) {
  list( $sPlaylist, $sFile, $sNumber, $sArtist, $sTitle, $sCover ) = explode( "'", $row );

  $sFile  = substr("$sFile", 0, -2);

  $num = 1;
  $last = ++$num;

  echo '

	' . $sArtist . '

';
  echo  $sCover . '
';
  echo  $sFile . '

 Genres: dance top 40 trance house pop

';
}
echo '
';
fclose( $fn );

A: echo '
';
$fn = fopen("./top_100/radio.txt","r") or die("fail to open file");

$countrow=1;
$last=20; //Начальный
$limit=40; //Конечный
while(($row = fgets($fn)) && ($countrow<=$limit)) { //Пока есть строки и пока меньше лимита
if  ($last <= $countrow){//если текущий ряд больше минимального
list( $sPlaylist, $sFile, $sNumber, $sArtist, $sTitle, $sCover ) = explode( "'", $row );

$sFile  = substr("$sFile", 0, -2);

echo '

	' . $sArtist . '

';
echo  $sCover . '
';
echo  $sFile . '

 Genres: dance top 40 trance house pop

';

}
$countrow++;
}
echo '
';
fclose( $fn );

A: Самый простой вариант, на коленке (ваш код для вывода оставил оставил без изменений):
$offset = 20; #сдвиг от начала
$limit = 25; #количество записей для вывода

$i = 0;
$count = 0;
while($row = fgets($fn)) {
    $i++;
    if ($i < $offset) {
        continue;
    }
    if ($count >= $limit){
        break;
    }

    list( $sPlaylist, $sFile, $sNumber, $sArtist, $sTitle, $sCover ) = explode( "'", $row );

    $sFile  = substr("$sFile", 0, -2);

    $num = 1;
    $last = ++$num;

    echo '

	' . $sArtist . '

';
    echo  $sCover . '
';
    echo  $sFile . '

 Genres: dance top 40 trance house pop

';
    $count++;
}


text:
Q: How to associate class property with instance property I have some models for Person, TaskListitem and Task as shown below.
I am currently using BindingList to bind to datagrid to show task in datagrid. I am using it because I have to show DeveloperName and ReviewerName in the grid.
Background: this is a code from Task Tracking Program (learning project). Client is written in C#.
Server is written in Ruby. Server stores data in activerecord tables for People, Tasks.
Client also locally caches the same in sqlite DB.
Currently Globals.People is defined as
public static class Globals
{
    ...
    public static List<Person> People = new List<Person>();
    ...
}

and the classes Person, TaskListitem and Task as shown below:
public class Person : TimeStamp, IEquatable<Person>
{
    public string name { get; set; }
    public string trigram { get; set; }
    public bool active { get; set; }
    public eLevel level { get; set; }
    public string internal_object_id { get; set; }
    public string token { get; set; }
    public int unread_objects_count { get; set; }
    public int documents_count { get; set; }
    public int work_tasks_count { get; set; }
    public int review_tasks_count { get; set; }

    public bool Equals(Person obj)
    {
        ...
    }
    public override bool Equals(object obj)
    {
        ...
    }
    public override int GetHashCode()
    {
        ...
    }
}

public class TaskListItem : Task
{
    public string taskName
    {
        get { return this.name + " - " + this.title; }
    }
    public string DeveloperName
    {
        get { return Globals.People.Find(x => x.id == this.developer_id).name; }
    }
    public string ReviewerName
    {
        get { return Globals.People.Find(x => x.id == this.reviewer_id).name; }
    }
}

public class Task : TimeStamp
{
    public Task()
    {
        ...
        if (Globals.People.Count == 0) Globals.People.Add(new Person { id = 0, name = "DummyUser", level = eLevel.Master });
        developer_id = Globals.People.First().id;
        reviewer_id = Globals.People.First().id;
        ...
    }

    public TaskListItem AsTaskListItem()
    {
    ...
    }

    public int developer_id { get; set; }
    public int reviewer_id { get; set; }
    public string name { get; set; }
    public string title { get; set; }
    ...
}

But then as I was learning I found that Static object must not be used to preserve state. So I started searching for an alternative to my implementation. I was able to solve it partially by returning DeveloperName and ReviewerName along with task. So I don't have to use to Static List.
But now I am facing a problem that when I retrieve Tasks from Cache. I am unable to merge it with retrieved data of People.
How Do I Merge it. My above partial solution requires me to retrieve redundant data along with each Task (i.e. Person names with each Task as client has already retrieved all people data).
Complete Code
Please comment for suggestions and improvements.


text:
Q: Error - "Corrupt JPEG data: 214 extraneous bytes before marker" after sending image to server I am sending image to server by converting the image into base64 format. But the probelm is after sending the image string the character '+' is replacing by a blank space " ". And there is showing the error:
Corrupt JPEG data: 214 extraneous bytes before marker

How to solve the problem? Thanks in advance for the help.
Here is the image conversion code into base64 format:
-(NSString*)base64forData:(NSData*)theData {

const uint8_t* input = (const uint8_t*)[theData bytes];
NSInteger length = [theData length];

static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
uint8_t* output = (uint8_t*)data.mutableBytes;

NSInteger i;
for (i=0; i < length; i += 3) {
    NSInteger value = 0;
    NSInteger j;
    for (j = i; j < (i + 3); j++) {
        value <<= 8;

        if (j < length) {
            value |= (0xFF & input[j]);
        }
    }

    NSInteger theIndex = (i / 3) * 4;
    output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
    output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
    output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
    output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
}

return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}

Here is the code for converting into Json format & sending that into server:
-(void)setOflynData2JsonFormat{

if (!([self.getOfflineData count] == 0)) {

    NSArray *array = [self getOfflineData];

    arrayOfJsonString = [[NSMutableArray alloc]init];

    for (int i = 0; i<[array count]; i++) {

        uniqueId++;

        NSNumber *uId = [NSNumber numberWithInt:uniqueId];

        OfflineTableObject *offObj = [array objectAtIndex:i];

        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];

        [dict setValue:uId forKey:@"id"];
        [dict setValue:offObj.qrCode forKey:@"qrCode"];
        [dict setValue:offObj.offlineStatus forKey:@"activity"];
        [dict setValue:offObj.time forKey:@"time"];
        [dict setValue:offObj.imageData forKey:@"image_base64"];

        [arrayOfJsonString addObject:dict];

    }

    NSData * jsonDataFromArray = [NSJSONSerialization dataWithJSONObject:arrayOfJsonString
                                                        options:kNilOptions
                                                          error:nil];

    NSString *string = [[NSString alloc] initWithData:jsonDataFromArray encoding:NSUTF8StringEncoding];

    //replace backslash from string
    NSString *jsonString = [[NSString alloc] init];

    NSString *specialChar = @"\\";

    jsonString = [string stringByReplacingOccurrencesOfString:specialChar withString:@""];

    NSLog(@"sent string to server: %@",jsonString);

    int lng = [jsonString length];

    NSLog(@"2nd string length: %d",lng);

    Get_Object_Class *obj = [[Get_Object_Class alloc]init];

    NSString *dvid = [[UIDevice currentDevice] uniqueIdentifier];

    [obj sendDeviceId:dvid];

    NSLog(@"device id: %@",dvid);

    int check = [obj sendOfflynData2Server:jsonString];

    if (check == 1) {

        NSLog(@"Offline data uploaded");

        AppDelegate *test = [AppDelegate sharedInstance];

        [test resetOfflineTable];
    }
    else{

        NSLog(@"Offline data upload failed");
    }

}

else{

    NSLog(@"Offline table is empty");
}

}

-(BOOL)sendOfflynData2Server:(NSString *)jsonRequest{

NSHTTPURLResponse * response = nil;
NSError* error = nil;

NSString * post = [NSString stringWithFormat:@"&offline_data=%@",jsonRequest];

NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL: [NSURL URLWithString:[NSString stringWithFormat: @"%@saveofflinedata.php", APIheader]]];

[request setHTTPMethod:@"POST"];
[request setValue:jsonRequest forHTTPHeaderField:@"offline_data"];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSData *dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

NSString *stringReply = (NSString *)[[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];

stringReply = [stringReply stringByReplacingOccurrencesOfString:@"(" withString:@"["];
stringReply = [stringReply stringByReplacingOccurrencesOfString:@")" withString:@"]"];
stringReply = [stringReply stringByReplacingOccurrencesOfString:@";" withString:@""];

NSLog(@"stringReply: %@", stringReply);

SBJsonParser *parser = [[SBJsonParser alloc]init];
NSArray *array = [parser objectWithString:stringReply error:nil];
stringReply = [NSString stringWithFormat:@"%@",[[array objectAtIndex:0]objectForKey:@"success"]];

NSLog(@"Success: %@", stringReply);

return [stringReply intValue];

}

Here is the string i am sending to server:
        NSString * str1 = @"/9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAZKADAAQAAAABAAAAggAAAAD/2wBDACAWGBwYFCAcGhwkIiAmMFA0MCwsMGJGSjpQdGZ6eHJmcG6AkLicgIiuim5woNqirr7EztDOfJri8uDI8LjKzsb/2wBDASIkJDAqMF40NF7GhHCExsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsb/wAARCACCAGQDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDeprtgdQPc1FdXUdrCZJD9B3JrnZ76S4lLO5C9lB4oEb3nLu4kzTvP2981zq3gTpxT/tp65pDN2e4VogO5NQBFchiASOmaz1ud5Xmr8ByvFAF+3IEQ+UL9BUmagGUHrjpSqxIyaAJDSUmaTNADqSkzRmgBc0UlFAHOavdi4uiAconA96zi9ErZNNAyaAAtQGNTRw7u1SG1z0FA7EUU21hntWhZ3uHAJqg9uVFRAlTQI6uC7SRtpPNWhXJw3DKwcHkV0djcrcQgg80AWDSU402gABpc0YpMUALmikxRQBxZ5NSJgdqcsW1RnqalVUB56UDFS4VTjFXoJI5BzgVmTbCflqe1gdzxkCkNFyaOMr1rMnjweKnuQ0ZxnpVfexHIzQgZCCRxWnpEzLPtB4NZr9at6UcXqe9Mk6nPFApKXNMQZpM0UUgDNFJRQMwjaM3JNMOnFsDNXmfHFPVxtqTSxQFikf3j09at21xBHwPzqjfNJI21c4qBEkjQ8ZNArly9VZcslUo2Vcq3WprN2LbX71PcWIc7l60LQGrmfMgIyKk0oZv4xnvTngZEOfSm6QpOoR47VSJZ1NJRSZpki0ZpM0UgDNFJRQMx3f5qQ3IHAqGV8cDrUawljuc4FSi7kpuF3Zxk08XCMOcVGGjXgClKxsOOtMRLCqB94q6GBWsobkPHSrUUhIxUspMkmAZTVTRoz/aDnsoNWHbil0Vfmnf1OKcSZGtSUUlWQLRmkpKQC0UlFAzCdfmzSMTipWwab8o61JZAUY0qKRU4ZTS/LSuFhgNKhxSbeaUCkMczZHvWjYW/2eAA/ePJqhCu6ZR71r1cSJC0lFFMkKSijNABRSZooAwS+KYXJNPaCU87DUflSD+A/lUljg9OD81H5b/3T+VGCD0NAXJw3FOXmolRm6KT+FTLHJ/cNKw7liyXNwD6DNaNQ6fbMELMMFqtPEw6VaIZHRThE57U7yX9KBEdJU4tz3NL9m/2qBleipjbt7UUASeQnpTDaoewqeloAqm0T0FN+wx56CrlFMCBLWNewp4hQdqkooEAAHSiiigYUtFFABRRRQAUUUUANNHaiigQCloopAFFFFMYUUUUALRRRQAUUUUAFFFFAH//2Q==";

And this is the string showing in server:
    NSString *str2 = @"/9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAZKADAAQAAAABAAAAggAAAAD/2wBDACAWGBwYFCAcGhwkIiAmMFA0MCwsMGJGSjpQdGZ6eHJmcG6AkLicgIiuim5woNqirr7EztDOfJri8uDI8LjKzsb/2wBDASIkJDAqMF40NF7GhHCExsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsbGxsb/wAARCACCAGQDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4 Tl5ufo6erx8vP09fb3 Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3 Pn6/9oADAMBAAIRAxEAPwDeprtgdQPc1FdXUdrCZJD9B3JrnZ76S4lLO5C9lB4oEb3nLu4kzTvP2981zq3gTpxT/tp65pDN2e4VogO5NQBFchiASOmaz1ud5Xmr8ByvFAF 3IEQ UL9BUmagGUHrjpSqxIyaAJDSUmaTNADqSkzRmgBc0UlFAHOavdi4uiAconA96zi9ErZNNAyaAAtQGNTRw7u1SG1z0FA7EUU21hntWhZ3uHAJqg9uVFRAlTQI6uC7SRtpPNWhXJw3DKwcHkV0djcrcQgg80AWDSU402gABpc0YpMUALmikxRQBxZ5NSJgdqcsW1RnqalVUB56UDFS4VTjFXoJI5BzgVmTbCflqe1gdzxkCkNFyaOMr1rMnjweKnuQ0ZxnpVfexHIzQgZCCRxWnpEzLPtB4NZr9at6UcXqe9Mk6nPFApKXNMQZpM0UUgDNFJRQMwjaM3JNMOnFsDNXmfHFPVxtqTSxQFikf3j09at21xBHwPzqjfNJI21c4qBEkjQ8ZNArly9VZcslUo2Vcq3WprN2LbX71PcWIc7l60LQGrmfMgIyKk0oZv4xnvTngZEOfSm6QpOoR47VSJZ1NJRSZpki0ZpM0UgDNFJRQMx3f5qQ3IHAqGV8cDrUawljuc4FSi7kpuF3Zxk08XCMOcVGGjXgClKxsOOtMRLCqB94q6GBWsobkPHSrUUhIxUspMkmAZTVTRoz/aDnsoNWHbil0Vfmnf1OKcSZGtSUUlWQLRmkpKQC0UlFAzCdfmzSMTipWwab8o61JZAUY0qKRU4ZTS/LSuFhgNKhxSbeaUCkMczZHvWjYW/2eAA/ePJqhCu6ZR71r1cSJC0lFFMkKSijNABRSZooAwS KYXJNPaCU87DUflSD A/lUljg9OD81H5b/3T VGCD0NAXJw3FOXmolRm6KT FTLHJ/cNKw7liyXNwD6DNaNQ6fbMELMMFqtPEw6VaIZHRThE57U7yX9KBEdJU4tz3NL9m/2qBleipjbt7UUASeQnpTDaoewqeloAqm0T0FN wx56CrlFMCBLWNewp4hQdqkooEAAHSiiigYUtFFABRRRQAUUUUANNHaiigQCloopAFFFFMYUUUUALRRRQAUUUUAFFFFAH//2Q==";

A: Your + signs aren't URL encoded in the post data even though your content type says they are.
You'll need to replace them by %2B for the recipient to get them correctly.

A: Why not just convert your UIImage into NSData and your NSData to base64?
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
NSString *base64string = [imageData base64EncodedString];

Just implement one of many NSData categories like this one: https://github.com/l4u/NSData-Base64


text:
Q: Testing services along with controller and API routes I currently use jasmine with karma to unit test my Angular controllers. I use JSON fixtures with mock data rather than relying on my actual services to make API calls.
Separately I test my API endpoints using jasmine-node.
My question is, do I need to also test my services in order to have a solid test suite? I feel like it would be overkill as all that is in my services are very simple $resource GET methods, and testing $resource is obviously not something which is necessary.


text:
Q: How to get the url name on which the application is running? I have a Plolty Dash application which is running on localhost. I will be making it live and give a specific domain name. What I want to achieve is to get the url name on which the application is running. For instance, if it is running on localhost:8050, I want a Python script to grab that specific url and store it in a variable inside the application. Is there any way I can achieve this? I have searched the internet but what I get is Webscraping tutorials. I want the script to automatically detect the url on which it is running. Thank you for any help.

A: You need to add a Location() element from Dash Core Components to your layout. You then create a callback which takes that elements as an input and the URL information will be passed into the callback.
Here is a minimal example:
import dash_core_components as dcc
from dash import Dash, html, Input, Output

app = Dash()
app.layout = html.Div(
        children=[
            dcc.Location(id='uri', refresh=False),
            html.P(id='url-display')
        ]
    )

@app.callback(
    Output('url-display', 'children'),
    Input('uri', 'href')
)
def process_location(uri):
    return uri

if __name__ == "__main__":
    app.run_server(debug=False)


text:
Q: Installing 15.04 on 32 bit machine under VMWare Workstation 10 I am trying to install ubuntu 15.04 on a laptop running VMware workstation 10.  It is a 32bit machine with 1GB memory (Yes it's really old).  I get through the install without issue and system boots up to login gui.  When I type in my password to login it starts like it is opening the desktop. Cursor spins then screen goes black and pops back up to login again.  I know that I have the password right.  Any ideas how to get past this?    I also tried installing 14.04.3 and got the same exact results

A: Please check {HERE} and see if your Laptop meets the minimum requirements. Unless it a custom built, or modified, I believe your Laptopt is what I would refer to as jurassic, and will not be able to run Ubuntu.


text:
Q: Name excel sheets with variables in VBA I am trying to write a program in VBA that takes up to 22 user inputs and creates and names a sheet for every input.
I have a Userform that sets the variable to nothing when it initializes.  I am having issues trying to:

*

*create a new sheet only if the user puts anything in that variable and

*Naming the sheet with their input.

Here is what I have so far
Public Part(1 to 22) as String

 Sub Start()

Application.ScreenUpdating = False

For i = 1 To 22
    If Part & i = "" Then

    Else
        Sheets.Add , after:=Worksheets(Worksheets.Count - 2)
        ActiveSheet.Name = Part & i
    End If

Next i

Application.ScreenUpdating = True

End Sub

Here is where the values are added to the variable. PartNumber1 - 22 are names of textboxes on the user form
    Private Sub UserForm_Initialize()

PartNumber1.Value = ""
PartNumber2.Value = ""
PartNumber3.Value = ""
PartNumber4.Value = ""
PartNumber5.Value = ""
PartNumber6.Value = ""
PartNumber7.Value = ""
PartNumber8.Value = ""
PartNumber9.Value = ""
PartNumber10.Value = ""
PartNumber11.Value = ""
PartNumber12.Value = ""
PartNumber13.Value = ""
PartNumber14.Value = ""
PartNumber15.Value = ""
PartNumber16.Value = ""
PartNumber17.Value = ""
PartNumber18.Value = ""
PartNumber19.Value = ""
PartNumber20.Value = ""
PartNumber21.Value = ""
PartNumber22.Value = ""

End Sub

Private Sub PartNumDone_Click()

Part(1) = PartNumber1.Value
Part(2) = PartNumber2.Value
Part(3) = PartNumber3.Value
Part(4) = PartNumber4.Value
Part(5) = PartNumber5.Value
Part(6) = PartNumber6.Value
Part(7) = PartNumber7.Value
Part(8) = PartNumber8.Value
Part(9) = PartNumber9.Value
Part(10) = PartNumber10.Value
Part(11) = PartNumber11.Value
Part(12) = PartNumber12.Value
Part(13) = PartNumber13.Value
Part(14) = PartNumber14.Value
Part(15) = PartNumber15.Value
Part(16) = PartNumber16.Value
Part(17) = PartNumber17.Value
Part(18) = PartNumber18.Value
Part(19) = PartNumber19.Value
Part(20) = PartNumber20.Value
Part(21) = PartNumber21.Value
Part(22) = PartNumber22.Value

End Sub

Thanks!

A: Use arrays.  Here is an example.  PseudoUserform() is run first:
Public Part(1 To 22) As String

Sub PseudoUserform()
    Part(6) = "James"
    Part(8) = "Ravenswood"
End Sub

Sub Start()
Application.ScreenUpdating = False
For i = 1 To 22
    If Part(i) = "" Then
    Else
        Sheets.Add after:=Worksheets(Worksheets.Count - 2)
        ActiveSheet.Name = Part(i)
    End If
  Next i
Application.ScreenUpdating = True
End Sub


text:
Q: Why do Markov matrices converge to the same vector after infinite steps irrespective of the starting vector? Can anyone explain me the reason why does any probability vector U0 converge to the same vector Uinfinity when a Markov matrix is acted on it?
I don't know how to put this but let me try.
If x1 and x2 are two Eigenvectors and the Eigenvalues are 1 and 0.75.
In the equation
U0 = C1  x1 + C2  x2
Why do I get the same value of C1 irrespective of any probability vector U0 to converge to the same steady state?. Hope this makes sense. Thanks!

A: To expand on Ian's comments, you can view the action of a matrix on a vector in the following way: if $\mathbf v$ is an eigenvector of the matrix with eigenvalue $\lambda$, then multiplying a vector $w$ by the matrix multiplies the component of $w$ in the $v$-direction by $\lambda$. For a stochastic matrix, $|\lambda|\le1$, so repeated applications of the matrix will cause the components of the initial probability vector that are in the directions with $|\lambda|\lt1$ to shrink away. What's left will be the components in directions where the eigenvalue is $\pm1$. For the simple type of Markov chain under consideration, the eigenspace is one-dimensional (and we won't have $\lambda=-1$), so we'll be left with the steady-state vector.
To see why the last statement might hold, consider the $2\times2$ case. We have $$P=\pmatrix{p&1-p\\q&1-q}$$ with eigenvalues $\lambda_1=1$ and $\lambda_2=p-q$. Observe that $|\lambda_2|\lt1$ unless $p=0$ and $q=1$ or vice-versa. The corresponding eigenvectors are $\mathbf v_1=\left({q\over1-p+q},{1-p\over1-p+q}\right)$ and $\mathbf v_2=(-1,1)$. (We've normalized $v_1$ so that its components sum to $1$.) Now, any probability vector $\mathbf v$ lies on the line segment joining $(1,0)$ to $(0,1)$, so it can be written in the form $\mathbf v=\mathbf v_1+\alpha\mathbf v_2$, so $P^n\mathbf v=\mathbf v_1+\lambda_2^n\alpha\mathbf v_2$, which clearly converges to $\mathbf v_1$ as $n\to\infty$.
The situation is similar for larger state spaces: probability vectors lie on the hyperplane $\mathbf v\cdot\mathbf 1=1$, and we can choose eigenvectors of $1$ which lie on this hyperplane. Any initial probability vector can be written as a linear combination of eigenvectors, and under repeated application of $P$ the components corresponding to $|\lambda|\lt1$ will "fade away," leaving only the components for which $|\lambda|=1$.


text:
Q: Laravel SoftDelete, delete and Update not working I'm trying to use Laravel REST API and I came across this problem. I can't seem to delete, forceDelete or even updating this model (haven't tried with any other model).
Model:
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Multimedia extends Model
{
    use SoftDeletes;

    protected $fillable = ['Path', 'Type'];

    protected $dates = ['deleted_at'];

    public function category()
    {
      return $this->belongsTo('App\Categories');
    }
}

Controller:

namespace App\Http\Controllers;
use App\Multimedia;
use Request;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\File;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Log;
use Carbon;

class MultimediaController extends Controller
{
    public function delete(Multimedia $multimedia)
{

    //Option 1
    $multimedia->delete();
    return response()->json(null, 204);

    //Option 2
    $multimedia->forceDelete();
    return response()->json(null, 204);

    //Option 3
    $multimedia->updated_at = Carbon::now();
    $multimedia->deleted_at = Carbon::now();
    $multimedia->update();
    return response()->json(null, 204);

    //Option 4
    DB::delete('DELETE FROM multimedia WHERE ID=' . $multimedia->ID);
    return response()->json(null, 204);

    //Option 5 (In response to suniti yadav) THIS ONE WORKS.
    $multimedia->where('id', '=', $multimedia->ID)->delete();
    return response()->json(null, 204);
}
}

Only option 4 works (it is equivalent as a Force Delete). In Option 1 and 3, if I send the $multimedia object onto the JSON, I can see the updated_at and deleted_at are set to current time.
Routes:
Route::delete('multimedia/{multimedia}', 'MultimediaController@delete');

Any Ideias?
Thanks!
EDIT: I implemented this on two migrations
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateMultimediaTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('Multimedia', function (Blueprint $table) {
            $table->increments('ID');
            $table->string('Path', 200)->unique();
            $table->enum('Type', ['Image', 'Video'])->default('Image');
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('multimedia');
    }
}

Migartion 2
<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddCategoryOnMultimedia extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('Multimedia', function (Blueprint $table) {
            $table->string('Category', 200);
            $table->foreign('Category')->references('Name')->on('Categories');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        //
    }
}

EDIT 2: Added a picture of a registry from PHPMyAdmin

EDIT 3: I continue experiencing this problem event after the answer of suniti yadav
I have this on another controller:
public function store(Request $request)
{
    $price = new Prices();
    $price['Price'] = $request->input('Price');
    $price['FromDate'] = date_create($request->input('FromDate'));
    if($request->has('ToDate'))
        $price['ToDate'] = date_create($request->input('ToDate'));
    $price['Type'] = $request->input('Type');

    if($price['Type'] == 'Regular')
    {
        $lastRegularPrice = Prices::where('Type', '=', 'Regular')->orderBy('FromDate', 'DESC')->take(1)->get()->first();
        $priceDate = Carbon::parse($price['FromDate']);
        //return response()->json($lastRegularPrice, 406);

        if($priceDate->lte($lastRegularPrice->FromDate))
        {
            $error["error"] = "Cannot add new 'Regular' price starting from " . $priceDate->toDateString() . " due to being before the current 'Regular' price starting from " . $lastRegularPrice->FromDate->toDateString();
            $error["status"] = 406 ;
            return response()->json($error, 406);
        }

        $priceDate->subDay();
        $lastRegularPrice->ToDate = $priceDate;
        $lastRegularPrice->save();
    }
    else if($price['Type'] == 'Promo')
    {

    }
    $price->save();
    return response()->json($price, 201);
}

the variable lastRegularPrice is never updated on the database. Any Help?

A: You have not mentioned 'id' to which record you want to delete or update.
//Option 1
$multimedia->where('id', '=', $multimedia->ID)->delete();

//Option 1 or 2

    $m = $multimedia->withTrashed()->findOrFail($multimedia->ID);
    if(!m->trashed()){
      $m->delete();
    }
    else {
      $m->forceDelete();
    }

//Option 2
    $multimedia->where('id', '=', $multimedia->ID)->forceDelete();

 //Option 3

    $data = [
       'updated_at' => Carbon::now(),
       'deleted_at' => Carbon::now()
   ];

    $multimedia->where('id', '=', $multimedia->ID)->update($data);

Hope this will work for you.


text:
Q: genetic algorithm - fitness function I'm trying to wrap my head around genetic algorithms and neural networks and have seen several videos on the web. Some of them are pathfinding algorithms like the mouse that searches the cheese.
The fitness function gives a sort of score to each mouse to rate how they are performing.  in an empty room the distance from the mouse to the cheese would be a good indicator of the fitness score because they can "see" the cheese and have to learn to go there.. But, in a room filled with boxes, what would be a good fitness function? the distance would assume that they know in what direction to go, because if I give a score to those that reduce the distance then eventually all mice will go in that direction... If I move the cheese to another location they will go crazy... Simply the distance they moved is also not good, becuase one that is moving in circles would have a high score...
What would be a good fitness function for this problem?

A: Are you sure you are not mixing genetic algorithms with traditional pathfinding algorithms? Both have sort of a fitness function. In the case of pathfinding, "heuristic" is often what it's called. For those algorithms, the "fitness" has to be assumed to use while executing the algorithm (or more like to speed it up).
The fitness function in actual genetic algorithms is relatively exact but that's because it is usually more of an evaluation.
For example you perform the simulation with the current values and compute how long it took for the mouse to find the cheese. That time or distance traveled is the inverse fitness (inverse because larger number means less fit).
If the fitness was better than previous runs, you can branch off new simulations with slightly different settings (generated via mutation, randomness etc.) and evaluate each time what improves the fitness and what doesn't (-> Survival of the fittest). If the fitness was worse, give this branch up (or maybe keep it only every XX times you encounter a bad branch; "possibly it is on a good way").

A: Number of steps required to reach the cheese perhaps?
Notice that your problem is clasically solved with the A* algorithm which is not evolutionary. It does use an heuristic to have a hint on how good is a position.
However, a fitness function should aim to optimize your end result, but you don't necessarily need to have it's "correct" or "best" value before hand. Just find something that you know works on "the more the better" or "the less the better" basis.


text:
Q: Where are the UITableViewCell's initialized? I've created my own CustomTableView and CustomCell. The cell is in a xib, and I'm registering it when initializing the tableView, like this:
[self registerNib:[UINib nibWithNibName:@"CustomCell" bundle:nil]
                    forCellReuseIdentifier:kCustomCellIdentifier];

If I don't do this, I won't be able to define what ReuseIdentifier should "point" to this class. This is my cellForRow:
-(UITableViewCell *)tableView:(UITableView *)tableView
                        cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *cell = [self dequeueReusableCellWithIdentifier:
                        kCustomCellIdentifier forIndexPath:indexPath];

    if(!cell)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"CustomCell"
                        owner:self options:nil] objectAtIndex:0];

        cell.delegate = self;
        [cell initialSetup]; //Other stuff
    }
    else
        [cell resetCell];

    //And other awesome stuff

    return cell;
}

This 'works'. When I lauch my app, my own custom cells are showing.
However, it turns out the cell is NEVER returned as nil from [self dequeue... Thus, the if-statement if(!cell) is never true. I have additional setup inside this statement that I want to perform, but I don't know where the cell's are being initialized the first time now. If I remove registerNib, then this statement is true, but then it's true for all cells, and none will ever be dequeued.
I can probably work around this, and put my initialSetup (and other stuff) inside the -(id)initWithCoder..-method in the CustomCell-class, but I'd like to know where my cells are being initialized right now. Why do my cells exist before cellForRowAtIndexPath?

A: When you register a class or a nib in a table view using method registerClass:forCellReuseIdentifieror registerNib:forCellReuseIdentifier the tableview internally will create an instance of the cell if no one is available when you call dequeueReusableCellWithIdentifier:, so initialization code is no longer needed inside the delegate.
From the UITableView.h code:
// Beginning in iOS 6, clients can register a nib or class for each cell.
// If all reuse identifiers are registered, use the newer -dequeueReusableCellWithIdentifier:forIndexPath: to guarantee that a cell instance is returned.
// Instances returned from the new dequeue method will also be properly sized when they are returned.
- (void)registerNib:(UINib *)nib forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(5_0);
- (void)registerClass:(Class)cellClass forCellReuseIdentifier:(NSString *)identifier NS_AVAILABLE_IOS(6_0);

Depending of the which register method is used the init methods called are:

*

*initWithStyle:reuseIdentifier for cells registered using registerClass:

*initWithCoder: for cells registered using registerNib:
If you are using registerNib: you can use too awakeFromNib method in the cell, that is also a good place to put initialization code of the cell. The main difference between using initWithCoder: or awakeFromNib its explained in this question.
When a cell is reused, you have the method prepareForReuse in the cell to make some cleanup in the cell and left it prepared to be configured again.
A good approach to work with all of this will be:
//ViewController code

- (void)viewDidLoad
{
    ...
    [_tableView registerNib:[UINib nibWithNibName:@"CellSample" bundle:Nil] forCellReuseIdentifier:@"cellIdentifier"];
    ...
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
   //configure the new cell, no if (!cell) needed
   return cell;
}

//Cell code

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        //You can put initialization here
    }
    return self;
}

- (void)awakeFromNib
{
    [super awakeFromNib];
    //But is better initialize here
}

- (void)prepareForReuse
{
    //Reuse and reset the cell here
}

Hope it helps

A: When using dequeueReusableCellWithIdentifier: forIndexPath: you don't have to alloc the cell like you would if you were using default UITableViewCell. In your custom UITableViewCell subclass, this is called when it is initialized:
- (void)awakeFromNib {
     [super awakeFromNib];
}

So add that in there and you should be good.

A: - (instancetype)initWithStyle:(UITableViewCellStyle)style
              reuseIdentifier:(NSString *)reuseIdentifier{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
    //custom your cell
    }
    return self;
  }


text:
Q: NoFlo async components and data races In NoFlo I often come across components like this:
noflo = require 'noflo'

class Foo extends noflo.AsyncComponent
  constructor: ->
    @inPorts = new noflo.InPorts
      main:
        datatype: 'int'
        description: 'Main async input'
        required: true
      sup1:
        datatype: 'string'
        description: 'Supplementary input #1'
        required: true
      sup2:
        datatype: 'int'
        description: 'Supplementary input #2'
        required: true
    @outPorts = new noflo.OutPorts
      out:
        datatype: 'object'
        description: 'Result object'
      error:
        datatype: 'object'

    @sup1 = null
    @sup2 = null

    @inPorts.sup1.on 'data', (@sup1) =>
    @inPorts.sup2.on 'data', (@sup2) =>

    super 'main', 'out'

  doAsync: (main, callback) ->
    unless @sup1 and @sup2
      return callback new Error "Supplementary data missing"

    # Combine data received from different sources
    result =
      main: main
      sup1: @sup1
      sup2: @sup2

    # Reset state until next iteration
    @sup1 = null
    @sup2 = null

    # Send the result
    @outPorts.out.send result
    @outPorts.out.disconnect()

    callback()

exports.getComponent = -> new Foo

It assumes that all 3 input connections are synchronized somehow despite the fact that network consists mostly of async components. Consider this situation: Foo waits for main to come and receives sup1 and sup2 packets, but then next sup1 packet arrives which should be combined with next main, while still waiting for previous main to come. The result will be a complete mess on more or high data throughput.
Do NoFlo async components have any means of data races protection or it is all up to component designers?
There are 2 sides of the problem here: synchronizing inputs and maintaining internal state. Internal state is more or less protected here by that fact Node.js is not multithreaded and nothing will try to access state variables until previous doAsync() handler finishes. But syncing inputs is still a question.

A: As it turns out for NoFlo v0.5.1, there are no built-in aids against data races and component designers have to care about it themselves.
For asynchronous components that means:

*

*If data from multiple inports is required, make sure it arrives from all the ports before processing. See Components & Ports toolbox.

*Reset component's state from iteration to iteration to ensure no "memory" side effects take place.

*Protect component's internal state from a data race by preceding it with a Throttle component and connecting component's LOAD outport with Throttle's LOAD inport.

A: With recent version of NoFlo, the recommended way is to use noflo.helpers.WirePattern, and syncronize using groups.


text:
Q: how to change order of R plotly hover labels with "x unified" mode I'm looking to see if there's a way to change the order of the hoverlabels when using hovermode = "x unified" in the newest version of the R package of plotly (4.9.3).  Alternatively, is it possible to revert back to the way the old version of plotly displayed the hoverlabels while still using the current version of the plotly package?  From a data visualization perspective, the old way is much clearer in my opinion.
I've included a minimum reproducible example below.  When I run this using plotly v4.9.2.1, I get the result shown in Figure A and when I run it in plotly v4.9.3, I get the result shown in Figure B.  The benefits to Figure A over Figure B are:

*

*Figure A labels are in descending order relative to the data on each line at the time specified.  Also this is reactive to the time period, so if one line moves above another at a different time period, the relative positioning of the label also moves to reflect the ordering of the data. You can see in Figure B that the dark green (y1) line has the lowest value (66) yet it is shown at the top of the hoverlabel box.  In figure B, the y1 label is at the bottom.

*Figure A labels are attached to the individual lines, so its easier to see the hovertext as it applies to the line in question

Figure A:

Figure B:

Code:
library(plotly)
library(tidyr)

df <- data.frame(Date = seq(as.Date("2018-01-01"),
                         as.Date("2021-01-01"),
                         by = "months"),
                 stringsAsFactors = F)
df$y1 <- seq(0, 100, length.out = nrow(df))
df$y2 <- seq(0, 600, length.out = nrow(df))
df$y3 <- seq(0, 300, length.out = nrow(df))
df$y4 <- seq(0, 200, length.out = nrow(df))
df <- df %>%
  pivot_longer(cols = -Date,
               names_to = "yname",
               values_to = ) %>%
  arrange(yname, Date)

mycols <- c("#006633", "#70AD47", "#1F4E78", "#2F75B5", "#C65911", "#EF8C4F",
            "#C00000", "#FF8B8B", "#7030A0", "#9966FF")
mycols <- mycols[1:length(unique(df$yname))]

p <- plot_ly()

p <- p %>%
  add_trace(data = df,
            x = ~Date,
            y = ~value,
            text = ~yname,
            hovertemplate = paste('%{text}',
                                  '
%{x}',
                                  '
%{y}',
                                  '<extra></extra>'),
            color = ~yname, colors = mycols,
            name = ~yname, yaxis = "y",
            type = "scatter", mode = "lines",
            showlegend = T)

p <- p %>%
  layout(hovermode = "x unified",
         legend = list(x = 1.12, y = .5, xanchor = "left"),
         yaxis = list(fixedrange = T),
         xaxis = list(title = "",
                      fixedrange = T,
                      hoverformat = "%b %d, %Y"),
         showlegend = T)
p

A: Two answers:

*

*the ordering of traces in the unified hoverlabel is always the same, regardless of the relative Y values of the traces. The order is the same as in the legend, so it will follow the ordering of the colors.

*You can revert to the previous behavior with hovermode = "x" rather than hovermode = "x unified"