text:
Q: Vue unit test - dynamic components & child components & require.context I am entering the world of application testing and I have some doubts about how to test, mainly because of the child components.
Basically, the first tests I'm trying to run is to cover whether the listing pages have the right data.
During this test 3 problems are happening to me.
First problem

require.context is not a function

In the settings of the vue-router I have the import of the middleware of each route dynamically, and when running the test this error appears to me. Is there any way to resolve this?
Config vue-router
...

const resolveMiddlewares = ( requireContext ) => {
    return requireContext.keys()
        .map(file =>
            [file.replace(/(^.\/)|(\.js$)/g, ''), requireContext(file)]
        ).reduce((guards, [name, guard]) => ({
            ...guards, [name]: guard.default
        }), {})
}

...

const routeMiddlewares = resolveMiddlewares( require.context( './middlewares', false, /.*\.js$/ ) );

If I comment this line const routeMiddlewares = ... the test continues, and the second problem arises.
Second problem

[vue-test-utils]: find did not return .table__users__col__1, cannot call text() on empty Wrapper

I am trying to replicate the structure of the components that are used for a listing. As you can see below, the structure is as follows. I have a parent component, baseTable, which will have two child components, columnHeader, which will fill the headers of the table and another that will be called dynamically, according to the route the user is navigating. In this example, imagine that the route is from the users page.
components structure
baseTable
  |- columnHeader
  |- rowRoute

In the test I am doing the following:
import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
import baseTable from '@/components/bundles/tables/baseTable';
import getters from '@/store/modules/globals/user/getters';
import actions from '@/store/modules/globals/user/actions';

const localVue = createLocalVue();
localVue.use( Vuex );

describe( 'Lists', () => {

    it( 'Users list', () => {
        // mock users
        const users = [{
            id: 1,
            name: 'User 1',
            email: 'user@email.com',
            role: 'Admin'
        }];

        const wrapper = shallowMount( baseTable, {
            propsData: {
                url: 'users',
                headers: [ null, 'name', 'email', 'role' ],
                fields: users,
                row: 'Users',
            },
            stubs: [ 'router-link' ],
            mocks: {
                $t: ( msg ) => msg
            },
            getters,
            actions
        });

        console.log( wrapper.html() );

        // validates if the fields are being filled in the appropriate places.
        // table__users__col__1 - class from dynamic child ( rowUsers ).
        expect( wrapper.find( '.table__users__col__1' ).text() ).toBe( user.name );
        expect( wrapper.find( '.table__users__col__2' ).text() ).toBe( user.email );
        expect( wrapper.find( '.table__users__col__3' ).text() ).toBe( user.role );
    })

})

I noticed that the log that is in the code, just returns me the HTML of the parent component, baseTable and I don't know if that's why the problem exists.
Third problem

*

*[Vue warn]: Error in created hook: "TypeError: Cannot read property 'dispatch' of undefined"

*[Vue warn]: Error in render: "TypeError: Cannot read property 'getters' of undefined"

This is because in the rowUsers component I have a child component, baseAvatar, in which the avatars are stored in the store, in order to avoid unnecessary requests.
I tried to get getters and actions through the wrapper, however it didn't work.
Test:
import { shallowMount, createLocalVue } from '@vue/test-utils';
import Vuex from 'vuex';
import getters from '@/store/modules/globals/user/getters';
import actions from '@/store/modules/globals/user/actions';
import rowUsers from '@/components/dynamic/tables/rowUsers';

const localVue = createLocalVue();
localVue.use( Vuex );

describe( 'List', () => {

    it( 'User list', () => {
        // mock user
        const user = {
            id: 1,
            name: 'User 1',
            email: 'user@email.com',
            role: 'Admin'
        };

        const wrapper = shallowMount( rowUsers, {
            propsData: {
                url: 'users',
                headers: [ null, 'name', 'email', 'role' ],
                row: user,
            },
            stubs: [ 'router-link' ],
            mocks: {
                $t: ( msg ) => msg
            },
            getters,
            actions
        });

        // validates if the fields are being filled in the appropriate places.
        expect( wrapper.find( '.table__users__col__1' ).text() ).toBe( user.name );
        expect( wrapper.find( '.table__users__col__2' ).text() ).toBe( user.email );
        expect( wrapper.find( '.table__users__col__3' ).text() ).toBe( user.role );
    })

})

If i comment on the import of the baseAvatar component in the rowUsers component, the test passes and gives me ok.
some help?


text:
Q: xslt how to generate sequence of untyped atomic? I have a loop like so in a template:
    <xsl:variable name="seq">
        <xsl:sequence select="1"/>
        <xsl:sequence select="2"/>
        <xsl:sequence select="3"/>
        <xsl:sequence select="4"/>
        <xsl:sequence select="5"/>
    </xsl:variable>

    <xsl:for-each select="$seq">
        <xsl:text>(</xsl:text>
        <xsl:value-of select="."/>
        <xsl:text>)</xsl:text>
    </xsl:for-each>

I want to iterate once over each element of $seq, producing:
(1)
(2)
(3)
(4)
(5)
Instead this code produces (1 2 3 4 5)
How can I create a proper sequence?
Thanks!

A: Well
<xsl:variable name="seq" select="1,2,3,4,5"/>

<xsl:value-of select="for $i in $seq return concat('(', $i, ')')" separator=" "/>

should do. Or what do you want to achieve? For your approach doing
<xsl:variable name="seq" as="item()*">
        <xsl:sequence select="1"/>
        <xsl:sequence select="2"/>
        <xsl:sequence select="3"/>
        <xsl:sequence select="4"/>
        <xsl:sequence select="5"/>
    </xsl:variable>

might improve things but looks rather complicated if all you want is a sequence.

A: A variable with contained instructions and no as attribute, like this:
<xsl:variable name="seq">
    <xsl:sequence select="1"/>
    <xsl:sequence select="2"/>
    <xsl:sequence select="3"/>
    <xsl:sequence select="4"/>
    <xsl:sequence select="5"/>
</xsl:variable>

represents a document node, in this case a document node containing a single text node whose string content is "1 2 3 4 5". If you want a sequence of five integers, either use the select attribute, or write
<xsl:variable name="seq" as="xs:integer*">
    <xsl:sequence select="1"/>
    <xsl:sequence select="2"/>
    <xsl:sequence select="3"/>
    <xsl:sequence select="4"/>
    <xsl:sequence select="5"/>
</xsl:variable>

redpajama_set_name: RedPajamaStackExchange


text:
Q: How bad is it to run Flask without a secret key? I'm using Flask to build a REST API.
I noticed that it didn't complain when I launched the app with no secret_key. Even in production mode.
I thought Flask used to complain in this case. Maybe I'm confused with another warning.
Anyway, what could be the consequences?
Can this trigger exceptions at runtime?
The API doesn't use sessions at all, so I don't see what it could need a secret key for.

A: As long as sessions are not used, Flask won't complain and there is no need for a secret key.
When a secret key is needed, Flask will crash at runtime if none is provided.
There is no security risk with providing no secret key in the sense of the concern expressed in the question (Flask lowering security due to the missing key). The worst that can happen is seeing the application crash at runtime.


text:
Q: batch file stops after cvs checkout I am just writing a small batch file that should checkout a module and build it using maven. But the batch file exits/stops after running the cvs checkout command. Below is the batch file contents.
call rmdir /S /Q C:\temp\project_folder
call cvs -q -d %CVSROOT% checkout -d C:\temp\project_folder module\workspace\project_folder
call cd C:\temp\project_folder
call mvn clean install

Any idea what I am doing wrong here?

A: The use of call is for generating a callback to the currently running batch file.  If you were to call another batch file without the call command it will transfer control to the new batch file and will not record where it came from.  With the call command it will remember what line of the batch file was executed and when the called batch file exits it will continue execution at the next line of the parent file.


text:
Q: Ionic IonRefresher render TypeError is not a function Here is my code :

class Calendar extends React.Component<{},State> {

  componentDidMount() {
    this.fetchCalendarApi(); //>> Working
  }
  fetchCalendarApi(){
     //Doing my API call here
  }
  doRefresh(event: CustomEvent<RefresherEventDetail>){
    console.log('Begin async operation');
    setTimeout(() => {
      console.log('Async operation has ended');
      this.fetchCalendarApi(); //>> Not working
      event.detail.complete();
    }, 2000);
  }
 renderCal(){
    return (
      <IonPage>
        <IonContent>

          <IonRefresher slot="fixed" onIonRefresh={this.doRefresh}>
            <IonRefresherContent></IonRefresherContent>
          </IonRefresher>
        </IonContent>
     </IonPage>
    )
  }
}

And I have this error when I actually use the pull refresh :

TypeError: this.fetchCalendarApi is not a function at [...]

Thanks

A: You need to change your doRefresh function to Arrow function:
doRefresh = (event: CustomEvent<RefresherEventDetail>) => {
    console.log('Begin async operation');
    setTimeout(() => {
      console.log('Async operation has ended');
      this.fetchCalendarApi(); //>> Not working
      event.detail.complete();
    }, 2000);
  }

The issue was because you were using the normal function and hence it was not able to get the fetchCalendarApi() function as it is not within the scope. By using the arrow function, this will refer to Class in which the method is defined.


text:
Q: Definition of Dual-Pairing
Let $V$ be an $\mathbb{K}$-Vectorspace with basis $B :=(b_i)_{i \in
 I}$ and $B^* = (b_i^*)_{i \in I}$ corresponding dual basis. Let $\Phi:
 V \rightarrow V^*$ the isomorphism defined as $\Phi(v_i) = v_i^*$.
The map:
$$ \pi: V \times V^* \rightarrow \mathbb{K}, \,\,\,\,\,\,(v, \,f)
 \mapsto f(v) $$
is called the dual pairing of $V$. Let $$ \gamma_B: V \times V
 \rightarrow \mathbb{K}, \,\,\,\,\,\,(v, \,w) \mapsto \pi(v, w^*) $$
Show that $\gamma_B$ is a perfect, symmetrical bilinear form.  What is
  $\gamma_B$ in the case of $V := \mathbb{R}^n$ and $B := (e_1, \dots,
 e_n)$?

I was able to show that $\gamma_B$ is a perfect, symmetric bilinear form. But I don't quite understand what is meant by

What is $\gamma_B$ in the case of $V := \mathbb{R}^n$ and $B := (e_1, \dots,
 e_n)$?

A: Let us consider $v,w \in V$, and let us compute $\gamma_B(v,w)$ step by step.
$\gamma_B(v,w) = \pi(v,w^*) = w^*(v).$
But recall that $w^*$ was defined in the following way : the isomorphism sends $b_i$ to $b_i^*$ (the linear form which sends $b_i$ to $1$ and the other $b_j$ to $0$)
So let us write $v = \sum_{i=1}^n v_ib_i$ and $w = \sum_{i=1}^n w_ib_i$ the decomposition of $v,w$ in the basis $B$. You then have $w^* = \sum_{i=1}^n w_ib_i^*$ so that
$\gamma_B(v,w) = \sum_{i=1}^n w_ib_i^*(v) = \sum_{i=1}^n w_iv_i = (v|w)$
where $( \cdot |\cdot)$ is just the usual inner product on $\mathbb{R}^n$ : which was the special thing to notice in this case.


text:
Q: $\cos z=\cosh 2$ all solutions for z $\cos z = \frac{e^{iz} + e^{-iz}}{2}$, $\cosh 2 = \frac{e^{2} + e^{-2}}{2}$, $z = x + iy$
We can see that $e^{iz} = e^{2} \implies e^{ix -y} = e^{2} \implies e^{-y}(\cos x + i \sin x) = e^2$
So then obviously $y = -2$, $x = 0 + 2 \pi k$
Finally I get $z = 2 \pi k -2i$ but the book has $z = 2 \pi k \pm 2i$
What am I missing?

A: If $u+\frac{1}{u} = v+\frac{1}{v}$ then $u=v$ or $u=\frac{1}{v}$.
You have $u=e^{iz}$ and $v=e^2$. You've only considered $u=v$.


text:
Q: boost::asio::io_service::post - how to move std::unique_ptr into a handler function I'm trying to use boost::asio::io_service::post with std::unique_ptr in lambda-capture of the handler. But the post handler needs to be copy-constructed for later execution. Thus, as far as I understand the msgPtr value of type std::unique_ptr in the lambda-capture as well needs to be copied, even though I'm trying to move-construct it in the lambda-capture.
But the copy constructor in the unique_ptr is deleted, which makes complete sense.
Is there a way to move the std::unique_ptr to be executed later in the handler of the io_service::post?
The error I get when I try to compile it with GCC:
   error: use of deleted function ...
   BOOST_ASIO_COMPLETION_HANDLER_CHECK(CompletionHandler, handler) type_check;

The code sample goes below (updated):
#include <boost/asio.hpp>
#include <boost/asio/io_service.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <deque>
#include <memory>
#include <string>

// Defined abstract class IMsg and concrete MsgTest class, representing the
// messages to be sent
class IMsg {
 public:
  explicit IMsg() = default;
  virtual ~IMsg() = default;
  IMsg(const IMsg& msg) = delete;
  IMsg& operator=(const IMsg& msg) = delete;
  virtual const std::string& Serialize() = 0;
};

class MsgTest : public IMsg {
 public:
  explicit MsgTest(const std::string& msg) : m_testMsg(msg) {}
  MsgTest(const MsgTest&) = delete;
  MsgTest& operator=(const MsgTest&) = delete;
  const std::string& Serialize() override { return m_testMsg; }

 private:
  std::string m_testMsg;
};

using IMsgPtr = std::unique_ptr<IMsg>;

class MsgClient {
 public:
  MsgClient(boost::asio::io_service& ioService)
      : m_ioService(ioService), m_socket(ioService) {}

  void asyncSendMsg(IMsgPtr&& msgPtr) {
    m_ioService.post([this, msgPtr{std::move(msgPtr)}]() mutable {
      m_messagesOut.emplace_back(std::move(msgPtr));
      // Serialize() returns const reference to serialized member data.
      // Thus, the data will be valid until the async_write returns.
      const std::string& currentMsg = m_messagesOut.front()->Serialize();

      // todo: such usage of async_write is dangerous and not thread-safe!
      boost::asio::async_write(
          m_socket, boost::asio::buffer(currentMsg, currentMsg.length()),
          [this](boost::system::error_code ec, std::size_t length) {
            if (ec == 0) {
              m_messagesOut.pop_front();
            } else {
              // todo: error
            }
          });
    });
  }

 private:
  std::deque<IMsgPtr> m_messagesOut;
  boost::asio::io_service& m_ioService;
  boost::asio::ip::tcp::socket m_socket;
};

// Calling the asynSendMsg
int main() {
  boost::asio::io_service ioServiceWorker;
  MsgClient client(ioServiceWorker);
  //todo: client.connect()...
  client.asyncSendMsg(std::make_unique<MsgTest>("Hello World"));
  // code that runs io_service in a separate thread is present below
  // but omitted.
}

P.S. We are limited to using C++14 only and Boost.Asio version 1.57. Also, if anyone is interested in why I'm using post and call async_write in the handler (why not async_write directly):
I have a multi-threaded app, and asyncSendMsg is usually called from a different thread than the MsgClient resides in. Thus, by adding the IMsgPtr into the array by post-ing, I can avoid using inter-thread synchronization using mutexes - as far as post's handler will always be executed in the same thread where the MsgClient is located.
I'd appreciate knowing how I can move construct std::unique_ptr<IMsg> in the post's handler.
Also, if you have any ideas on improving the code quality here, this will be appreciated as well.

A: Move-only handler support has improved over latest releases.
That means when using the post, dispatch and defer interfaces on executors. However, you're using the legacy io_service::post interface.
If your version of boost is recent enough you may be able to simply get away with switching m_io.post(task) into asio::post(m_io, task)
First Take
Live On Coliru
#include <boost/asio.hpp>
#include <boost/endian/arithmetic.hpp>
#include <deque>
#include <iostream>
namespace asio = boost::asio;
using asio::ip::tcp;
using boost::system::error_code;

// Defined abstract class IMsg and concrete MsgTest class, representing the
// messages to be sent
struct IMsg {
    virtual ~IMsg() = default;
    using buffers = std::vector<boost::asio::const_buffer>;
    virtual buffers as_buffers() const = 0;
};

struct MsgTest : public IMsg {
    boost::endian::big_uint32_t msg_type_ = 0x0001;
    std::string                 payload_;
    boost::endian::big_uint32_t payload_length_ = payload_.length();

    MsgTest(std::string payload) : payload_(std::move(payload)) {}

    virtual buffers as_buffers() const override {
        return {
            boost::asio::buffer(&msg_type_, sizeof(msg_type_)),
            boost::asio::buffer(&payload_length_, sizeof(payload_length_)),
            boost::asio::buffer(payload_),
        };
    }
};

using IMsgPtr = std::unique_ptr<IMsg>;

class MsgClient {
  public:
    MsgClient(boost::asio::io_context& ioc) : m_io(ioc) {}

    error_code connect(tcp::endpoint ep) {
        auto task = std::packaged_task<error_code()>{[this, ep]() {
            error_code ec;
            m_socket.connect(ep, ec);
            return ec;
        }};
        return asio::post(m_io, std::move(task)).get();
    }

    void asyncSendMsg(IMsgPtr msgPtr) {
        post(m_io, [this, msgPtr = std::move(msgPtr)]() mutable {
            m_messagesOut.emplace_back(std::move(msgPtr));

            if (m_messagesOut.size() == 1)
                do_send_loop();
        });
    }

  private:
    void do_send_loop() {
        if (m_messagesOut.empty())
            return;

        asio::async_write( //
            m_socket, m_messagesOut.front()->as_buffers(),
            [this](error_code ec, size_t /*length*/) {
                if (!ec.failed()) {
                    m_messagesOut.pop_front();

                    do_send_loop();
                } else {
                    // todo: error
                }
            });
    }

    asio::io_context&   m_io;
    tcp::socket         m_socket{m_io};
    std::deque<IMsgPtr> m_messagesOut;
};

// Calling the asynSendMsg
int main() {
    boost::asio::io_context ioc;
    MsgClient client(ioc);

    std::cout << "Connecting: " << client.connect({{}, 7878}).message() << "\n";

    for (auto msg : {"Hello", " World!\n", "Bye", " Universe\n"})
        client.asyncSendMsg(std::make_unique<MsgTest>(msg));

    ioc.run();
}

When run against netcat -tlp 7878 | xxd:
Connecting: Success

With the netcat pipeline printing:
00000000: 0000 0001 0000 0005 4865 6c6c 6f00 0000  ........Hello...
00000010: 0100 0000 0820 576f 726c 6421 0a00 0000  ..... World!....
00000020: 0100 0000 0342 7965 0000 0001 0000 000a  .....Bye........
00000030: 2055 6e69 7665 7273 650a                  Universe.

Note the many small fixes/improvements:

*

*using buffer sequence instead of serialized string - this may or may not help you depending on how you serialize your data

*showing some message framing for fun

*showing how to safely dispatch synchronous operations to the service (by using a packaged task/future)

*correctly queuing the output messages

*

*not allowing multiple async_write operations concurrently (see docs)

*correctly sending FIFO order (you had Serialize(...back()) but then  pop_front()...)

Going From Here
I'd actually go the extra step and switch to the executor model, which has some simplifying benefits:
Live On Coliru
#include <boost/asio.hpp>
#include <boost/endian/arithmetic.hpp>
#include <deque>
#include <iostream>
namespace asio = boost::asio;
using asio::ip::tcp;
using boost::system::error_code;

// Defined abstract class IMsg and concrete MsgTest class, representing the
// messages to be sent
struct IMsg {
    virtual ~IMsg() = default;
    using buffers = std::vector<boost::asio::const_buffer>;
    virtual buffers as_buffers() const = 0;
};

struct MsgTest : IMsg {
    boost::endian::big_uint32_t msg_type_ = 0x0001;
    std::string                 payload_;
    boost::endian::big_uint32_t payload_length_ = payload_.length();

    MsgTest(std::string payload) : payload_(std::move(payload)) {}

    virtual buffers as_buffers() const override {
        return {
            boost::asio::buffer(&msg_type_, sizeof(msg_type_)),
            boost::asio::buffer(&payload_length_, sizeof(payload_length_)),
            boost::asio::buffer(payload_),
        };
    }
};

using IMsgPtr = std::unique_ptr<IMsg>;

class MsgClient {
  public:
    template <typename Executor> MsgClient(Executor ex) : m_socket(ex) {}

    error_code connect(tcp::endpoint ep) {
        auto task = std::packaged_task<error_code()>{[this, ep]() {
            error_code ec;
            m_socket.connect(ep, ec);
            return ec;
        }};
        return asio::post(m_socket.get_executor(), std::move(task)).get();
    }

    void asyncSendMsg(IMsgPtr msgPtr) {
        post(m_socket.get_executor(),
             [this, msgPtr = std::move(msgPtr)]() mutable {
                 m_messagesOut.emplace_back(std::move(msgPtr));

                 if (m_messagesOut.size() == 1)
                     do_send_loop();
             });
    }

  private:
    void do_send_loop() {
        if (m_messagesOut.empty())
            return;

        asio::async_write( //
            m_socket, m_messagesOut.front()->as_buffers(),
            [this](error_code ec, size_t /*length*/) {
                if (!ec.failed()) {
                    m_messagesOut.pop_front();

                    do_send_loop();
                } else {
                    // todo: error
                }
            });
    }

    tcp::socket         m_socket;
    std::deque<IMsgPtr> m_messagesOut;
};

// Calling the asynSendMsg
int main() {
    boost::asio::thread_pool ioc(1);

    MsgClient client(make_strand(ioc.get_executor()));

    std::cout << "Connecting: " << client.connect({{}, 7878}).message() << "\n";

    for (auto msg : {"Hello", " World!\n", "Bye", " Universe\n"})
        client.asyncSendMsg(std::make_unique<MsgTest>(msg));

    ioc.join();
}

BONUS
If you have to use the old interfaces and cannot upgrade Boost, you might use the BOOST_ASIO_DISABLE_HANDLER_TYPE_REQUIREMENTS define to skip the handler type checks, which makes it compile in more cases: https://godbolt.org/z/76dh9dcjj


text:
Q: For Machine.Specifications suites, is there a way to run code globally? I'd like to execute startup/teardown code one time for all discovered specs when using Mspec.  Does it currently have any facility for doing this?

A: IAssemblyContext is your friend. But it does that per assembly, not globally.


text:
Q: infinite scrolling stops if I zoom my browser I've got a page with infinite scrolling that works fine when the user's browser's zoom is at 100%. If the user zooms in on the page or zooms out (ie anything other than 100%) the scrolling eventually breaks and the page will stop retrieving records, even though there are many more to get.
How do I correct that?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <title></title>

            <?php
            for($counter=0; $counter <= 50; $counter += 1){
              echo "\n".'
Post no '.$counter.'
';
            }
            ?>

here's test2.php:
<?php
if(isset($_GET['lastid'])){
$counter=addslashes($_GET['lastid']) + 1;
$total=$counter+25;
  for($counter; $counter <= $total; $counter += 1){
   echo "\n".'
Post no '.$counter.'
';
  }
}
?>

A: Possible solution
Just to make sure,
Check out this link, and see if that solution might do you any better. It checks when you've hit the bottom of the scroll. It's really accurate!

var elem = $('#box');
var inner = $('#box > .inner');
if ( Math.abs(inner.offset().top) + elem.height() + elem.offset().top >= inner.outerHeight() ) {
  // We're at the bottom!
}

Checking zoom ratio
Hm, if that doesn't work, I'd suggest you take a look at this question & answer.
They discuss how to detect the amount of zoom in different browsers.
You can, from there, correct your code to account for the zoom when determining the end of scroll.

Infinite scroll plugins
Other than that, I'd suggest you look into some of the alternative plugins that manage infinite scrolling
Like

*

*scrollLoad

*Infinite Scroll jQuery Plugin
I could probably list a few others, but it's easier just to do a google search, there are so many of them.

Happy coding and good luck! :)

A: when zoom in,
console.log('document height'+jQuery(document).height());  ---15138
console.log('window scrollTop'+jQuery(window).scrollTop());---13926.25
console.log('window height'+jQuery(window).height());      ---1211

and the sum of jQuery(window).scrollTop() and jQuery(window).height() is 0.75 lower than jQuery(document).height().
So I add 2
    if (jQuery(document).height() <= jQuery(window).scrollTop() + jQuery(window).height() + 2)

Hope it works for you


text:
Q: Multilevel modeling I want to look at the change in the percentage of income savings measured in dollars using repeated measures data for older adults. I want to compare three groups based on their father's occupation while growing up.
I want to estimate different slopes and intercepts for the three groups. For example: group A is subjects whose father's were blue-collar; group B is subjects whose fathers were white-collar; group C is subjects whose fathers were other types of workers. I have repeated measures for 10 annual surveys and subjects reported how much of their income they saved. I want to see if the intercept and trajectory differ for the three groups.
This is what I come up with but I am not sure if this gets at the appropriate verbal explanation.
m1
xtmixed savings time || subjects:, var

m1 looks at the impact of time on savings and estimates intercepts and slopes for each subject.
m2
xtmixed savings time##fathers_occupation || subjects:, var

Does m2 examine the differences in the intercept and slope for the two groups? Or do I need to add fathers_occupation to the right side of || as well?

A: You don't need it in the right part, unless you think the effect of fathers_occupation on savings is different between all the subjects. m2 estimates different intercepts for each subject and then the time##fathers_occupation estimates the slopes of fathers_occupation in each measurement (time) group of subjects.
I don't know your data but I think it's very unlikely to have different effects for fathers_occupation for all the different subjects, so I think you could rely on the simpler, random intercept model with the interaction term, as specified by m2.


text:
Q: Way to calculate zoom and pan using canvas and d3.js hierarchical circle structure I currently have a d3 hierarchical circle pack graph in canvas (with help from this awesome tutorial!)
I wanted to make the graph also pan with the mouse and scale with the wheel in addition to zooming in to a node. I used this.
Now, when I first pan and then zoom to a node using the initial scale (When the page first loads), it works as expected. It zooms to the node from wherever the graph's last panned position was.
But when I try to pan and zoom from the zoomed state, the view starts at a completely different place before it ends at the expected node. If from the zoomed state I don't pan, but jump/zoom from one node to another, the transition works as expected. I'm not sure why this happens. Can anyone help me figure out what I'm doing wrong? Thanks in advance!
(Sorry for any faux-pas -- Its my first stack overflow question...)

  @ViewChild('myCanvas') canvas: ElementRef;
  @ViewChild('myCanvas') hiddenCanvas: ElementRef;
  public context: CanvasRenderingContext2D;
  public hiddenContext: CanvasRenderingContext2D;

  public focus;
  public xleftView = 0;
  public ytopView = 0;

  public widthViewOriginal = window.innerWidth;
  public heightViewOriginal = window.innerHeight;
  public widthView = this.widthViewOriginal;
  public heightView = this.heightViewOriginal;
  public widthCanvas = window.innerWidth;
  public heightCanvas = window.innerHeight;

  public mouseDown = false;
  public movedCoordinatesX;
  public movedCoordinatesY;
  public lastX = 0;
  public lastY = 0;

  public zoomInfo = {
    centerX: window.innerWidth / 2,
    centerY: window.innerHeight / 2,
    scale: 1
  };

    public handleMouseDown(event) {
      // get where the mouse first clicked to pan the graph
      this.movedCoordinatesX = event.clientX
      this.movedCoordinatesY = event.clientY
      if (event.which === 1) {
        this.mouseDown = true;
      }
    }

    public handleMouseUp(event) {
      this.mouseDown = false;
      // Get the distance moved in the x & y direction from the initial click to the end mouse position
      this.movedCoordinatesX = this.movedCoordinatesX - event.clientX
      this.movedCoordinatesY =  this.movedCoordinatesY - event.clientY

      // add distance in the X & Y to the old view's X & Y (to make the transition happen from the current position
      this.vOld[0] = (this.vOld[0] + this.movedCoordinatesX)
      this.vOld[1] = (this.vOld[1] + this.movedCoordinatesY)
    }

    public handleMouseMove(event) {

      var X = event.clientX - this.context.canvas.offsetLeft -  this.context.canvas.clientLeft + this.context.canvas.scrollLeft;
      var Y = event.clientY -  this.context.canvas.offsetTop -  this.context.canvas.clientTop +  this.context.canvas.scrollTop;
      if (this.mouseDown) {
          var dx = (X - this.lastX) / this.widthCanvas * this.widthView;
          var dy = (Y - this.lastY)/ this.heightCanvas * this.heightView;
          this.xleftView -= dx;
          this.ytopView -= dy;
      }
      this.lastX = X;
      this.lastY = Y;
  }

  // Listen for clicks on the main canvas
  public zoomInToNode(e) {
    // We actually only need to draw the hidden canvas when there is an interaction.
    // This sketch can draw it on each loop, but that is only for demonstration.
    this.drawCanvas(this.hiddenContext, true);

    //Figure out where the mouse click occurred.
    var mouseX = e.layerX;
    var mouseY = e.layerY;
    this.lastX = mouseX
    this.lastY = mouseY

    // Get the corresponding pixel color on the hidden canvas and look up the node in our map.
    // This will return that pixel's color
    var col = this.hiddenContext.getImageData(mouseX, mouseY, 1, 1).data;
    //Our map uses these rgb strings as keys to nodes.
    var colString = "rgb(" + col[0] + "," + col[1] + ","+ col[2] + ")";
    var node = this.colToCircle[colString];

    if(node) {
      if (this.focus !== node) {

        this.xleftView = 0
        this.ytopView = 0
        this.hiddenContext.setTransform(1, 0, 0, 1, 0, 0);
        this.zoomToCanvas(node);
      }
      else {

        this.xleftView = 0
        this.ytopView = 0
        this.hiddenContext.setTransform(1, 0, 0, 1, 0, 0);

        this. widthView = this.widthViewOriginal;
        this. heightView = this.heightViewOriginal;
        this. widthCanvas = window.innerWidth;
        this. heightCanvas = window.innerHeight;
        this.zoomToCanvas(this.rooting);
      }
    }//if
  };

  public zoomToCanvas(focusNode) {
    // the node that we want to zoom to
    this.focus = focusNode;

    var v = [this.focus.x, this.focus.y, this.focus.r * 2.05]; //The center and width of the new "viewport"

    this.interpolator = d3.interpolateZoom(this.vOld, v); //Create interpolation between current and new "viewport"

    this.duration = this.interpolator.duration; //Interpolation gives back a suggested duration
    this.timeElapsed = 0; //Set the time elapsed for the interpolateZoom function to 0
    this.vOld = v; //Save the "viewport" of the next state as the next "old" state

  }//function zoomToCanvas

  // Perform the interpolation and continuously change the zoomInfo while the "transition" occurs
  public interpolateZoom(dt) {
    if (this.interpolator) {
      this.timeElapsed += dt;
      var t = this.ease(this.timeElapsed / this.duration);

      if(isFinite(t)) {
      this.zoomInfo.centerX = this.interpolator(t)[0];
      this.zoomInfo.centerY = this.interpolator(t)[1];
      this.zoomInfo.scale = this.diameter / this.interpolator(t)[2];

      if (this.timeElapsed >= this.duration) this.interpolator = null;
      }
    }//if
  }//function zoomToCanvas

  public drawCanvas(chosenContext, hidden) {
    chosenContext.save();
    chosenContext.setTransform(1,0,0,1,0,0);
    chosenContext.clearRect(0, 0, this.canvas.nativeElement.width, this.canvas.nativeElement.height);
    chosenContext.scale(this.widthCanvas/this.widthView, this.heightCanvas/this.heightView);
    chosenContext.translate(-this.xleftView,-this.ytopView);
    chosenContext.restore();

  }

A: So I figured it out... I was supposed to divide by the overall scale.
I really want to thank this answer for giving me the inspiration!
    public handleMouseUp(event) {
      this.mouseDown = false;
        this.movedCoordinatesX = this.movedCoordinatesX - event.clientX
        this.movedCoordinatesY =  this.movedCoordinatesY - event.clientY

        if(this.zoomInfo.scale == 1) {
          this.vOld[0] = (this.vOld[0] + this.movedCoordinatesX)
          this.vOld[1] = (this.vOld[1] + this.movedCoordinatesY)
        } else {
          this.vOld[0] = (this.vOld[0] + (this.movedCoordinatesX/this.zoomInfo.scale))
          this.vOld[1] = (this.vOld[1] + (this.movedCoordinatesY/this.zoomInfo.scale))
        }
    }


text:
Q: Django. Загрузка файла на сервер без формы Есть модель:
class UploadFile(models.Model):
    attach = models.FileField(upload_to='media/')

Генерирую pdf документ. На выходе получаю переменную типа <class 'bytes'>. Как мне сохранить сгенерированный файл в модель.

A: Метод FileField.save (это класс поля revsys.attach) принимает любой file-подобный объект, благодаря чему можно не записывать его в ФС заранее, а просто создать в памяти с помощью BytesIO:
from io import BytesIO

revsys = UploadFile()
revsys.attach.save('file.pdf', BytesIO(pdf), save=True)

Это работает в Django 1.10, где file-подобный объект оборачивается в джанговый класс File автоматически. Если вы используете Django 1.9 или старее, оно будет ругаться ошибкой '_io.BytesIO' object has no attribute 'size', и здесь придётся обернуть BytesIO самостоятельно:
from django.core.files import File
# ...
revsys.attach.save('file.pdf', File(BytesIO(pdf)), save=True)


text:
Q: PHP - loop button and input in form I wanted create firm list (from sql) and buttons to delete. It should looks like:
 ------------------------------
 |name_firm1   'delete_button'|
 |name_firm2   'delete_button'|
 |name_firm3   'delete_button'|
 ------------------------------

i created form (here i removed css elements for you):
echo '<form method="post" name="remove_firm_to_targs" action="">';

         while($saf = mysql_fetch_assoc($show_added_firm))
         {
            $query = mysql_query ("SELECT id_firm, name_firm FROM firms WHERE id_firm ='".$saf['id_firm']."'");
            $q = mysql_fetch_assoc($query);

            <input type="hidden" name="id_firm[]" value="'.$q['id_firmy'].'" />

 '.$q['name_firm'].'

<input type="submit" id="button" value="delete firm" name="remove_firm_to_targ"/>

';
        }
echo '</form>';

I can't $_post id_firm from hidden input.
Here is code:
if(isset($_POST['remove_firm_to_targ'])) {
    $id_targ = $_GET['id'];

    $id_firmy = array();
    foreach ($_POST['id_firm'] as $idid)
    {
        $id_firm[] = array ('idid' => $idid);
    }

    mysql_query ("DELETE FROM firm_to_targ WHERE id_firm = '".$id_firm.' && id_targ = '".$id_targ."'");
}

I change this code many times so now it has nosense.

A: Your form should be like this:
I put the id of the firm into delete button value.
while($saf = mysql_fetch_assoc($show_added_firm))
{
echo '<form method="post" name="remove_firm_to_targs" action="">';

    $query = mysql_query ("SELECT id_firm, name_firm FROM firms WHERE id_firm ='".$saf['id_firm']."'");
$q = mysql_fetch_assoc($query);

 '.$q['name_firm'].'

<input type="submit" id="button" value="DELETE" name="remove_firm_to_targ"/>

    <input type="hidden" name="delete_this" value="'.$q['id_firmy'].'">
    ';

    echo '</form>';
}

So when you submit the button for the firm, it will delete the firm which has id on delete button value's:
if(isset($_POST['remove_firm_to_targ'])) {
$id_targ = $_GET['id'];

mysql_query ("DELETE FROM firm_to_targ WHERE id_firm = '".$_POST['delete_this'].' && id_targ = '".$id_targ."'");
}

A: while($saf = mysql_fetch_assoc($show_added_firm)) {
    $query = mysql_query ("SELECT id_firm,
             name_firm FROM firms WHERE id_firm ='".$saf['id_firm']."'");
        $q = mysql_fetch_assoc($query);

 '.$q['name_firm'].'

<a href="delete.php?id=$q['name']
';
 }
 echo '</form>';

in ur case


text:
Q: Find the sum of all quantities per item I use the NorthWind database and my point is to select the total amount of shipped orders per City in one row. Sorry for dummy question but I am new in Sql
select e.FirstName , o.ShipCity, od.UnitPrice,Sum(od.Quantity),
sum(od.Quantity*od.UnitPrice) from [Order Details] as od
inner join Products as p on p.ProductID=od.ProductID
inner join Orders as o on o.OrderID =od.OrderID
inner join Employees as e on e.EmployeeID=o.EmployeeID
where o.ShipCity= 'Graz' and o.isCanceled !=1 and e.FirstName ='Nancy'
group by e.FirstName , o.ShipCity,od.UnitPrice

A: =>
select e.firstName , o.ShipCity , sum ( od.Quantity) from [ order Details ] as od
inner join Orders  as o on o.OrderId = od.OrderId
inner join Employees as e on e.employeeID=o.EmployeeID
where o.shipcity = 'Graz'and o.iscanceled !=1 and e.firstname='Nancy'
group by e.firstName , o.ShipCity

A: To get the amount per city you must remove FirstName and UnitPrice from your select.
select o.ShipCity,
   Sum(od.Quantity),
   sum(od.Quantity*od.UnitPrice)
from [Order Details] as od
inner join Products as p on p.ProductID=od.ProductID
inner join Orders as o on o.OrderID =od.OrderID
inner join Employees as e on e.EmployeeID=o.EmployeeID
where o.ShipCity= 'Graz' and o.isCanceled !=1 and e.FirstName ='Nancy'
group by o.ShipCity


text:
Q: Coordinate compression Problem: You have an N x N grid (1 <= N <= 10^9). Each square can either be traversed or is blocked. There are M (1 <= M <= 100) obstacles in the grid, each one shaped like a 1xK or Kx1 strip of grid squares. Each obstacle is specified by two endpoints (A_i, B_i) and (C_i, D_i), where A_i=C_i or B_i=D_i. You are also given a start square (X,Y).
The question is: how many squares are reachable from the start square if you can go left, right, up, and down, and you cannot traverse obstacles?
I have tried to solve this problem with BFS, but for very large dimensions of the grid it is too slow. Then i heard of coordinate compression. Can someone explain what is coordinate compression, how is it implemented, where can i learn more about it ?

A: You have few obstacles on a large field. If you treat every square of the field as vertex in your graph, you will end up with a large graph, which requires a lot of memory and will take a long time to traverse.
The idea is to reduce the number of squares in the graph by creating rectangular blocks from the squares. To illustrate, you want to convert your graph like this:

This reduces the number of vertices greatly. For example, the 5×7 squares in the top left corner are now represented by a single block. The new graph has only 7×7 blocks.
It should be easy to achieve such a representation: Find the horizontal and vertical block coordinates. Sort them. Use binary search to find the block coordinates of obstacles and the starting point. Then use your original algorithm on the compressed grid.


text:
Q: Mongo opens too many connections I am trying to write a lot of data to MongoDB, in a Java loop. I am getting errors based on the number of connections open.
My theory is that since MongoDB is not transactional, lots of connections can be opened simultaneously. However the Java code is also able to loop very fast, after a certain time the number of loop iterations starts overtaking the number of available connections and Mongo hits a wall.
My code looks like this. I've seen it recommended to not do m.close() but then you just get the error even faster.
public static void upsert(){
    Mongo m = null;
    DB db = null;

    try {
    m = new Mongo("localhost");
    db = m.getDB("sempedia");    } catch (UnknownHostException e1) { e1.printStackTrace(); } catch (MongoException e1) { e1.printStackTrace(); }

    // create documents
    // I am doing an upsert - hence the doc, doc
    DBCollection triples;
try {
        triples = db.getCollection("triples");
        triples.update(doc,doc,true,false);
    } catch (MongoException e) { e.printStackTrace(); }

    m.close();
}

In my java console I get this error:

WARNING: Exception determining maxBSON size using0
  java.net.SocketException: Connection reset

And mongodb gives this error:

Tue Oct 25 22:31:39 [initandlisten] connection refused because too
  many open connections: 204 of 204

What would be the most elegant way to deal with this issue?

A: You're making a new MongoClient everytime you come through your method.
I had this problem as well, but i solved it making a checkConnection function:
private static DBCollection checkConnection(String collection) throws UnknownHostException{
    if(db == null){
        db = (new MongoClient(host, port)).getDB(database);
    }
    return db.getCollection(collection);
}

On top where you instantiate your variables, have this:
private static DB db = null;
private static String database = "<Your database>";
private static String host = "localhost"; //<--- usually localhost
private static int port = 27017; //<---- usually 27017, but you can change it.

Then when you make a method, have it like this:
 public <whatever> someFunction() throws UnknownHostException{
    DBCollection dbCollection = checkConnection("triples"); //<--- can be "triples"
                                                    //or whatever collection you want

     <REST OF YOUR FUNCTION HERE USING THE AMAZING COLLECTION
 }

This approach has a few advantage:
- Code reusability, you won't have to write the same thing at every method
- Readability, which programmer doesn't understand this:
  DBCollection dbCollection = checkConnection("triples");
- ONLY ONE CONNECTION WHICH YOU RE-USE (this doesn't affect data not being synced)

Hope I helped

A: You are creating an instance of the Mongo class for each individual operation. That won't work since each instance will create and hold at least one connection (but by default, 10) and those connections will only be removed if the Java GC cleans up your Mongo instance or when you invoke close().
The problem is that in both cases you're creating them faster than they are being closed even using a single thread. This will exhaust the maximum amount of connections in a hurry. The right fix is to keep one Mongo instance around using the singleton pattern (Mongo.Holder provides functionality for this, try Mongo.Holder.connect(..)). A quick "fix" is to increase the file descriptor limit on your machine so the maximum amount of connections is considerably higher but obviously you eventually might hit the same limit. You can check your current max using (in shell) :
db.serverStatus().connections

TL;DR : Treat a Mongo instance as a singleton and make them as long-lived as possible and you're golden. Implementing a MongoFactory with a static method getInstance() that returns a lazily created instance will do the trick just fine. Good luck.


text:
Q: White and Black chess pieces The following works when I use the pro version of font awesome, but I'm wondering if I'm missing something obvious.
I decided to use class="fa fa-chess-pawn" for black pieces and class="far fa-chess-pawn" for white pieces.
Q: Am I missing something obvious? Is there something I should use to differentiate between white and black pieces?

.row {
 min-height:90px;
}
.col-1 {
 border-bottom:1px solid black;
 border-right:1px solid black;
}
.left {
 border-left:1px solid black;
}
.top {
 border-top:1px solid black;
}
.card-body {
 font-size:72px;
}
.gray {
 color:white
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

A: To make it work with the free version of font awesome: Add a "white" class to the parent (draggable container) and change far to fas:
As Chris Forrence mentioned: I'd suggest to change "fa" to "fas" (since "fa" is deprecated)

.draggable.white {
    color: #fff;
}
.row {
 min-height:90px;
}
.col-1 {
 border-bottom:1px solid black;
 border-right:1px solid black;
}
.left {
 border-left:1px solid black;
}
.top {
 border-top:1px solid black;
}
.card-body {
 font-size:72px;
}
.gray {
 color:white
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">


text:
Q: Which projection is best for mapping the contiguous United States? If I wanted to project latitude & longitude data for the contiguous United States (the United States excluding Alaska and Hawaii), which projection would I use? I prefer more accurate distances followed by shapes

A: The Albers equal area conic is the typical projection for historical USGS maps of the lower 48, it being a general-purpose low-distortion compromise for mid-latitude short and wide extents.
As a reference on map projections, I like the ESRI book Understanding Map Projections. Its first 30 pages are not unlike a short textbook, followed by ~70 pages of appendix on individual projections, their uses, strengths, weaknesses, etc.

*

*Albers, pg 37

*Lambert, pg 66

*equidistant conic, pg 53

A: ESRI has defined three projections especially for the contiguos United states. These are included in QGIS as well:
EPSG:102003 USA_Contiguous_Albers_Equal_Area_Conic
+proj=aea +lat_1=29.5 +lat_2=45.5 +lat_0=37.5 +lon_0=-96 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs

EPSG:102004 USA_Contiguous_Lambert_Conformal_Conic
+proj=lcc +lat_1=33 +lat_2=45 +lat_0=39 +lon_0=-96 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs

EPSG:102005 USA_Contiguous_Equidistant_Conic
+proj=eqdc +lat_0=39 +lon_0=-96 +lat_1=33 +lat_2=45 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs

So it is up to you which projection characteristics you need: equal area, equal distance or conformal.
Visit this page to see the differences: http://www.radicalcartography.net/?projectionref

A: If shape is important, consider a Lambert conic conformal projection, with two standard latitudes.
Distances will be consistent in the vicinity of each of the standard parallels.
See

*

*wikipedia.org/wiki/Lambert_conformal_conic_projection

*wired.com/2013/11/projection-lambert-conformal-conic

*georeference.org/doc/lambert_conformal_conic

*mathworld.wolfram.com/LambertConformalConicProjection
You could also consider some sort of "equidistant" projection. However, distance scale will never be true everywhere; only true from one or two points (in all directions) or from one line (in a single direction).


text:
Q: How to upload multiple files using smarty in php? I make a select box in which i select different resumes to apply on the same job but when i applying jobs it gives me error like this "You Already Applied"
Here is my apply_now.tpl:
{literal}

 {/literal}

div id="ProgressBar" style="display:none">[[Please wait ...]]

{if $is_data_submitted && !$errors}

[[You applied successfully]]

{else}
    {foreach from=$errors key=error_code item=error_message}

                {if $error_code  eq 'EMPTY_VALUE'} [[Enter Security code]]
                {elseif $error_code eq 'NOT_VALID'} [[Security code is not valid]]
                {elseif $error_code eq 'SEND_ERROR'} [[There was an error while sending your application.]]
                {else}[[{$error_message}]]
                {/if}

    {/foreach}
    {include file='field_errors.tpl'}
    <form method="POST" enctype="multipart/form-data" action="{$GLOBALS.site_url}/apply-now/" id="applyForm">
        <input type="hidden" name="is_data_submitted" value="1">
        <input type="hidden" name="listing_id" value="{$listing_id}">
        {if NOT $GLOBALS.current_user.logged_in}
            <fieldset>

[[Your name]]:

<input type="text" name="name" value="{$request.name}" />

            </fieldset>
            <fieldset>

[[Your e-mail]]:

<input type="text" name="email" value="{$request.email}" />

            </fieldset>
        {/if}
        <fieldset>

[[Cover letter (optional)]]:

<textarea name="comments" rows="5">{$request.comments}</textarea>

        </fieldset>
        {if $GLOBALS.current_user.logged_in && $resume}
            <fieldset>

[[Select your resume]]:

                    <select name="id_resume" multiple="multiple">
                        <option value="0" selected="selected">[[Select your resume]]</option>
                        {html_options options=$resume selected=$request.id_resume}
                    </select>

or

            </fieldset>
        {/if}
        <fieldset>

[[Attach your resume]]:

<input type="file" name="file_tmp" />

        </fieldset>
        {if $isCaptcha == 1}
            <fieldset>

[[$captcha.caption]]:

{input property=$captcha.id object=$captchaObject}

            </fieldset>
        {/if}
        <input type="hidden" name="anonymous" value="1" />
        {if $form_fields}
            <fieldset>
                {include file="questionnaire.tpl" form_fields=$form_fields}
            </fieldset>
        {/if}
        <fieldset>

<input id="SubmitButton" type="submit" value="[[Send]]" onclick="return applySubmit();"/>

        </fieldset>
    </form>
{/if}

and here is my apply_now.php code:
 $listingId = 0;
                $post['submitted_data']['questionnaire'] = '';
                if (isset($post['submitted_data']['id_resume']))
                    $listingId = $post['submitted_data']['id_resume'];

                $mimeType = isset($_FILES['file_tmp']['type']) ? $_FILES['file_tmp']['type'] : '';

                if (isset($_FILES['file_tmp']['size']) && $file_name != '' && $_FILES['file_tmp']['size'] == 0) {
                    $errors['FILE_IS_EMPTY'] = 'The uploaded file should not be blank';
                }

                if (!empty($_FILES['file_tmp']['name'])){
                    $fileFormats = explode(',',SJB_System::getSettingByName('file_valid_types'));
                    $fileInfo = pathinfo($_FILES['file_tmp']['name']);
                    if (!in_array(strtolower($fileInfo['extension']), $fileFormats)) {
                        $errors['NOT_SUPPORTED_FILE_FORMAT'] = strtolower($fileInfo['extension']) . ' ' . SJB_I18N::getInstance()->gettext(null, 'is not in an acceptable file format');
                    }
                }

                if ($file_name == '' && $listingId == 0) {
                    $canAppplyWithoutResume = false;
                    SJB_Event::dispatch('CanApplyWithoutResume', $canAppplyWithoutResume);
                    if (!$canAppplyWithoutResume) {
                        $errors['APPLY_INPUT_ERROR'] = 'Please select file or resume';
                    }
                }
                else if (SJB_Applications::isApplied($post['submitted_data']['listing_id'], $current_user_sid) && !is_null($current_user_sid)) {
                    $errors['APPLY_APPLIED_ERROR'] = 'You already applied';
                }

 if (count($errors) == 0 && count($field_errors) == 0) {
                    $res = SJB_Applications::create(
                        $post['submitted_data']['listing_id'],
                        $current_user_sid,
                        (isset($post['submitted_data']['id_resume'])) ? $post['submitted_data']['id_resume'] : '',
                        $post['submitted_data']['comments'],
                        $file_name,
                        $mimeType,
                        $id_file,
                        (isset($post['submitted_data']['anonymous'])) ? $post['submitted_data']['anonymous'] : '0',
                        $notRegisterUserData,
                        $post['submitted_data']['questionnaire'],
                        $score
                    );
                    if ($res)
                        SJB_Statistics::addStatistics('apply', $post['submitted_data']['listing_id'], $res);
                    if (isset($post['submitted_data']['id_resume']) && $post['submitted_data']['id_resume'] != 0) {
                        $listing_info = SJB_ListingManager::getListingInfoBySID($post['submitted_data']['id_resume']);
                        $emp_sid = SJB_ListingManager::getUserSIDByListingSID($post['submitted_data']['listing_id']);
                        $accessible = SJB_ListingManager::isListingAccessableByUser($post['submitted_data']['id_resume'], $emp_sid);
                        if (!$accessible)
                            SJB_ListingManager::setListingAccessibleToUser($post['submitted_data']['id_resume'], $emp_sid);
                    }

How i select multiple resumes and then applied?

A: use this..
<input type="file" name="file_tmp[]" multiple />..
this will give you an array of files.
 for($i=0; $i < count($_FILES['file_tmp']['tmp_name']);$i++)
    {
        // check if there is a file in the array
        if(!is_uploaded_file($_FILES['file_tmp']['tmp_name'][$i]))
        {
            $messages[] = 'No file uploaded';
        }
        else
        {
            // copy the file to the specified dir
            if(@copy($_FILES['file_tmp']['tmp_name'][$i],$upload_dir.'/'.$_FILES['file_tmp']['name'][$i]))
            {
                $messages[] = $_FILES['file_tmp']['name'][$i].' uploaded';
            }
            else
            {
                /*** an error message ***/
                $messages[] = 'Uploading '.$_FILES['file_tmp']['name'][$i].' Failed';
            }
        }
    }

let me know if you want any further guidance...


text:
Q: Laravel Array Element Validation I want to validate that audition_dates field to be before shoot_dates.
I know I can pass these rules to validate the array:
public function store(Request $request)
{
    $validatedData = $request->validate([
      'shoot_dates' => 'array',
      'shoot_dates.*' => 'date',
      'audition_dates' => 'array',
      'audition_dates.*' => 'date'
    ]);

    // The request is valid...
}

I know these validation rules exist:
$rules = [
 'start_date' => 'after:tomorrow',
 'end_date' => 'after:start_date'
];

But I don't know how to implement them on an array.

A: As for your code, and also as stated in Laravel Documentation:
Validator::make($request->all(), $rules)->validate();

We put that at the beginning of our function. You can read more about how to create rules in the documentation link I provided.
To validate before a date, you must go:
'audition_dates' =>'required|date|before:date'

Date must be according to strtotime, if you want to check against other fields, it may be:
'audition_dates' => 'required|date|before:shoot_dates'

A: I have found a solution.
[
  'audition_dates'   => 'required|array',
  'audition_dates.*' => 'date|after:tomorrow',
  'shoot_dates'      => 'required|array',
  'shoot_dates.*'    => 'date|after:audition_dates.*',
];


text:
Q: I can't get calendar.app from the iOS app store I can't download / get calendar app from the iOS app store. I just updated to iOS10 and when I finished I noticed that something was missing in my home screen. I took me a while to realize that I lost my calendar app.
When I tried to get it from the app store I just couldn't. I can push the "get" button that transform into a install button. When I tried to push install I just can't. I can get any other apps from the app store. Buy or just get it.
Is this a normal behavior?
Thanks!

A: Try to restart your device whit:

*

*On an iPhone 7 or iPhone 7 Plus: Press and hold both the Sleep/Wake and Volume Down buttons for at least ten seconds, until you see the Apple logo.

*On an iPhone 6s and earlier, iPad, or iPod touch: Press and hold both the Sleep/Wake and Home buttons for at least ten seconds, until you see the Apple logo.

If the problem persists, make sure you make all system updates.
Try an alternative to load a Backup of your device from iTunes to restore the calendar App.

A: I had similar issue on iOS 12. What helped me is reinstalling OS from scratch with the help of iTunes.

*

*Switch to the DFU mode (see link)

*Dialog window will appear in iTunes with message, that iPhone is broken and you can either Update or Recover. Press Recover (Update may work. I did not test this.)

*After that iTunes will start iOS download

*iPhone waits max 15 minutes. If download takes more than 15 minutes, iPhone does not wait longer and reboots (do not panic, ignore that for a while)

*After Download is completed, go to DFU mode again (if Phone has rebooted)

*After iTunes has finished Recovery process, phone will reboot

*Then pass standard procedure of the phone activation and configuration

At the end, I've got recovered device with all standard applications. What was weird is that I wasn't able to restore backup. I do not know why.
Also after I've executed "Erase All Content and Settings", I've lost my apps again.


text:
Q: Make div's height expand as per content height and width Here is my html structure

$('.product').click(function(){
  var $this = $(this).find('.product-desc');
  $(".product-desc").not($this).hide('slow');
  $this.toggle('slow');
})
.prod-container>.col-md-3 {
  padding: 0 6px;
}

.prooduct-title img {
  width: 100%;
  height: 100%;
}

/*.prooduct-title img {
    min-width: 70%;
    max-height: 105px;
    margin: 5px 20px;
}*/

.product {
  background: linear-gradient(-58deg, #0057a0, #00b8e1);
  color: #fff;
  text-transform: uppercase;
  margin: 12px 0;
  cursor: pointer;
      display: inline-block;
}

.prooduct-title {
  min-height: 105px;
  display: flex;
  height: 121px;
}

.prooduct-title>div {
  padding: 0;
}

.products-section .col-md-10 .col-md-3 {
  padding: 0 6px;
}

.products-section {
  margin: 7px 0;
}

.prod-title {
  /*padding: 10px!important;*/
  align-self: center;
  font-size: 17px;
}

.prod-title p {
  padding: 10px;
  margin-bottom: 0;
  line-height: 18px;
}

.product-desc ul {
  padding: 0px 0px 0 0px;
  margin: 0;
  text-transform: none;
  list-style: none;
  float: left;
}

.product-desc ul li {
  list-style-type: none;
  padding: 5px 18px 5px 28px;
  transition: all 0.5s ease-in-out;
}

.product-desc ul li:hover {
  background: rgba(0, 0, 0, 0.3);
}

.product-desc ul li a,
.product-desc ul li a:active,
.product-desc ul li a:focus,
.product-desc ul li a:hover {
  display: block;
  color: #fff;
  text-decoration: none;
}

.product-desc ul li>p:first-child {
  margin-bottom: 0;
  font-size: 16px;
  line-height: 18px;
  padding-bottom: 7px;
}

.product-desc ul li>p:last-child {
  margin-bottom: 5px;
  font-size: 13px;
}

.product-desc ul li a>p:last-child {
  font-size: 12px;
  padding-left: 10px;
  margin-bottom: 0;
}

.vertical-track {
  width: 5px;
  background-color: rgba(0, 0, 0, 0.3);
}

.vertical-handle {
  width: 100%;
  border-radius: 0px;
  background-color: #fff;
}

.product-desc ul+div {
  right: 10px!important;
  left: auto!important;
}

.search-results {
  background: rgba(233, 233, 233, 0.9);
  width: 100%;
  position: absolute;
  z-index: 1;
  border-bottom-left-radius: 0;
  border-bottom-right-radius: 0;
  -webkit-box-shadow: 0 10px 10px -10px #000000;
  -moz-box-shadow: 0 10px 10px -10px #000000;
  box-shadow: 0 10px 10px -10px #000000;
  z-index: 1000;
  top: 100%;
}

.results.default-skin.scrollable {
  border-radius: 0;
}

.results.default-skin.scrollable a {
  padding: 10px;
}

.results.default-skin.scrollable a:hover {
  background-color: #1a3a5f;
}

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum Lorem Ipsum is simply dummy

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Screw

0 Battle Card

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

Lorem Ipsum

jsfiddle
Now I want to expand like this on click.

I want to expand div as per content width and height, what can I do for this. When I click on div it's information is sliding down. Now I have to create like this, when I click on div it's parent's height and width should be change as per sliding content width and height.Please help.


text:
Q: How to fix dynamic height for individual cells as UIautodimensions is not working I am creating a wall page like twitter or Facebook in which user can post on the wall it can include image and just text. So based on the content the cell's heights must change, if the post is of one line the row height must be appropriate.
I tried using UITableViewAutomaticDimensions, but its not working with my code please do help me.
import UIKit

class wallPageViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

var tableOfApps : UITableView?
var appNames: [String]? = []
var apps: [wallPageModel]?
var dynamic_height : CGFloat = 150.0
var addPost : UITextField?
var readMore : UITextView?

func loadTableOfApps(){

    //appNames = ["jkbajdba", "abfajfb", "akjbfkjag", "ahbfkajf" ]

    let provider = wallPageProvider()
    apps = provider.getApps()

    let tableHeight = view.frame.size.height

    tableOfApps = UITableView(frame: CGRect(x: 10, y: 60, width: 300, height: tableHeight))
    tableOfApps!.delegate = self
    tableOfApps!.dataSource = self
    tableOfApps?.separatorStyle = UITableViewCellSeparatorStyle.none

    //self.tableOfApps?.rowHeight = UITableViewAutomaticDimension
    //self.tableOfApps?.estimatedRowHeight = UITableViewAutomaticDimension
    print("load table of apps")

    view.addSubview(tableOfApps!)

}

override func viewDidLoad() {
    super.viewDidLoad()
    loadTableOfApps()
    loadAddPost()

    tableOfApps?.estimatedRowHeight = 150.0
    tableOfApps?.rowHeight = UITableViewAutomaticDimension

    view.backgroundColor = UIColor(red: 232/255, green: 234/255, blue: 246/255, alpha: 1.0)

    // Do any additional setup after loading the view.
}

func loadAddPost(){
    addPost = UITextField(frame: CGRect(x: 10, y: 20, width: 300, height: 30))
    addPost?.placeholder = "Stay safe, post a tip!"
    addPost?.isUserInteractionEnabled = true
    addPost?.borderStyle = UITextBorderStyle.roundedRect
    addPost?.autocapitalizationType = .none
    view.addSubview(addPost!)

    addPost?.addTarget(self, action: #selector(writeComment), for: UIControlEvents.touchDown)

}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

    print("app coun\(apps!.count)")
    return apps!.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    var cell : wallModelTableViewCell?

    cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? wallModelTableViewCell

    if cell == nil {
        cell = wallModelTableViewCell(style: UITableViewCellStyle.default, reuseIdentifier: "cell")
    }

    let app = apps![indexPath.row]//reading the array of data hence provider

    //association of provider and view
    //this is the processs from where view can read the data from provide

    cell!.iconImageLabel!.image = app.icon
    cell!.titleLabel!.text = app.title
    cell?.backgroundColor = UIColor.white

    cell!.commentsLabel?.image = app.comments_Label
    cell?.commentsLabel?.center = CGPoint(x: tableView.frame.size.width/2, y: dynamic_height-20)

    cell?.likeButtonLabel?.image = app.likeButton
    cell?.likeButtonLabel?.center = CGPoint(x: (tableView.frame.size.width/2)-130, y: dynamic_height-20)
    /*cell?.likeButtonLabel?.leftAnchor.constraint(equalTo: tableView.leftAnchor, constant: 50)*/

    cell!.feedTextLabel!.text = app.feedText
    cell?.feedTextLabel?.sizeToFit()//so that it can expand the data more than two lines
    cell?.feedTextLabel?.backgroundColor = UIColor.clear

    //Limiting UIlabel to 125 characters
    if (cell?.feedTextLabel?.text.count)! > 125{
        /*
        let index = cell?.feedTextLabel?.text.index((cell?.feedTextLabel?.text.startIndex)!, offsetBy: 125)
        cell?.feedTextLabel?.text = cell?.feedTextLabel?.text.substring(to: index!)
        cell?.feedTextLabel?.text = cell?.feedTextLabel?.text.appending("...")*/
        //cell?.feedTextLabel?.attributedText = NSAttributedString(string: "...readmore")
    }

    cell?.layer.cornerRadius = 6.0
    cell?.isUserInteractionEnabled = false

    cell?.titleLabel?.isUserInteractionEnabled = true

    tableOfApps?.backgroundColor = UIColor.clear
    tableOfApps?.backgroundView?.isOpaque = false

    tableOfApps!.estimatedRowHeight = 150.0
    tableOfApps!.rowHeight = UITableViewAutomaticDimension

    print("table view cell for row")

    /*let tap: UITapGestureRecognizer  = UITapGestureRecognizer(target: self, action: #selector( self.labelAction(gesture:)))
    cell?.feedTextLabel?.addGestureRecognizer(tap)
    cell?.feedTextLabel?.isUserInteractionEnabled = true
    tap.delegate = self as! UIGestureRecognizerDelegate*/

    return cell!

}

/*@objc func labelAction(gesture: UITapGestureRecognizer){

}*/

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    print("height for row")
    return UITableViewAutomaticDimension
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return 150.0
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

 // MARK: - Navigation
 @objc func writeComment(){
 let addComment = addCommentViewController()
 navigationController?.pushViewController(addComment, animated: true)
 }
/*
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
 // Get the new view controller using segue.destinationViewController.
 // Pass the selected object to the new view controller.
 }
 */

}

I want each row must have dynamic height as the content is provided by the user if the content contains 150 characters the height of the cell must be 200+ if content contains less than 125 characters the height must be as adequate to read.


text:
Q: Symfony2 And Single Webpage Applications using a framework like AngularJS (If this is not the right place to post this kind of question I'd happily post it somewhere else)
I'm trying to build an interactive web application to manage company resources.
I have experience with Symfony2 but I kind of hit a wall with this new application.
I'd like to make this application quite interactive on the client side. Almost a full single webpage application.
My previous web applications would normally just use a typical MVC pattern with CRUD pages.
In those simple applications I would have
/employees/
/employees/create
/employees/detail/45
/employees/update/45
/employees/delete/45

Using symfony in this kind of application would give me a lot of advantages:

*

*Routing

*Security (CSRF tokens)

*FormTypes and Form handling

*Validation

*Integration with Doctrine

*Twig

Especially functionality like this in Twig was very refreshing (since my models were build as Doctrine entities):

{{ employee.getCurrentTask().description }}

The problem I'm facing now is that I feel like Symfony2 isn't really build for single webpage applications. As soon as I try to add some Ajax functionality I'm faced with these problems:

*

*CSRF tokens invalid

*Too much non reusable view/presentation logic in jQuery

*Adding data-attributes in html to get id's etc...

I then looked into Knockout.js and Angularjs but then I feel like lose all of the advantages of Doctrine and Twig. I have to rebuild my models on the client side anyway and have to maintain them in two different locations then.
So I came up with this idea:

*

*Use Symfony2 models and controllers to persist data to the database but let controllers in symfony just send out JSON and receive JSON (FOSRestBundle maybe?)

*Use a framework like AngularJS or KnockoutJS to rebuild that JSON data on the client side to use 2-way binding.

But then how would I tackle the issues like Doctrine2 Relationships, Form Validation, CSRF which Symfony already solved but are unusable if I use a frontend js framework?
All suggestions are welcome!

A: You don't need to rebuild the model in client. I normally just create a service in angularjs that provides json data. Data manipulation still happens server side using ajax.
For forms that requires csrf, I normally just send the html rendered by twig via json. Or you can serialize $form->createView() with jms serializer. However you will need some client script  to transform the json data to actual form controls.

A: Some words about JSON, Serialization and Models
Simon, I faced exactly the same questions and problems. First like ken already mentioned. You don't need to rebuild any model. Better use FosRestBundle and/or JMS Serializer. It turns you entities with relations into JSON objects. This objects are transferred via api to your frontend and you can work with them just like in twig, when you use angular.js like this
{[{ user.username }]}

is as same as in twig. But remember that you have to set custom brackets for angular because by default it uses the same as twig.
Routing
You talk of a single page application, so symfony's routing is kept on a low level to have few page refresh. Instead you have to use routing of your frontend framework, because I am only familiar with angular.js, I give an angular example:
app.config(function($routeProvider, $interpolateProvider) {

    //here you go, custom brackets
    $interpolateProvider.startSymbol('{[{');
    $interpolateProvider.endSymbol('}]}');

    $routeProvider.when('/user', {
        controller: UserController,
        templateUrl: Routing.generate('suser_list')
    }).when('/ticket', {
        controller: TicketController,
        templateUrl: Routing.generate('ticket_list')
    });
});

When you hit a link like
Go to tickets

AngularJs will know which frontend controller to trigger. Pretty great stuff, without page reload. Also have a look at FosJSRoutingBundle. It allows you to generate symfony routes in javascript, I use them to link js controllers with html templates where data is pushed in.
FormTypes, Form handling, Validation
Well, when you use a frontend framework like angularjs, your symfony form types are pretty useless. But I am not sure. Remember data is pushed and pulled via api as json, I think this would be a hard job for form types to handle this kind of compexity.
For validation you can use angular's live validation or have you symfony's validation in the backend, no problem. It might be a good thing to use both, client and server side validation.
Twig
Twig is out of the race. All data is rendered on the client side, and not pre rendered on server side like with twig. But that is only the case if your application is really a single page application. Of course you can use twig, but it will only refresh if you reload the entire page.
Integration with Doctrine
You can still use doctrine in the backend. Do you have a specific question regarding doctrine and SPA?


text:
Q: Passing python variable to sql I have a python script that I want to extract data to a list from a DB, and then print it out.
Here is the code:
sql = "SELECT * FROM example WHERE column1 == 'string_value' AND column2 = float_value AND column3 == 'string_value'"
 # Assemble list.
query = []
for row in c.execute(sql):
    query.append(row)

This runs fine. When I debug i see sql is a string and the loop runs fine and assembles the list. When I however try to use variables for the sql query columns values using string formatting like this:
sql = "SELECT * FROM example WHERE column1 = %s AND column2 = %s  AND column3 = %s ",(var1_str, var2_float, var3_str)

I get a:
 for row in c.execute(sql):
ValueError: operation parameter must be str

and I cannot run the loop to assemble the list. Debugging this  I see 'sql' is now a tuple and not a string.Why is that?
Is there a better way to do this than what I am using. This is my first venture into SQL and Python so I am new to this.
Thanks you for any suggestions.

A:
ValueError: operation parameter must be str

What is happening is that sql variable is a tuple, but execute() expects to see a string as the first positional parameter. What you meant was to parameterize the query by passing the query parameters to execute() separately:
sql = "SELECT * FROM example WHERE column1 = %s AND column2 = %s  AND column3 = %s "
c.execute(sql, (var1_str, var2_float, var3_str))

for row in c.fetchall():
    query.append(row)

A: "AND column3 = %s ",(var1_str, var2_float, var3_str)

String formatting requires a percent sign.
"AND column3 = %s " % (var1_str, var2_float, var3_str)

Not that I condone using string formatting when forming a sql query. If any of those values come from an untrusted source, you're opening yourself up to SQL injection attacks. Check the documentation of your DB interface to see if it has a safer way of including parameters.


text:
Q: Calculating Pi using Monte Carlo method in parallel I have been trying to calculate the value of pi using Monte Carlo simulation in parallel.
So far, I have created threads, and generated the random points, but I'm not able to return those generated points back from the threads to the main thread.
How to tackle this problem ?
Below is the code I have written
import java.util.*;

class MyThread extends Thread{
    int points;
    int insidePoints;

    public MyThread(int insidePoints, int points){
      this.points = points;
      this.insidePoints = insidePoints;
    }

    // simulating monte carlo to generate points and check which are inside the circle
    public void run(){
          int prec = 1000000;
          Random rand = new Random();
          for( int i=0 ; i < points ; ++i){
              double x = (double)rand.nextInt(prec+1)/(double)prec;
              double y = (double)rand.nextInt(prec+1)/(double)prec;

             if( (x*x + y*y) <= 1){
                ++insidePoints;
             }
         }
         System.out.println("Thread " + Thread.currentThread().getId() + " running and Inside points are" + insidePoints);
    }

    public int getCount(){
         return this.insidePoints;
    }
}

public class A{

    public static void main(String[] args){

        int totalPoints = 1000000;
            int insidePoints = 0;
            int threadsToBeUsed = 1;

            Scanner scan = new Scanner(System.in);
            System.out.println("Enter the value of Threads : ");
            threadsToBeUsed = scan.nextInt();

             try{
                int eachThreadPoints = totalPoints/threadsToBeUsed;
                Thread[] thread = new Thread[threadsToBeUsed];

                for(int i = 0; i < threadsToBeUsed ; ++i){
                    if( i == (threadsToBeUsed-1)){
                       eachThreadPoints += (totalPoints)%eachThreadPoints ;
                    }
                 MyThread myT = new MyThread(insidePoints, eachThreadPoints);
                 thread[i] = new Thread(myT);
                 thread[i].start();
              }

              for( int  i=0; i < threadsToBeUsed; ++i)
                 thread[i].join();

               System.out.println("Number of inside points :" + insidePoints);
               System.out.println("Pi/4 = " + (double)insidePoints/(double)totalPoints);
               System.out.println("Pi   = " + 4*(double)insidePoints/(double)totalPoints);

               } catch(Exception e){
                   System.out.println(e);
                   System.exit(1);
               }
          }
}

A: As an alternative approach, you can use Java Executor Interface, which offers a higher-level abstraction than handling the threads explicitly. Moreover, you might consider the use of the ThreadLocalRandom:

A random number generator isolated to the current thread. Like the
global Random generator used by the Math class, a ThreadLocalRandom is
initialized with an internally generated seed that may not otherwise
be modified. When applicable, use of ThreadLocalRandom rather than
shared Random objects in concurrent programs will typically encounter
much less overhead and contention. Use of ThreadLocalRandom is
particularly appropriate when multiple tasks (for example, each a
ForkJoinTask) use random numbers in parallel in thread pools.

Back to your question:

but I'm not able to return those generated points back from thread to
main function.

You can take advantage of the Executor interface and submit a task that returns a Java Future:

A Future represents the result of an asynchronous computation. Methods
are provided to check if the computation is complete, to wait for its
completion, and to retrieve the result of the computation. The result
can only be retrieved using method get when the computation has
completed, blocking if necessary until it is ready.

Each thread computes the number of points inside and returns that value as a Future to the main thread. The main thread, in turn, sums all the values returned by the other threads.
So code-wise, one would create a pool of threads
ExecutorService pool = Executors.newFixedThreadPool(threadsToBeUsed);

then a list to collect the results
    List<Future<Integer>> results = new ArrayList<>(threadsToBeUsed);

and then submit the work to be done in parallel
   for(int i = 0; i < threadsToBeUsed; i++){
       Future<Integer> insidePointsThr = pool.submit(new task(eachThreadPoints));
       results.add(insidePointsThr);
   }

Make the main thread sum all the results from the other threads:
  int insidePoints = results.stream().mapToInt(f -> f.get()).sum();

Print the results, and shutdown the pool of threads:
pool.shutdown();

A running code example (based on the code that you have provided):
import java.util.*;
import java.util.concurrent.*;

class task implements Callable<Integer> {
    final int points;

    public task(int points){
        this.points = points;
    }

    @Override
    public Integer call() {
        int insidePoints = 0;
        int prec = 1000000;
        for( int i=0 ; i < points ; ++i){
            double x = (double)ThreadLocalRandom.current().nextInt(prec + 1)/(double)prec;
            double y = (double)ThreadLocalRandom.current().nextInt(prec + 1)/(double)prec;
            if( (x*x + y*y) <= 1){
                ++insidePoints;
            }
        }
        System.out.println("Thread " + Thread.currentThread().getId() + " running and Inside points are " + insidePoints);
        return insidePoints;
    }
}

class A{
    public static void main(String[] args){
        int totalPoints = 1000000;
        Scanner scan = new Scanner(System.in);
        System.out.println("Enter the value of Threads : ");
        int threadsToBeUsed = scan.nextInt();

        int eachThreadPoints = totalPoints/threadsToBeUsed;
        ExecutorService pool = Executors.newFixedThreadPool(threadsToBeUsed);
        List<Future<Integer>> results = new ArrayList<>(threadsToBeUsed);
        for(int i = 0; i < threadsToBeUsed; i++){
            Future<Integer> insidePointsThr = pool.submit(new task(eachThreadPoints));
            results.add(insidePointsThr);
        }
        int insidePoints = results.stream().mapToInt(A::getFutureResult).sum();

        System.out.println("Number of inside points :" + insidePoints);
        System.out.println("Pi/4 = " + (double)insidePoints/(double)totalPoints);
        System.out.println("Pi   = " + 4*(double)insidePoints/(double)totalPoints);

        pool.shutdown();
    }

    private static int getFutureResult(Future<Integer> f) {
        try {
            return f.get();
        } catch (InterruptedException | ExecutionException e) {
            // handle the error
        }
        return 0;
    }
}

Output (for 4 threads):
Enter the value of Threads :
4
Thread 16 running and Inside points are 196447
Thread 17 running and Inside points are 196147
Thread 15 running and Inside points are 196076
Thread 14 running and Inside points are 196795
Number of inside points :785465
Pi/4 = 0.785465
Pi   = 3.14186