text:
Q: Why do I get a segmentation fault when I allocate memory for a matrix? I am working on an MPI program with matrixes. I need 5 matrixes in each process. When I create the 5th matrix, I get a segmentation fault.
Here are some screenshots:
Here it work, when the sPrevParts matrix is commented out

Here it does a segmentation fault! :s

Here again the segmentation fault...

Here is this part of the code (if you need the whole code, tell me, please).
MATRIX_CREATE FUNCTION
    /* M(m*n) as array of rows, call free(p) */
    void **matrix_create(size_t m, size_t n, size_t size) {
       size_t i;
       void **p= (void **) malloc(m*n*size+ m*sizeof(void *));
       char *c=  (char*) (p+m);
       for(i=0; i<m; ++i)
          p[i]= (void *) c+i*n*size;
       return p;
    }

MAIN
    /* Variables for the partial matrixes */
    double **aParts, **mParts, **mPrevParts, **sParts, **sPrevParts;
    /* Gets the rows of the partial matrixes of each process */
    rows = sendcounts[myrank] / n;
    /* Allocates memory for the partial A matrix of each process */
    aParts = (double**)matrix_create(rows, n, sizeof(double));
    /* Allocates memory for the partial M matrix of each process */
    mParts = (double**)matrix_create(rows, n, sizeof(double));
    /* Allocates memory for the partial S matrix of each process */
    sParts = (double**)matrix_create(rows, n, sizeof(double));
    /* Allocates memory for the previous partial M matrix of each process */
    mPrevParts = (double**)matrix_create(rows, n, sizeof(double));
    /* Allocates memory for the previous partial S matrix of each process */
    //PrevParts = (double**)matrix_create(rows, n, sizeof(double));

    MPI_Barrier(MPI_COMM_WORLD);

    /* Scatters the A matrix through all the processes */
    MPI_Scatterv(&a[0][0], sendcounts, displs, MPI_DOUBLE, &aParts[0][0], sendcounts[myrank], MPI_DOUBLE, root, MPI_COMM_WORLD);
    /* Scatters the M matrix through all the processes */
    MPI_Scatterv(&m[0][0], sendcounts, displs, MPI_DOUBLE, &mParts[0][0], sendcounts[myrank], MPI_DOUBLE, root, MPI_COMM_WORLD);
    MPI_Scatterv(&m[0][0], sendcounts, displs, MPI_DOUBLE, &mPrevParts[0][0], sendcounts[myrank], MPI_DOUBLE, root, MPI_COMM_WORLD);
    /* Scatters the S matrix through all the processes */
    MPI_Scatterv(&s[0][0], sendcounts, displs, MPI_DOUBLE, &sParts[0][0], sendcounts[myrank], MPI_DOUBLE, root, MPI_COMM_WORLD);
    //MPI_Scatterv(&s[0][0], sendcounts, displs, MPI_DOUBLE, &sPrevParts[0][0], sendcounts[myrank], MPI_DOUBLE, root, MPI_COMM_WORLD);

    int i;
    for (i = 0; i < npes; ++i) {
        MPI_Barrier(MPI_COMM_WORLD);
        if (myrank == i) {
            printf("%d\n", i);
            matrix_print(aParts, rows, n, "aParts");
            matrix_print(mParts, rows, n, "mParts");
            matrix_print(sParts, rows, n, "sParts");
            matrix_print(mPrevParts, rows, n, "mPrevParts");
        }
    }

NOTE: This is being run by ALL the processes.
Could it be that I have used up all the memory? How can I fix this? Thanks

A: The void * gives it away:
malloc(m*n*size+ m*sizeof(void *));

You never actually allocate your matrix, but instead only a 2D array of pointers which you then treat as an array of double.

*

*Don't ever do that.

*You are probably developing with a 32-bit run-time, where your pointers are only half the size of double (or some other kind of system where pointers are simply smaller than double).

Consider this example for a basic reference on how to work with matrices when using MPI.


text:
Q: How to create a reg exp to parse such url? So we have http://127.0.0.1:4773/robot10382.flv?action=read we need to get out from it protocol, ip/adress, port, actual url (robot10382.flv here) and actions (action=read here) how to parse all that into string vars in one reg exp?

A: I'm surprised that AS3 does not include proper URL parsing facilities.  To put it simply, it is not easy to safely parse a URL using an RE.  Here's an example of doing it though.

A: /(\w+)\:\/\/(\d+\.\d+\.\d+\.\d+)\:(\d+)\/(\w+)\?(.+)/ : $1 - protocol, $2 - ip, $3 - port, $4 - actual url, $5 - actions
there's also another way:
protocol : url.split('://')[0]
ip/domain name : url.split('://')[1].split(':')[0] (or if no port specified - url.split('://')[1].split('/)[0]
port : url.split('://')[1].split(':')[1].split('/')[0]
actual url : url.split('?')[0].split('/').reverse()[0]
actions : url.split('?')[1].split('&')/*the most possible separator imho*/ elements of this array can also be spliced('=') to separate variable names and values.
i know there's an opinion that splice shouldn't be used, but i think it's just beautiful when used properly.

A: Sometimes when passing a file path to a SWF you would like to perform FileExistance check before passing the file to an AS3 class. To do so you want to know if a URI is a file or an http URL or any other URI with specific protocol (moniker).
The following code will tell you if you are dealing with a local full or relative path.
http://younsi.blogspot.com/2009/08/as3-uri-parser-and-code-sequence-to.html

redpajama_set_name: RedPajamaStackExchange


text:
Q: Electronic test clip (hook/grabber): how to open it up? How do I properly disassemble one of these hooked test clips? The wire broke off: you can see the tiny remainder inside the oval hole. I want to fix / re-solder the wire, but how do I open up the plastic tube enclosure to get to the inside? I see copper/plastic moving parts inside, but no obvious way (like a paperclip hole etc) to unlock the mechanism.

A: Grab the smaller moving part with one hand (left side in the picture), and the right side plastic hooky part with the other hand, and pull.


text:
Q: Definite integral as dot product I was reading examples of dot products and I came across the following:

In the vector space $P_n(\mathbb{R})$ of polynomials with degree less or equal to $n$ we consider the following dot product:$$\langle p(x),q(x)\rangle:=\int _{0} ^1 p(x)q(x)dx\quad$$

I don't see why this is a dot product. In particular I don't see how it is positive definite.
$$\langle p(x),p(x)\rangle=\int _{0} ^1 (p(x))^2 dx\quad$$
Why is the above always greater or equal to zero?

A: Obviously, $p(x)^2 \geq 0$ for any $x \in \mathbb{R}$. Hence, $\int_0^1 p(x)^2 \mathrm{d}x \geq 0$. However, this was the easy part of the first condition for something to be an inner product. The harder part of proving that what you have defined is indeed an inner product is to show that it is non-degenerate, i.e. $\langle p(x), p(x) \rangle = 0 \implies p(x) = 0$ and I believe you haven't shown this if you got stuck in showing that it's non-negative.
It is a well known theorem in Riemann integration that if $f(x) \geq 0$ for all $x\in  [a,b]$ then
$$\int_a^b f(x) \mathrm{d}x = 0 \implies f(x) = 0 \text{ on the interval } [a,b]$$
Here, you have $p(x)^2 \geq 0$ for any $x$ in $[0,1]$. Hence, the above theorem implies that $p(x)=0$ on $[0,1]$.
So, the polynomial $p(x)$ has infinitely many roots! Therefore, $p(x)$ must be the zero polynomial because a non-zero polynomial of degree $n$ can have $n$ roots at most.
Remark: In general, the aforementioned theorem about Riemann integration only implies that $f(x)=0$ on the interval of integration, not all of $\mathbb{R}$. However, polynomials are very rigid objects in the sense that if a polynomial becomes constant on an interval, it must be constant everywhere. So, in this particular problem, the fact that we are defining the inner product on polynomials of degree at most $n$ is crucial and should not be overlooked.


text:
Q: Make text scroll using marquee when item checked I use a checkable listview ( I've set : Mylistview.setChoiceMode(1)).
Inside each row I have 2 ImageViews and 2 TextViews.
I'd like that when my item is checked, the text inside the TextViews scrolls if the text is too long. So in the XML of my row, I've assign the following to both of my TextViews :
android:singleLine="true"
android:ellipsize="marquee"
android:marqueeRepeatLimit="marquee_forever"

Unfortunately, this will make the text scroll only if the item is focused and not checked.
So the solution I think about are :
1) Make my own Custom TextView class and make it focus itself when checked (I don't know if it is possible ?)
2) Put the focus to the checked item even if we're in touch mode (use SetFocusableInTouchMode)
I haven't achieved to do the 2nd solution and I don't know which method override if I want to make my own own Custom TextView.
Could you help me to make the text scroll when the item is checked ? Thanks.

A: You need to do something like following.
int scrollAmount = mTextView.getLayout().getLineTop(mTextView.getLineCount())
        -mTextView.getHeight();

// if there is no need to scroll, scrollAmount will be <=0
if(scrollAmount>0)
    mTextView.scrollTo(0, scrollAmount);
else
    mTextView.scrollTo(0,0);


text:
Q: Binding current foreground to Rectangle.Fill property I'm using Mahapps Metro theme in my project. I want to create TabControl where TabItem will be image. Mahapps theme provides changing color of TabItem's text when TabItem is selected etc. I want to bind this foreground color to my image.
I have the solution of this problem but I think it isn't correct.
'Bad' Code (but it's working):
<TabItem>
   <TabItem.HeaderTemplate>
      <DataTemplate>
         <Grid Margin="0,5,0,0">
            <TextBlock x:Name="myTextBlock" />
            <Rectangle Width="28.947" Height="25" Fill="{Binding ElementName=myTextBlock, Path=Foreground}">
               <Rectangle.OpacityMask>
                  <VisualBrush Stretch="Fill" Visual="{StaticResource appbar_image_gallery}" />
               </Rectangle.OpacityMask>
            </Rectangle>
         </Grid>
      </DataTemplate>
   </TabItem.HeaderTemplate>
</TabItem>

A: You can use TemplateBinding if you don't want to bind to the inner TextBlock.
<TabItem.HeaderTemplate>
    <DataTemplate>
        <Grid Margin="0 5 0 0">
            <TextBlock Text="{Binding}" />
            <Rectangle Width="28.947"
                        Height="25"
                        Fill="{TemplateBinding TextElement.Foreground}">
                <Rectangle.OpacityMask>
                    <VisualBrush Stretch="Fill" Visual="{DynamicResource appbar_image_gallery}" />
                </Rectangle.OpacityMask>
            </Rectangle>
        </Grid>
    </DataTemplate>
</TabItem.HeaderTemplate>


text:
Q: Fast way to convert react class component to functional component? I have a class component which works as expected but now I would like to change this class component to functional component
Here is my class
import React, { Component } from 'react'
import EventCalendar from '../App';
import moment from 'moment';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Button from 'react-bootstrap/Button';
import ButtonToolbar from 'react-bootstrap/ButtonToolbar';

const events =[
        {
            title: 'Womens History Month ',
            start: '2020-03-02',
            end: '2020-03-02',
            //description: '',
            url: 'dev91b558163211cf9d2e7d1efe6c3e32035973fdf9',
            eventClasses: 'event1'

        },
];

export class CalendarDemo extends Component {
    constructor(props) {
        super(props);

        this.state = {
            moment: moment(),

        };

        this.handleNextMonth = this.handleNextMonth.bind(this);
        this.handlePreviousMonth = this.handlePreviousMonth.bind(this);
        this.handleToday = this.handleToday.bind(this);
        this.handleEventClick = this.handleEventClick.bind(this);
        this.handleEventMouseOver = this.handleEventMouseOver.bind(this);
        this.handleEventMouseOut = this.handleEventMouseOut.bind(this);
        this.handleDayClick = this.handleDayClick.bind(this);
    }

    handleNextMonth() {
        this.setState({
            moment: this.state.moment.add(1, 'M'),
        });
    }

    handlePreviousMonth() {
        this.setState({
            moment: this.state.moment.subtract(1, 'M'),
        });
    }

    handleToday() {
        this.setState({
            moment: moment(),
        });
    }

    handleEventMouseOver(target, eventData, day) {
      console.log("event data", target.props.eventData.url);
        this.setState({

        });
    }

    handleEventMouseOut(target, eventData, day) {
        this.setState({

        });
    }

    handleEventClick(target, eventData, day) {
        this.setState({

        });
    }

    handleDayClick(target, day) {
        this.setState({

        });
    }

    getMomentFromDay(day) {
        return moment().set({
            'year': day.year,
            'month': (day.month + 0) % 12,
            'date': day.day,

        });
    }

    getHumanDate() {
        return [moment.months('MM', this.state.moment.month()), this.state.moment.year(), ].join(' ');
    }

    render() {

        return (

                    <Row className='topBar'>
                        <Col xs={6}>
                            <ButtonToolbar>
                                <Button onClick={this.handlePreviousMonth}><</Button>
                                <Button onClick={this.handleNextMonth}>></Button>
                                <Button onClick={this.handleToday}>Today</Button>
                            </ButtonToolbar>
                        </Col>
                        <Col xs={6}>

{this.getHumanDate()}

                        </Col>
                    </Row>

                    <Row>
                        <Col xs={12}>
                            <EventCalendar
                                month={this.state.moment.month()}
                                year={this.state.moment.year()}
                                events={events}
                                onEventClick={this.handleEventClick}
                                onEventMouseOver={this.handleEventMouseOver}
                                onEventMouseOut={this.handleEventMouseOut}
                                onDayClick={this.handleDayClick}
                                maxEventSlots={0}
                            />
                        </Col>
                    </Row>

        );
    }
}

export default CalendarDemo

    const styles = {
            position: 'relative',
        };

What do I need to change here so that I will get a functional component?

A: Every method has to be changed to const method = () => ..., every lifecycle has to be changed to a useState/useEffect, the render should be be the return value of the functional component.
import React, { Component, useState } from 'react'
import EventCalendar from '../App';
import moment from 'moment';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Button from 'react-bootstrap/Button';
import ButtonToolbar from 'react-bootstrap/ButtonToolbar';

const events =[
        {
            title: 'Womens History Month ',
            start: '2020-03-02',
            end: '2020-03-02',
            //description: '',
            url: 'dev91b558163211cf9d2e7d1efe6c3e32035973fdf9',
            eventClasses: 'event1'

        },
];

export const CalendarDemo = (props) => {
    const [_moment, updateMoment] = useState(moment());

    const handleNextMonth = () => {
        updateMoment(_moment.add(1, "M").clone());
    }

    const handlePreviousMonth = () => {
        updateMoment(_moment.subtract(1, "M").clone());
    }

    const handleToday = () => {
        updateMoment(moment());
    }

    const handleEventMouseOver = (target, eventData, day)  => {
        console.log("event data", target.props.eventData.url);
    }

    const handleEventMouseOut = (target, eventData, day) => {

    }

    const handleEventClick = (target, eventData, data) => {

    }

    const handleDayClick = (target, day) => {

    }

    const getMomentFromDay = day => {
        return moment().set({
            'year': day.year,
            'month': (day.month + 0) % 12,
            'date': day.day,

        });
    }

    const getHumanDate = () => {
        return [moment.months('MM', _moment.month()), _moment.year(), ].join(' ');
    }

    return (

                <Row className='topBar'>
                    <Col xs={6}>
                        <ButtonToolbar>
                            <Button onClick={handlePreviousMonth}><</Button>
                            <Button onClick={handleNextMonth}>></Button>
                            <Button onClick={handleToday}>Today</Button>
                        </ButtonToolbar>
                    </Col>
                    <Col xs={6}>

{getHumanDate()}

                    </Col>
                </Row>

                <Row>
                    <Col xs={12}>
                        <EventCalendar
                            month={_moment.month()}
                            year={_moment.year()}
                            events={events}
                            onEventClick={handleEventClick}
                            onEventMouseOver={handleEventMouseOver}
                            onEventMouseOut={handleEventMouseOut}
                            onDayClick={handleDayClick}
                            maxEventSlots={0}
                        />
                    </Col>
                </Row>

    );
}

export default CalendarDemo

    const styles = {
            position: 'relative',
        };

A: *

*convert every class method func to an inner function (either using function func() {} or using const func = () => {})

*convert every attribute attr in your state to a const [attr, setAttr] = useState() call. Then replace every call to this.state.attr with attr and every call of this.setState({attr: newValue}) with setAttr(newValue)

*Keep your render() function mostly as-is, just remove the outer function, remove every this. prefix when referencing function and replace every reference to this.state as described above

*(Not present in your example): Replace componentDidMount with useEffect

*Replace class CalendarDemo extends Component with function CalendarDemo() (use arrow-syntax, if you like)

A: Notes:

*

*this.state bindings need to be converted to useState hooks

*You'll need to export a function instead of Class as the default export

*I didn't add the onHandleClick methods as they weren't supplied in the example.

import React, { useState, Component } from "react"
import EventCalendar from '../App';
import moment from 'moment';
import Row from 'react-bootstrap/Row';
import Col from 'react-bootstrap/Col';
import Button from 'react-bootstrap/Button';
import ButtonToolbar from 'react-bootstrap/ButtonToolbar';

const events = [
  {
    title: 'Womens History Month ',
    start: '2020-03-02',
    end: '2020-03-02',
    //description: '',
    url: 'dev91b558163211cf9d2e7d1efe6c3e32035973fdf9',
    eventClasses: 'event1'

  },
];

const CalendarComponent = (props) => {

  const [momentState, updateMoment] = useState(moment())

  const handlePreviousMonth = () => updateMoment(moment().subtract(1, 'M'));
  const handleNextMonth = () => updateMoment(moment().add(1, 'M'));
  const handleToday = () => updateMoment(moment())

  const getHumanDate = () => {
    return [
      moment.months('MM', momentState.month()),
      momentState.year(),
    ].join(' ');
  }

  // todo
  // const handleEventClick =
  // const handleEventMouseOver =
  // const handleEventMouseOut =
  // const handleDayClick =

  return (

      <Row className='topBar'>
        <Col xs={6}>
          <ButtonToolbar>
            <Button onClick={handlePreviousMonth}><</Button>
            <Button onClick={handleNextMonth}>></Button>
            <Button onClick={handleToday}>Today</Button>
          </ButtonToolbar>
        </Col>
        <Col xs={6}>

{getHumanDate()}

        </Col>
      </Row>

      <Row>
        <Col xs={12}>
          <EventCalendar
            month={momentState.month()}
            year={momentState.year()}
            events={events}
            // onEventClick={handleEventClick}
            // onEventMouseOver={handleEventMouseOver}
            // onEventMouseOut={handleEventMouseOut}
            // onDayClick={handleDayClick}
            maxEventSlots={0}
          />
        </Col>
      </Row>

  );
}

export default CalendarComponent


text:
Q: Incrementing and printing variable in the same for loop I am trying to increment variable x in a for loop and print it on each iteration.
include <stdio.h>

int x = 0;

void main()
{
    int c;
    for (c = 1; c <= 5; c++)

        x++;
        printf("%d", x);

}

The output I want is:
12345

However this code only prints:
5

When I do not increment x, I am able to print on every iteration:
# include <stdio.h>

int x = 0;

void main()
{
    int c;
    for (c = 1; c <= 5; c++)

        //x++;
        printf("%d", x);

}

Outputs:
00000

Why does incrementing x in the loop change the behaviour of printf?

A: The problem is, you are missing a block scope here.
The statements
for (c = 1; c <= 5; c++)

    x++;
    printf("%d", x);

is the same as
for (c = 1; c <= 5; c++)
{
    x++;
}
printf("%d", x);

so, your print statement is not part of the loop.
On the other hand, when you comment the x++; statement, the printf() statement is considered as the body of the loop.
You need to enforce the block using braces, like
for (c = 1; c <= 5; c++)
{
    x++;
    printf("%d", x);
}

A: The body of your for loop comprises just one command, i.e. x++;. Note that the compiler does not care about indentation but just about curly braces.
Write...
for (c = 1; c <= 5; c++) {
    x++;
    printf("%d", x);
}


text:
Q: In Far Cry 3 how can you equip a weapon you already own? I own an AK-47 (shows as "owned" in store/buy/assault rifile) but holding 1 for the weapon switcher just shows my M133 shotgun.
What happened to my AK-47? How can I equip it again?

A: Go to one of the weapon shops, select the AK-47 and press 'Equip' at the bottom of the screen. That should do it :)

A: As far as I can tell, you have to be at the store or self serve in a safe house. Just act like you're going to buy a waapon, click on owned, select a slot.


text:
Q: Symfony 3 routes + VueJS's index.html with F5 falls to 404 I try connect Vue.js with Symfony 3, but have no idea how to create proper route configuration for it.
Project tree looks like that:
Project root
  - app/
    - Resources/
      - views/
        - default/
  - web/
    - assets/
    - static/
    index.html     // here Vue is included

From Symfony I provide some REST API, the routes to it are prefixed by /api/. And I have some routes in Vue SPA.
The problem is if I press F5 in browser on any Vue route, which of course is not included in my routing.yml, browser returns 404 error from Symfony.
One half-working decision is when I put content of index.html to Resourses/views/default/twig with such a route:
fallback_for_vue:
    path: /{req}
    defaults: { _controller: 'AppBundle:Default:index' }
    requirements:
        req: ".+"

,taken from another question, but this is not actually what I need, because I don't want my frontend programmer to go somewhere except web/ folder.
So which configuration of Symfony routes I should use?

A: You need a wildcard address to point to your Vue.js application. Otherwise when you reload you send a request to Symfony, and it doesn't know hoy to handle it.
vuejs_wildcard_route:
    defaults:  { _controller: AppBundle:YourController:yourAction }
    path:   /vuejsappbasepath/{whatever}
    requirements:
        whatever: .*
    defaults:
        whatever: null

I have this setup working with a reactjs app and is working perfectly.
YourController is the controller that contains yourAction, the one that loads the template with the Vue.js panel.


text:
Q: Sharepoint list formatting- contact card with hover for more text information I am trying to format a list view by tailoring samples from github. I am trying to create a user profile card where you hover over the card and information about the person is shown like a short bio of the person.
The profile card is here:
https://github.com/pnp/List-Formatting/tree/master/view-samples/profile-card
Its good as it allows inserting your own image.
The hover feature would be great to take from this one here:
https://github.com/pnp/List-Formatting/tree/master/view-samples/horse-crests
This would allow the more information to be highlighted. I am just really struggling to create a hybrid of the two.
If anyone can help, I would really appreciate it. Many thanks.
Edit- I have also posted here: https://sharepoint.stackexchange.com/questions/302525/sharepoint-list-formatting-contact-card-image-name-and-title-with-hover-for-mo


text:
Q: Could ReSharper highlight errors instead of underlining them? R# has two ways of notifying me of problems in my code. One is highlighting the whole text, which I love and which could be seen from the far end of the room:

And the other is ugly curly underlining:

And so far I haven't found the color which make the second one at least close in its visibility to the first one. It's just invisible on the dark background.
I also know that first one (nice) is called Resharper Error Highlighting and the second one is Resharper Underlined Error Highlighting.
Could R# always be nice and highlight the errors so I could see them?

A: Unfortunately, you can change the colours for the underlines, but not how it affects the text, because it doesn't touch the text - it only draws the underline.
(And I've kicked off an internal discussion as to why we have two different ways of showing errors.)

A: Class names are colored as classes, methods as methods, string as strings, and so on — and if some word does not look like any of those, then R# paints it red to indicate that it can't understand the reference. Once the reference is known, it gets colored after to its kind.
If there're further errors, they're wavy-underlined without spoiling the text color. There might be looong highlightings, and usually we don't want the text under them to look all plain red. Also I believe the errors shan't be standing out too much, or they will distract from the text one is trying to correct. Why, if the error is under the caret, you'll see it anyway. And if it's not, you often don't care looking at it until you jump there with Alt+PgDn or Alt+Shift+PgDn or by clicking the error indicator at the top-right corner.
What is the scenario for seeing all the errors?
Making the wavy underline brighter is a viable option though. Should we have an option to make the line thicker? Or maybe make a transparent red overlay?


text:
Q: Eliminating a variable using three equations Given positive numbers $r$, $q$ $k$ and $N$ satisfying
$$\frac{1}{r} + \frac{N-1}{2q} = \frac{1}{2}- \frac{kN}{2}$$
and
$$R = \frac{2(1+k)r}{r-1}$$ and $$Q=\frac{2(1+k)q}{q-1},$$
I want to show that
$$\frac{1}{R} + \frac{N-1}{2Q} = \frac{N}{4}.$$
I tried for a long time and i couldn't show it. I wonder if it's even true. Can someone help me with this?

A: It is true!
Inserting the given equations for $R$ and $Q$ into your final equation we get:
$$\frac{1}{\frac{2(1+k)r}{r-1}} + \frac{N-1}{4\frac{(1+k)q}{q-1}} \stackrel{?}{=} \frac{N}{4} \leftrightarrow$$ $$\frac{2(r-1)}{r} +\frac{(N-1)(q-1)}{q}\stackrel{?}{=}N(1+k) \leftrightarrow$$
$$1- \frac{2}{r}+\frac{1}{q}+N(1-\frac{1}{q}-1-k)\stackrel{?}{=}0 \leftrightarrow$$
$$N \left( k+\frac{1}{q} \right)\stackrel{?}{=}1+\frac{1}{q}-\frac{2}{r}$$
Starting from the other end, with the first equation, we get:
$$\frac{N}{q}-\frac{1}{q}+kN +\frac{2}{r}-1 = 0 \leftrightarrow$$
$$N \left( k+\frac{1}{q} \right)=1+\frac{1}{q}-\frac{2}{r}$$
which is exactly the same as before!

A: Plugging the inverses of the second and third relations in the fourth, you get
$$\frac{r-1}{2(1+k)r} + \frac{N-1}{2}\frac{q-1}{2(1+k)q} = \frac{N}{4}.$$
Multiply by $2(k+1)$ and expand,
$$1-\frac1r + \frac N2-\frac12-\frac N{2q}+\frac1{2q}= \frac{Nk}2+\frac N2.$$
Compare to the first,
$$\frac{1}{r} + \frac{N}{2q} -\frac{1}{2q} = \frac{1}{2}- \frac{kN}{2}.$$


text:
Q: Won't read full file c++ I am trying to populate a linked list with creatures from a file. However, when I do it reads the first one but no other creatures. I cannot pass an int to get the number of creatures because it is not static.
I have the following code
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

void clearBuffer() {
    cin.clear();
    cin.ignore(100, '\n');
}

void enterMagicalCreatureFromFile() {
    string filepath = "test.txt";
    ifstream creatureFile;
    creatureFile.open(filepath);
    if (!creatureFile) {
        cerr << "Unable to open file " << filepath << endl;
        return;
    }
    string name, description;
    float cost;
    char danger;
    int numCreated = 0;
    while (getline(creatureFile, name) && getline(creatureFile, description) && creatureFile >> danger && creatureFile >> cost) {
        cout << "name: " << name << " desc: " << description << " danger: " << danger << " cost: " << cost << endl;
        numCreated++;
    }
    cout << numCreated << " creatures from " << filepath << " have been added to the zoo" << endl;
}

int main() {
    enterMagicalCreatureFromFile();
}

The file test.txt looks like
Beholder
Giant center eye and twelve eye stalks above it.  It is a flying eyeball.  Mouth full of razor sharp teeth.  Eye stalks shoot various beams of magical death-dealing energy.
1
750.85
Banshee
The English Banshee is a fairy woman who wails when death is approaching.They do not cause death, only mourn it.  Banshees are almost always female, and are usually seen with long, dark, black hair and pale chees.  Their eyes also are usually red from crying.
0
15.5
Troll
Ugly and big.  Sometimes smell bad.
1
85648.34
Mike Wazowski
One-eyed, funny green monster.  A scare assistant to James P. Sullivan at Monsters, Inc.  Mike doesn't want any interruptions in his life.
0
455.32
Unicorn
The unicorn is a legendary creature that has been described since antiquity as a beast with a single large, pointed, spiraling horn projecting from its forehead.
0
24.32
Sasquatch
The sasquatch is also called Big Food.  Bigfoot is a cryptid in American folklore, supposedly a simian-like creature that inhabits forests, especially those of the Pacific Northwest. Bigfoot is usually described as a large, hairy, bipedal humanoid.
1
39475.93

As I said the first creature "Beholder" loads and get added to the list perfectly, so I don't think my logic is in the list or the creature file.
I am stuck, any pointers?

A: After reading the double cost, there's a newline waiting in the  creatureFile stream.
We need to advance past that with ignore() before reading the next creature:
while (std::getline(creatureFile, name)
       && std::getline(creatureFile, description)
       && creatureFile >> danger
       && creatureFile >> cost)
{
    std::cout << "name: " << name
              << " desc: " << description
              << " danger: " << danger
              << " cost: " << cost
              << std::endl;
    ++numCreated;
    creatureFile.ignore(100, '\n');
}


text:
Q: Number of paths with 1,2,... crosses over a point $m$ between 0 and $x$ in a random walk of $n$ steps Suppose we have a random walk starting from origin and ending at $x$ with $n$ steps, where the set of points is integers on the number line and the steps allowed are 'right' and 'left'. We know that the total paths satisfying the above statement is
$$W(x,n)=\binom{n}{\frac{n+x}{2}}$$
I want to find the number of paths with 1 cross, 2 crosses, and so on over $m$ which is a point located between $0$ and $x$. I figured out
$$W(m−1,t)W(2,2)W(x−(m+1),n−t−2)$$
is the total number of paths with 1 cross but I can't generalize it to more crosses.


text:
Q: Gradient along MKPolyLineView ( MKPolylineRenderer ) I'd like to apply a gradient on a polyline view depending on some conditions like speed.
I was able to subclass MKPolyLineRenderer to draw with custom stroke and fill, but only with the same color along the path.
I saw other similar questions like : Draw segments from a circle or donut  or On OSX, how do I gradient fill a path stroke? , but it is not exactly what I'd want.
If I understand correctly, a path like below couldn't be filled with these methods. At least not treated as a whole.

A very similar question is Gradient Polyline with MapKit ios. But it adds an overlay for each segment between the points, which I think isn't too efficient.
Is this the only possible way ? ( I'd need to draw hundreds or maybe thousands of these segments ... )  How can this be achieved easily ?
Thanks

A: So the original answer is here https://stackoverflow.com/a/20159374/2606068
you can find the demo here https://github.com/wdanxna/GradientPolyline
and some improvement tips provided by @Templar is:

*

*prepare the path directly in the init.

*check also for CGRectContains, not only for intersection.

thanks man! :p


text:
Q: pip install from custom whl file in Dockerfile I have a Dockerfile which is trying to install a whl file which is located in my project using pip. I want to force pip to include my whl file in its searches, but it doesn't:
No distributions matching the version for mylibname==mylibversion

I tried using build_ext with options -L:
pip install --global-option=build_ext --global-option="-L/directory/containing/whl/file/"

-I:
pip install --global-option=build_ext --global-option="-I/directory/containing/whl/file/"

and -b:
pip install --global-option=build_ext --global-option="-b/directory/containing/whl/file/"

But none of them worked.
EDIT 1:
This is my Dockerfile:
FROM python:2.7.9
MAINTAINER Zeinab Abbasimazar
ADD myprojectdir .
RUN ls -la ${HOME}/myprojectdir/dependency
RUN pip --version
RUN pip install --global-option=build_ext --global-option="-L${HOME}/myprojectdir/dependency" mypackagename-mypackageversion
WORKDIR .
CMD python --version

This is the output of docker build -t myimagename .:
Sending build context to Docker daemon 4.096 kB
Step 1 : FROM python:2.7.9
 ---> 646fa5bbf55d
Step 2 : MAINTAINER Zeinab Abbasimazar
 ---> d08f7cb9e985
Step 2 : ADD myprojectdir .
 ---> 0e190b21a30b
Step 3 : RUN ls -la ${HOME}/myprojectdir/dependency
total 1740
drwxr-sr-x 2 root staff    4096 Sep  6 11:58 .
drwxr-sr-x 3 root staff    4096 Sep  6 11:58 ..
-rw-r--r-- 1 root staff  454253 Sep  6 11:58 mypackagename-mypackageversion-py2-none-any.whl
 ---> d069986bd3b6
Step 4 : RUN pip --version
pip 1.5.6 from /usr/lib/python2.7/dist-packages (python 2.7)
 ---> ddeccc833ea2
Step 5 : RUN pip install --global-option=build_ext --global-option="-L${HOME}/myprojectdir/dependency" mypackagename-mypackageversion
Downloading/unpacking mypackagename-mypackageversion
  Could not find a version that satisfies the requirement mypackagename-mypackageversion
Cleaning up...
No distributions matching the version for mypackagename-mypackageversion
Storing debug log for failure in /root/.pip/pip.log
The command '/bin/sh -c pip install --global-option=build_ext --global-option="-L${HOME}/myprojectdir/dependency" mypackagename-mypackageversion' returned a non-zero code: 1

EDIT2:
The pip install /path/to/the/whl/file.whl completely works; but it's not what I want.

A: Install all wheels without listing them explicitly:
pip install /path/to/*.whl


text:
Q: Is there a possibilty to use the @> operator from PostgreSQL in JPA? In PostgreSQL, we have the @> operator.
It checks if the JSON value exists in a jsonb field.
Is there a possibility to do this in JPQL or is there no other way than a native query?


text:
Q: Error while implementing MOXy's I was getting a cyclic error in my DTO classes, so decided to implement MOXy's to get rid of it. I followed the following steps for implementing MOXy's:

*

*Downloaded EclipseLink from [http://www.eclipse.org/eclipselink/downloads/nightly.php]

*Copied all the JARs from /eclipselink/jlib folder to my /WEB-INF/lib

*For Specifying EclipseLink MOXy as the JAXB provider created a jaxb.properties file in the folder where all classes are present with following entry in it -
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
I am using @XmlElement and @XmlInverseReference annotations in my dto classes but I am getting following error while I am running my application:
javax.ws.rs.WebApplicationException: com.sun.xml.bind.v2.runtime.IllegalAnnotationsException: 1 counts of IllegalAnnotationExceptions, Class has two properties of the same name "application"
this problem is related to the following location:
    at public thbs.provisioning.dto.ApplicationDTO thbs.provisioning.dto.EnvironmentDTO.getApplication()
    at thbs.provisioning.dto.EnvironmentDTO
    at public java.util.Set thbs.provisioning.dto.ApplicationDTO.getEnvironment()
    at thbs.provisioning.dto.ApplicationDTO
this problem is related to the following location:
    at private thbs.provisioning.dto.ApplicationDTO thbs.provisioning.dto.EnvironmentDTO.application
    at thbs.provisioning.dto.EnvironmentDTO
    at public java.util.Set thbs.provisioning.dto.ApplicationDTO.getEnvironment()
    at thbs.provisioning.dto.ApplicationDTO

A: For some reason, your jaxb.properties file was not picked up -- the "com.sun.xml.bind.v2.runtime" in the error message indicates that Sun JAXB is running, not MOXy.
Make sure that jaxb.properties is on the classpath in the same package as your model classes.  If you included jaxb.properties in your source directory, ensure that it was copied to the same directory where your .class files end up.  You can read about setting up your jaxb.properties here: http://www.eclipse.org/eclipselink/documentation/2.5/moxy/runtime.htm#sthref8
Hope this helps,
Rick

A: To address your followup question where you are getting the wrong output.  The mapping for the environmentproperty on your ApplicationDTO is wrong.  You could do one of the following:
Option #1 - @XmlElementRef
If you use the @XmlElementRef annotation the element name for this property will be based on the @XmlRootElement annotation on the target class.
@OneToMany(mappedBy = "application", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@XmlElementRef
public Set<EnvironmentDTO> getEnvironment() {
    return environment;
}

Option #2 - @XmlElement
Alternatively you can use the @XmlElement annotation to specify the element that should be used for the property.
@OneToMany(mappedBy = "application", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@XmlElement(name="environmentDTO")
public Set<EnvironmentDTO> getEnvironment() {
    return environment;
}

EDIT:
@GET
@Path("/get")
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
public List<ApplicationDTO> getAllApplications(){
    List<ApplicationDTO> allApplication = applicationService.getAllApplication();
    return allApplication;
}

From here flow comes to the following class:
@Override
public List<ApplicationDTO> getAllApplication() {

    List<ApplicationDTO> AppList = genericDAOTxService.findAll(ApplicationDTO.class);
    return AppList;
}

Than to the following class:
@Override
@Transactional(rollbackFor = java.lang.Exception.class, noRollbackFor = java.io.FileNotFoundException.class, propagation = Propagation.REQUIRES_NEW)
public <T> List<T> findAll(Class<T> type) {
    List<T> list = genericDAOImpl.findAll(type);
    return list;
}

And, then from database values are getting populated.
Previously i.e. before using MOXy's I used to get following in ApplicationDTO object:
[ApplicationDTO [applicationId=1, applicationName=name, applicationDescription=desc, owner=5, createTime=2013-05-06 15:29:15.0, environment=[EnvironmentDTO [environmentId=1, environmentName=envname]]], ApplicationDTO [applicationId=2, applicationName=name, applicationDescription=desc, owner=5, createTime=2013-05-28 19:07:10.0, environment=[EnvironmentDTO [environmentId=2, environmentName=envname]]]]

But, now I am getting following in the ApplicationDTO object:
[ApplicationDTO [applicationId=1, applicationName=name, applicationDescription=desc, owner=5, createTime=2013-05-06 15:29:15.0], ApplicationDTO [applicationId=2, applicationName=name, applicationDescription=desc, owner=5, createTime=2013-05-28 19:07:10.0]]

This is the actual flow of my application and object is getting created automatically using JAXB and Jersy libraries. I am not having any other seperate program for marshalling and unmarshalling the object.


text:
Q: Cannot erase SD card with Disk Utility (El Capitan) I have this SD card that I am trying to use to backup photos on a Windows computer.
After using the SD card on the Windows computer, and copying the photos back on a safe drive, I cannot erase the SD card:

And yep, in the Info window for the card, the device is listed as "read only":

I checked the Lock Tab and it's not on Lock position... What gives?

A: I had the same exact problem.  Format your card using this application: https://www.sdcard.org/downloads/formatter_4/index.html
Worked perfect for me.
Cheers.

A: A better and simpler solution would be using the command-line.
Execute the following command to identify the mount name of SD card following the pattern /dev/diskX, e.g., /dev/disk2
diskutil list

Say the disk name is /dev/disk2. Now format the card to FAT32 by running the following command:
sudo diskutil eraseDisk FAT32 MYSD MBRFormat /dev/disk2

A: I had to run
sudo diskutil eraseVolume exFAT MYSD MBRFormat /dev/disk2s1

to successfully format a volume on my 64G SD card.

A: For a reason I haven't yet understood, the card was erased just fine once I used an older version of Disk Utility.
When I inserted the SD Card in a computer running Yosemite, two drives mounted, one called "NO NAME" which I could click on, and one called "UNTITLED" which seemed to be a ghost file or an alias:

When using Version 13 (606) of Disk Utility (so, the version included with Yosemite), the SD Card was erased without any problem.
The ghost "UNTITLED" drive disappeared.
I am therefore led to believe that the new Disk Utility in El Capitan doesn't work the same way as the previous one, or that it failed at erasing the card in this particular situation.

A: I faced the same issue. I tried with 8GB, 16GB and 32GB cards and none worked. The trick was in the SD card reader. On the left side there was a switch for physical write protection. Toggling the switch and reinserting the card worked!!

A: I tried a different SD card reader, and that fixed the problem.


text:
Q: Laravel api Login giving wrong feedback message In my Project I am using Laravel-8, laravel-passport and spatie-permission for restful api. Already, I have this code in the Controller.
I have this controller
public function adminLogin(Request $request)
{
    if (auth('web')->attempt($request->only('email', 'password'))) {
        $user = Auth::guard('web')->user();
      //  dd($user);
        if (!$user->hasRole('Super Admin')) {
            return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
        }

        $success['token'] =  $user->createToken('MyApp')-> accessToken;
        $success['name'] =  $user->name;

        return $this->sendResponse($success, 'User login successfully.');
    }
    else{
        return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
    }
}:

'Super Admin' is part of the current user's role, yet I am getting this feedback:

{"success":false,"message":"Unauthorised.","data":{"error":"Unauthorised"}}

It has to do with this line:
if (!$user->hasRole('Super Admin')) {
  return $this->sendError('Unauthorised.', ['error'=>'Unauthorised']);
}

CREATE TABLE `roles` (
  `id` bigint(20) UNSIGNED NOT NULL,
  `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `guard_name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `created_at` timestamp NULL DEFAULT NULL,
  `updated_at` timestamp NULL DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `roles` (`id`, `name`, `guard_name`, `created_at`, `updated_at`)
VALUES
(1, 'Super Admin', 'web', '2019-11-13 12:11:38', NULL),
(2, 'Employee', 'web', '2019-11-13 12:11:38', NULL),
(3, 'HOD', 'web', '2019-11-13 12:11:38', NULL);

CREATE TABLE `model_has_roles` (
  `role_id` bigint(20) UNSIGNED NOT NULL,
  `model_type` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
  `model_id` bigint(20) UNSIGNED NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;

INSERT INTO `model_has_roles` (`role_id`, `model_type`, `model_id`) VALUES
(1, 'App\\Models\\User', 1),
(2, 'App\\Models\\User', 1);

What could be the problem and how do I get it resolved?
Thanks


text:
Q: Dart intl library resolving with incorrect path I've only just started a Dart application (using AngularDart). When I import the AngularDart package I see a console error in Dartium.
import 'package:angular/angular.dart';

If I comment out the AngularDart import then I don't see the error.
It appears as though the intl library is being resolved from my web directory as its root. (e.g. web/packages/intl/src/temporary_debugging.dart instead of packages/intl/src/temporary_debugging.dart).
I also see this same error with an untouched version of the AngularDart tutorial so I'm wondering if this is a bug. I've played around with this tutorial before and I haven't seen this error until now.

A: In describing this error I found that in using the built in server in WebStrom 8 (EAP) I see this error, but when using WebStorm 7 the error doesn't occur. I'm going to file a bug with IntelliJ.


text:
Q: WPF binding TextBox with ResourceDictionary I have a TextBox and I made a ResourceDictionary for it for designing purpose. How can I bind it's Text property to its ViewModel in MVVM architecture? The current code is not working.
TextboxTheme.xaml:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Style TargetType="{x:Type TextBox}" x:Key="ModernTextbox">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type TextBox}">
                    <Border CornerRadius="10" Background="#353340" Width="200" Height="30">
                        <Grid>
                            <Rectangle StrokeThickness="1"/>
                            <TextBox Margin="1" BorderThickness="0" Background="Transparent" VerticalContentAlignment="Center" Padding="5" Foreground="#CFCFCF" x:Name="SearchBox"/>
                            <TextBlock IsHitTestVisible="False" Text="{TemplateBinding ToolTip}" VerticalAlignment="Center" HorizontalAlignment="Left" Margin="10,0,0,0" FontSize="11" Foreground="DarkGray" Grid.Column="1">
                                <TextBlock.Style>
                                    <Style TargetType="{x:Type TextBlock}">
                                        <Style.Triggers>
                                            <DataTrigger Binding="{Binding Text, ElementName=SearchBox}" Value="">
                                                <Setter Property="Visibility" Value="Visible"/>
                                            </DataTrigger>
                                        </Style.Triggers>
                                        <Setter Property="Visibility" Value="Hidden"/>
                                    </Style>
                                </TextBlock.Style>
                            </TextBlock>
                        </Grid>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ResourceDictionary>

An example for TextBox in the corresponding View (SettingsView.xaml):
<TextBox Text="{Binding DailyCalories}" ToolTip="Napi kalóriamennyiség" Width="250" Height="30" VerticalContentAlignment="Center" HorizontalAlignment="Center" Margin="2" Style="{StaticResource ModernTextbox}"/>

The property in the viewmodel:
private String _dailyCalories;
public String DailyCalories
{
    get { return _dailyCalories; }
    set
    {
        if (_dailyCalories != value)
        {
            _dailyCalories = value;
            OnPropertyChanged();
        }
    }
}

App.xaml:
<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="Theme/TextboxTheme.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

A: You missed to bind the Text property inside of your template.
It is as simple as
<TextBox
  x:Name="SearchBox"
  Margin="1"
  Padding="5"
  VerticalContentAlignment="Center"
  Background="Transparent"
  BorderThickness="0"
  Foreground="#CFCFCF"
  Text="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=Text, UpdateSourceTrigger=PropertyChanged}" />


text:
Q: How can I turn off creating a sub folder for a new added project in Visual Studio? Hi this question is already asked but its 11 years ago so this problem its solved or anyone have any idea
When I try to add a new project in a solutin folder by browsing a folder, let's say
..\MyFolder
and give a new to my new Project: MyProject
The result seems to be:
..\MyFolder\MyProject\MyProject.cspoj
but I want to achieve
..\MyFolder\MyProject.cspoj
And Icannot see any option or check-box on new project addin dialog box.
How can I turn of the feature to insert the new project in a auto-created subfolder?
Thanks!

A: You can follow my steps to create a new project and then add this new project to the solution. For example, I want to add the project "New" to the solution "Old".
As shown in the figure below:

If you have suggestions for improving Visual Studio, please visit https://developercommunity.visualstudio.com/home).


text:
Q: Load images from database CodeIgniter I would like to create a photo gallery, taking images from the database.
I'm using codeigniter.
Database
this is a static page located in views/pages/gallery.php
does anyone have any ideas?

A: What you want is to query the database table, get the relevant fields, and return that to a view. In MVC, it looks something like this:
Model:
class Portfolio_model extends CI_Model {

    public function get_items() {
        $this->db->select('name, description, image');
        $this->db->order_by('date', 'DESC');
        $q = $this->db->get('tablename'); // your tablename here
        if ($q->num_rows() > 0) {
            return $q->result();
        } else {
            return null;
        }
    }

}

Controller:
class Portfolio extends CI_Controller {
    public function index() {
        $this->load->helper('html');
        $this->load->model('portfolio_model');
        $data['items'] = $this->portfolio_model->get_items();
        $this->load->view('portfolio', $data);
    }
}

View:
if (!is_null($items)) {
    foreach ($items as $item) {
        echo $item->name . '
';
        echo $item->description . '
';
        echo 'Image src: ' . base_url() . $item->image . '
';  // might need slash after base_url, don't remember
        echo img($item->image);
    }
} else {
    echo 'No items found!';
}

A: This worked for me :
Controller -
public function index(){
    $this->load->model('galleryModel');
    $data1['items'] = $this->galleryModel->get_items();
    $this->load->view('gallery', $data1);
}

Model -
public function get_items() {
    $this->db->select('*');
    $this->db->from('gallery');
    $query = $this->db->get();

    if($query->num_rows() != 0){
        return $query->result_array();
    }else{
        return false;
    }
}

View -
<?php
    foreach ($items as $item) {
        $image_id = $item['image_id'];
        $name = $item['name'];
        $category = $item['category'];
        $image = $item['image'];
        ?>

    <div class="tile scale-anm <?php echo $category; ?>">
        <img src="<?php echo $image; ?>" class="film-img-gallery" alt="" />

<?php } ?>


text:
Q: Mapping an integer to an array I recently started with C++; I'm an hobby programmer, and I know a bit of Python.
I programmed a little snake. I wanted to insert another snake guided by the computer.
I decided to put the possible direction that the snake can take in an enum:
enum directions{UP, DOWN, RIGHT, LEFT, IN, OUT, FW, RW,NONE};

void fill_map(std::map<directions,V4> &map_vec);

void fill_map(std::map<int, directions*> &map_dir);

void fill_map(std::map<directions,directions> &map);

and map the enum for the needed function:
void fill_map(std::map<directions,V4> &map_vec){
    map_vec[UP] = V4(0,1,0,0);
    map_vec[DOWN] = V4(0,-1,0,0);
    //others

  }

 void fill_map(std::map<directions, directions> &map){
    map[UP]= DOWN;
    map[DOWN]= UP;
    //others
  }

void fill_map_axis(std::map<int, directions*> &map_dir){
    directions array_x[2] = {RIGHT,LEFT};
    map_dir[0] = array_x;

    directions array_y[2] = {UP,DOWN};//store the array
    map_dir[1] = array_y;

    directions array_z[2] = {FW,RW};//store the array
    map_dir[2] = array_z;

    directions array_w[2] = {IN,OUT};//store the array
    map_dir[3] = array_w;

}

The fill_map functions are called in the snake constructor.
Basically what I wanted to do in the fill_map_axis is to map an integer corresponding to the index of the coordinate (0 coord x, 1 coord y etc) and map the two directions that move along those axis.
So I stored an array of two directions.
Now I call the function:
directions SnakeCPU::find_dir(V4 point){
    //point is the target point
    directions dir;
    int index = get_coord_index(point); //get the index where to move
    double diff = head_pos[index]-point[index]; //find the difference between the head and the target point

    directions* axis = dir_coords[index]; //call the map containing the directions stored in an array.

    if(diff<0.){

        dir = *axis; //use the first
    }
    else if(diff>0.) {
        axis++;
        dir = *axis; //use the second
    }
    else{
        dir = NONE;
    }

    return dir;
}

Although the map are initialized in the Snake constructor, it seems that the returned value from the pointer axis is a random memory block.
So my question: do you see a mistake in the code? did I used the pointer axis with sense?
I'm really not expert with pointer; in Python the map is instantiated with a dictionary like this:
dir_coords = {0:[LEFT,RIGHT], ...}

so I just need to call it:
axis = dir_coords[index]
dir = axis[0]
#or
dir = axis[1]

edit:
Snake constructor:
Snake::Snake()
{
    fill_map(dir_vectors);
    fill_map(dir_coords);
    fill_map(opposite_dir);
    head_pos = V4(0.,0.,0.,0.);
    //other stuff...
}

A: Just a shot in the blue, here is how I would design this.
#include <map>

enum EDirection { NONE = 0, UP, DOWN, RIGHT, LEFT, IN, OUT, FW, RW };

typedef std::map<EDirection, V4>           DirectionMap;
typedef std::pair<EDirection, EDirection> DirectionPair;
typedef std::map<int, DirectionPair>            PairMap;

extern const DirectionMap map_vec {
  { UP,   (0, 1, 0, 0) },
  { DOWN, (0,-1, 0, 0) },
  // ...
};   // using C++11 initialization lists for convenience

extern const PairMap map_dir {
  { 0, { RIGHT, LEFT } },
  { 1, { UP, DOWN }    },
  // ...
};

Here I decided to make map_vec and map_dir global constants, because I gathered that that's essentially what they are. To initialize those, I rely on the new C++11 initialization syntax. If that's not an option, we can also fill the map in the traditional way:
PairMap map_dir;
map_dir.insert(std::make_pair(0, DirectionPair(RIGHT, LEFT)));
map_dir.insert(std::make_pair(1, DirectionPair(UP, DOWN)));
// ...

DirectionMap map_vec;
map_vec.insert(std::make_pair(UP,   V4(0, 1, 0, 0)));
map_vec.insert(std::make_pair(DOWN, V4(0,-1, 0, 0)));
// ...

(Yes, you can also write map_dir[0] = DirectionPair(RIGHT, LEFT)'. I don't like the square brackets, though, they feel too violent for my taste.)

A: As Kerrek said, you filled map_dir with automatic scoped variables, which means they are automatically destroyed when the function ended.
void fill_map_axis(std::map<int, directions*> &map_dir){
    //This variable will be destroyed when the function ends
    directions array_x[2] = {RIGHT,LEFT};
    map_dir[0] = array_x; //should have a warning at least, probably not compile

What you probably want is actual directions in the map
void fill_map_axis(std::map<int, std::pair<directions, directions> > &map_dir){
    //This variable will be destroyed when the function ends
    std::pair<directions, directions> array_x = {RIGHT,LEFT};
    map_dir[0] = array_x; //makes a copy


text:
Q: Vibe.d REST Interface serve image Sending a bunch of binary back to the user like an image:
interface API
{
  @path("/data/image")
  @contentType("image/png")
  ubyte[] getImagePreview(string foo);
}

The function is returning a Json array with the values of the ubyte[]
Here are the list of attributes I can use:
adjustMethodStyle
bodyParam
contentType
extractHTTPMethodAndName
headerParam
method
noRoute
path
queryParam
rootPathFromName

Source: Vibe.d site
The only attribute that can do the job is contentType and it's said there that it only works with ubyte[] functions, and that's what I used.
What am I missing?

A: You can try hunt framework so easy use:
    @Action
    Response image(string imageName)
    {
        return new FileResponse("/data/image/" ~ imageName);
    }

More read wiki:
https://github.com/huntlabs/hunt-framework/wiki/FileResponse


text:
Q: grep show all lines, not just matches, set exit status I'm piping some output of a command to egrep, which I'm using to make sure a particular failure string doesn't appear in.
The command itself, unfortunately, won't return a proper non-zero exit status on failure, that's why I'm doing this.
command | egrep -i -v "badpattern"

This works as far as giving me the exit code I want (1 if badpattern appears in the output, 0 otherwise), BUT, it'll only output lines that don't match the pattern (as the -v switch was designed to do). For my needs, those lines are the most interesting lines.
Is there a way to have grep just blindly pass through all lines it gets as input, and just give me the exit code as appropriate?
If not, I was thinking I could just use perl -ne "print; exit 1 if /badpattern/". I use -n rather than -p because -p won't print the offending line (since it prints after running the one-liner). So, I use -n and call print myself, which at least gives me the first offending line, but then output (and execution) stops there, so I'd have to do something like
perl -e '$code = 0; while (<>) { print; $code = 1 if /badpattern/; } exit $code'
which does the whole deal, but is a bit much, is there a simple command line switch for grep that will just do what I'm looking for?

A: Actually, your perl idea is not bad.  Try:
perl -pe 'END { exit $status } $status=1 if /badpattern/;'

I bet this is at least as fast as the other options being suggested.

A: $ tee /dev/tty < ~/.bashrc | grep -q spam && echo spam || echo no spam

A: How about doing a redirect to /dev/null, hence removing all lines, but you still get the exit code?
$ grep spam .bashrc > /dev/null

$ echo $?
1

$ grep alias .bashrc > /dev/null

$ echo $?
0

Or you can simply use the -q switch
   -q, --quiet, --silent
          Quiet;   do   not  write  anything  to  standard  output.   Exit
          immediately with zero status if any match is found, even  if  an
          error  was  detected.   Also see the -s or --no-messages option.
          (-q is specified by POSIX.)


text:
Q: how to get the selected item from list-group in angular 2 I'm using bootstrap to display list of items in angular 2.

Select a Program

x

                <button type="button" class="list-group-item list-group-
        item-action" active>Pictures</button>
                <button type="button" class="list-group-item list-group-
        item-action">Documents</button>
                <button type="button" class="list-group-item list-group-
        item-action">Music</button>
                <button type="button" class="list-group-item list-group-
        item-action">Videos</button>

Now when user select any one of the item from above list, I want that selected item value.
This is the code in my component class.
      onClickedItem() {
         var items = document.getElementsByClassName("list-group-item
     active");
    if(items != undefined && items.length === 1) {
         console.log("selected item is:", items[0]);
    }

    }

I'm getting undefined as selected value.
Please suggest the solution.

A: Youe can use the Template Reference from Angular:
Check this out: documantion

            <button type="button" class="list-group-item list-group-
    item-action" active #pic>Pictures</button>

  onClickedItem(ref: any) {
     let items = ref.value;

     if(items != undefined && items.length === 1) {
          console.log("selected item is:", items[0]);
     }
  }


text:
Q: How to disable button over class of parent element? I have the following HTML:

    add file...
    <input type="file" name="file" disabled>

I want to disable the input element (button) using the label's class name (without the button's ID).
$('label.fileinput-button') ... button ... disable.

How can I do this?

A: $('label.fileinput-button input').prop('disabled', true);

Note: .prop() is available since version 1.6

A: Use the attr method to assign the disabled property to your named input.
$('label.fileinput-button input[name=file]').attr("disabled", "disabled");


text:
Q: My background image isn't fading in (but the nav bar is) My background image is not fading in but my navbar is. (I want my background image to fade in and the navbar to not)
Here is the HTML

body {
  margin: 0;
  padding: 0;
  background-color: #272727;
}

body.home {
  background-image: URL("Homebc.png");
  background-size: cover;
  -webkit-animation: fadein 2s;
}

@-webkit-keyframes fadein {
  from { opacity: 0; }
  to   { opacity: 1; }
}

HOME

ABOUT

OUR APPROACH

CONTACT

Thanks in advance!

A: You can not animate body background and your code has some issue too. Try below code-

body {
  margin: 0;
  padding: 0;
  background-color: #272727;
}

.home {
  background-image: url("https://cdn.pixabay.com/photo/2013/04/06/11/50/image-editing-101040_960_720.jpg");
  background-size: cover;
  height: 100vh;
  width: 100vh;
  -webkit-animation: fadein 2s;
}

@-webkit-keyframes fadein {
  from { opacity: 0; }
  to   { opacity: 1; }
}

HOME

ABOUT

OUR APPROACH

CONTACT

A: First, You should replace the line:

With

Then, the body selector on your CSS file don't have a corresponding end }.
Besides that, body background cannot be animated.

body {
  margin: 0;
  padding: 0;
  background-color: #272727;
}
body.home {
  background-image: url("http://via.placeholder.com/350x150");
  background-size: cover;
  -webkit-animation: fadein 2s;
}

@-webkit-keyframes fadein {
  from { opacity: 0; }
  to   { opacity: 1; }
}

HOME

ABOUT

OUR APPROACH

CONTACT


text:
Q: PhP get content of all files in directory I have many files in a directory that look similar to:
personalchat.spud.3353.1789
personalchat.guest.3355.1789
personalchat.ken.3355.1789

each file essentially has a few lines of html inside, and wanting to open all files, pull the content to the screen. I can do it by hardcoding a single filename but not all at once or by using a * for filename
Code:
$names=file('/var/www/html/web/www/chat.support/status/personalchat*');

foreach($names as $name)
{
   echo $name.'
';
}

##UPATE 2
I tried changing to an array but it only displays the name of the files not the content of each:
I am able to list the files as an array:
personalchat.mick.3350.1733
personalchat.guest.3352.1739
personalchat.test.3351.1736

But not able to display the name of each file but not the content:
$mydir = '/var/www/html/web/www/chat.support/status/';
$myfiles = array_diff(scandir($mydir), array('.', '..'));

foreach($myfiles as $name)
{
   echo $name.'
';
}

Thanks

A: file() function reads 1 file. So you need an array of files to read with file().
May be you can try to create such array using scandir() first, and then read the file 1 by one.


text:
Q: How to get htmlFor of a label I'm trying to get the for attribute of a label element using jQuery. So far all of my attempts have yielded incorrect responses.
        console.log($('label'.htmlFor)); //e.fn.init.....
        console.log($('label').htmlFor)); //undefined
        console.log($('label.htmlFor')); //[prevObject.....]..
        console.log($('label[for]'));
        console.log($('label')); //same as directly above
        console.log($('label[for].htmlFor')); //[prevObject.....]..
        console.log($('label[for]').htmlFor)); //undefined

I know the htmlFor is defined as I can see it in chromes web inspector. What am I doing wrong?

A: Your examples don't work because you either select the element only (and don't retrieve the attribute value) or you try and get the htmlFor attribute which not a valid property of a jQuery object.
To do what you require you need to select the label then use attr() to get the for attribute, like this:
var forAttr = $('label[for]').attr('for');

Alternatively, if there are multiple label elements in your form you can loop through them like this:
$('label[for]').each(function() {
   var forAttr = $(this).attr('for');
   // work with for here...
});


text:
Q: How to go to next line after every row in a 2D array? So I need to come up with something like this: It's a layout of seats on an airplane.

1 A B C D
2 A B C D
3 A B C D
4 A B C D
5 A B C D
6 A B C D
7 A B C D

But instead my code prints this:

ABCD
ABCABCD
ABCABCD
ABCABCD
ABC

This is my code, any help would be really appreciated. I just started working with arrays
#include <iostream>

using namespace std;

int main ()
{
     char airplane[7][4] = {{'A', 'B', 'C', 'D'},
                             {'A', 'B', 'C', 'D'},
                             {'A', 'B', 'C', 'D'},
                             {'A', 'B', 'C', 'D'},
                             {'A', 'B', 'C', 'D'},
                             {'A', 'B', 'C', 'D'},
                             {'A', 'B', 'C', 'D'}};

     for (int i=0; i<4; i++)
     {

            for (int j=0; j<7; j++)
            {
                 cout<<airplane[i][j];
                 if (airplane[i][j]=='D')
                 {
                     cout<<endl;
                 }
            }
     }

     system ("PAUSE");
     return 0;
}

A: try this..:-->
#include <iostream>

using namespace std;

int main ()
{
  char airplane[7][4] = {{'A', 'B', 'C', 'D'},
                         {'A', 'B', 'C', 'D'},
                         {'A', 'B', 'C', 'D'},
                         {'A', 'B', 'C', 'D'},
                         {'A', 'B', 'C', 'D'},
                         {'A', 'B', 'C', 'D'},
                         {'A', 'B', 'C', 'D'}};

 for (int i=0; i<7; i++)       //Row
 {
        cout<<i+1;
        for (int j=0; j<4; j++)    //Column
        {
             cout<<airplane[i][j];
             cout<<" ";
        }
     cout<<endl;
 }

 system ("PAUSE");
 return 0;
}

A: Here the code :
 #include <iostream>

    using namespace std;

    int main ()
    {
         char airplane[7][4] = {{'A', 'B', 'C', 'D'},
                                 {'A', 'B', 'C', 'D'},
                                 {'A', 'B', 'C', 'D'},
                                 {'A', 'B', 'C', 'D'},
                                 {'A', 'B', 'C', 'D'},
                                 {'A', 'B', 'C', 'D'},
                                 {'A', 'B', 'C', 'D'}};

         for (int i=0; i<7; i++)
         {
             cout << i+1;
                for (int j=0; j<4; j++)
                {
                     cout<<airplane[i][j];
                     if (airplane[i][j]=='D')
                     {
                         cout<<endl;
                     }
                }
         }

         system ("PAUSE");
         return 0;
    }

A: Change the for loop in this fashion
for (int i=0; i<7; i++)
     {
            cout<<i+1;
            for (int j=0; j<4; j++)
            {
                cout<<' ';
                 cout<<airplane[i][j];

            }
            cout<<endl;
     }

A: Try running your outer loop for 7 times and inner loop for 4 times. Include  cout<

And by the way the code given by Bui Akinori is buggy for if you change the number of seats in each row to five.


text:
Q: convergence of continued nested function Does $$\sin (x + \sin (x + \sin (x + \sin (x + ... ) ) )))  $$ converge to any limit? If so, to what?
Recursive plotting appears at times to come to same/similar profiles.

A: Define the sequence
$$x_{n+1} = x_0 + \sin x_n$$
For any $x_0$, the function $x_0+\sin x$ is $1$-lipschitzian and maps the interval $[x_0 - 1, x_0 + 1]$ into itself. Therefore it has a unique fixed point in that interval, and the sequence $x_n$ converges to it according to this modification of the Banach fixed point theorem.


text:
Q: Facemask Recognition using TFlite in Raspberry Pi 3B+ with Python3 I try to use TFlite for my facemask recognition project. But the problem is it has errors. The problem can Stream. However, if it detects a human face/facemask the error will terminate the system.
Here's the error
Traceback (most recent call last):
  File "/home/pi/Desktop/fm_detection/fm_tflite.py", line 113, in <module>
    (mask, withoutMask) = pred
TypeError: cannot unpack non-iterable numpy.float32 object

Here's my coding
import tensorflow as tf
from tensorflow.keras.applications.mobilenet_v2 import preprocess_input
from tensorflow.keras.preprocessing.image import img_to_array
from tensorflow.keras.models import load_model
from imutils.video import VideoStream
from gpiozero import LED, Buzzer
import numpy as np
import imutils
import time
import cv2
import os
import sys

led = LED(19)
buzzer = Buzzer(26)

def detect_and_predict_mask(frame, faceNet, interpreter):

    (h, w) = frame.shape[:2]
    blob = cv2.dnn.blobFromImage(frame, 1.0, (224, 224),
        (104.0, 177.0, 123.0))

    faceNet.setInput(blob)
    detections = faceNet.forward()
    print(detections.shape)

    faces = []
    locs = []
    preds = []

    for i in range(0, detections.shape[2]):

        confidence = detections[0, 0, i, 2]

        if confidence > 0.5:

            box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
            (startX, startY, endX, endY) = box.astype("int")

            (startX, startY) = (max(0, startX), max(0, startY))
            (endX, endY) = (min(w - 1, endX), min(h - 1, endY))

            face = frame[startY:endY, startX:endX]
            face = cv2.cvtColor(face, cv2.COLOR_BGR2RGB)
            face = cv2.resize(face, (224, 224))
            face = img_to_array(face)
            face = preprocess_input(face)

            faces.append(face)
            locs.append((startX, startY, endX, endY))

    if len(faces) > 0:

        faces = np.array(faces, dtype="float32")
        #preds = maskNet.predict(faces, batch_size=32)
        interpreter.allocate_tensors()
        interpreter.set_tensor(interpreter.get_input_details()[0]["index"], faces)
        interpreter.invoke()
        preds = interpreter.tensor(interpreter.get_output_details()[0]["index"])()[0]

    return (locs, preds)

# load our serialized facemask model from disk
prototxtPath = "/home/pi/Desktop/fm_detection/face_detector/deploy.prototxt"
weightsPath = "/home/pi/Desktop/fm_detection/face_detector/res10_300x300_ssd_iter_140000.caffemodel"
faceNet = cv2.dnn.readNet(prototxtPath, weightsPath)

#maskNet = load_model("facemask_model.model")
interpreter = tf.lite.Interpreter("facemask_model.tflite")

# initialize the video stream
print("[INFO] starting video stream...")
vs = VideoStream(src=1).start()

# loop over the frames
while True:

    frame = vs.read()
    frame = imutils.resize(frame, width=500)

    (locs, preds) = detect_and_predict_mask(frame, faceNet, interpreter)

    for (box, pred) in zip(locs, preds):
        # unpack the bounding box and predictions
        (startX, startY, endX, endY) = box
        (mask, withoutMask) = pred

        label = "Mask" if mask > withoutMask else "No Mask"
        color = (0, 255, 0) if label == "Mask" else (0, 0, 255)
        led.on() if mask > withoutMask else led.off()
        buzzer.beep(0.1, 0.1, 1) if mask > withoutMask else led.off()

        time.sleep(2)
        led.off() if mask > withoutMask else led.off()
        os.system("espeak -s 130 'THANK YOU'") if mask > withoutMask else led.off()
        sys.exit() if sw2Press else buzzer.off()

        cv2.putText(frame, label, (startX, startY - 10),
            cv2.FONT_HERSHEY_SIMPLEX, 0.45, color, 2)
        cv2.rectangle(frame, (startX, startY), (endX, endY), color, 2)

    cv2.imshow("Frame", frame)
    key = cv2.waitKey(1) & 0xFF

    if key == ord("q"):
        break

cv2.destroyAllWindows()
vs.stop()

The program will be stuck at the moment it detects the human face. Hope someone can help me.
Thank You


text:
Q: Does passing data in props duplicate that data? I'm building a dashboard in React, and currently I'm looking at building a small button component that will allow a user to download data from a chart as a CSV file. Something like this:
// Dashboard
render(){
  const data=makeLargeDataset(); // make an array with 1m rows
  return (
    <DownloadCSV data={data} />
  );
}

// Download Button
onClick(){
  if (this.props.data){
    convertAndDownload(this.props.data);
  }
}

Does this duplicate the 1M rows when passing to the button's prop? If I had to pass a prop through several layers, will it keep duplicating? Is there a smarter way to pass props -- or work with large variables and arrays, in general -- so it isn't as wasteful or inefficient?

A: You are not passing the data copy, you are passing the reference.
You could think about paginating your data in some way in order to handle lower sized arrays.

A: Nope, It does not.
Any props passed from a higher order component to a child component always references the same props. It's called Single Source of Truth. You can alter one data point in the HO Component and React as the name tells reacts to only the change and nothing else.
A simple way for holding such big data sets would be to use a store like Redux to keep the data safe but the smarter way would be to create an API or a micro service based on your needs and call that rather than loading a million rows on the browser.


text:
Q: Excel 2010 IF() statement assistance I need assistance converting this to an Excel formula or VBA script.  Let me know if you have questions.  It needs to run on each row starting at row 2 until row 30.  This is an example of what would be on row 2.  Also, if any character other than 1 or 2--to include nothing or null--is in J2, then M2 needs to remain blank as well.
if (J2="1" || J2="2"){
    if (I2="*(AE)*"){
        M2="(AE)"
    }
    else{
        if(I2="*(OT)*"){
            M2="(OT)"
        }
        else{
            if(I2="*(OT SP)*" || I2="*(OTSP)*"){
                M2="(OT SP)"
            }
            else{
                M2="F"
            }
        }
    }
}

A: In VBA, the equivalent to your example is:
If Range("J2").Value = "1" Or Range("J2").Value = "2" Then
    If Range("I2").Value Like "*(AE)*" Then
        Range("M2").Value = "(AE)"
    End If
ElseIf Range("I2").Value Like "*(OT)*" Then
    Range("M2").Value = "(OT)"
ElseIf Range("I2").Value Like "*(OT SP)*" Or Range("I2").Value Like "*(OTSP)*" Then
    Range("M2").Value = "(OT SP)"
Else
    Range("M2").Value = "F"
End If

But to make this loop from rows 2 to 30, we'll add a simple row variable and loop:
theRow = 2

Do
    If Range("J" & theRow).Value = "1" Or Range("J" & theRow).Value = "2" Then
        If Range("I" & theRow).Value Like "*(AE)*" Then
            Range("M" & theRow).Value = "(AE)"
        ElseIf Range("I" & theRow).Value Like "*(OT)*" Then
            Range("M" & theRow).Value = "(OT)"
        ElseIf Range("I" & theRow).Value Like "*(OT SP)*" Or Range("I" & theRow).Value Like "*(OTSP)*" Then
            Range("M" & theRow).Value = "(OT SP)"
        Else
            Range("M" & theRow).Value = "F"
        End If
    End If

    theRow = theRow + 1

Loop Until theRow = 31


text:
Q: Confused about passing argument via custom functional object For now, I'm trying to make a little graphic class from custom class with two fields:
struct Prog {
    Prog(int y, const string& s) :yy{ y }, name{ s }{}
    Prog() :yy{0}, name{"none"} {}
    int yy;
    string name;
};

Then I create my functional object, to convert argument to coordinates value:
class Scale {
public:
    Scale() : cbase{ 40 }, vbase{ 1960 }, scale{ 20 }{};
    int operator()(const int y) {
        return cbase + (y - vbase) * scale;
    }
private:
    int cbase;
    int vbase;
    double scale;
};

And this is my Graphic class:
class Prog_shape :public Shape {
public:
    Prog_shape(const Prog& p) :txt{ {sc(p.yy),240},p.name }, cir{ {sc(p.yy),244},10 } { }
    void draw_lines() const {
        txt.draw();
        cir.draw();
    }
private:
    Graph_lib::Text txt;
    Scale sc;
    Graph_lib::Circle cir;
};

And the function that is filling the Shapes container from vector<Prog>:
void generate_figures() {
    for (auto p : p_vec) {
        sh_vec.push_back(new Prog_shape{ p});
    }
}

And now I'm really confused about my Prog_shape class's txt object, I can't get the value from the Scale func object, while the cir object can. When I take a few moments to debug, I find values passed to the txt constructor are 0. How can it be possible when the values must be the same?


text:
Q: Not able access multiple data sources in Spring boot I am new to Spring & Spring boot and I am trying to access two data sources but am I able to connect to only one data source.
when I try to call a function accessing 2nd data source the call goes to the first data source and I get the below error,

com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table
  'testify.test' doesn't exist

I have followed the below tutorials for multi DB access and my code is similar to the code in Roufid link,

*

*Roufid

*Baeldung
Can someone point out what i am missing or where I am doing a mistake ?
below are the code files,
AConfig.java
@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "aEntityManager",
transactionManagerRef = "aTransactionManager",
basePackages = "test.serv")
public class AConfig {

@Bean
@Primary
@ConfigurationProperties(prefix="spring.datasource.adb")
public DataSource aDataSource() {
    return DataSourceBuilder.create().build();
}

@Primary
@Bean(name="aEntityManager")
public LocalContainerEntityManagerFactoryBean mysqlEntManFactory(EntityManagerFactoryBuilder build) {
    return build.dataSource(aDataSource()).persistenceUnit("aPU").build();
}

@Primary
@Bean(name="aTransactionManager")
public PlatformTransactionManager mysqlTransactionManager(@Qualifier("aEntityManager") EntityManagerFactory enManFact) {
    return new JpaTransactionManager(enManFact);
}
}

BConfig.java
@Configuration
@EnableJpaRepositories(entityManagerFactoryRef = "bEntityManager",
transactionManagerRef = "bTransactionManager",
basePackages = "test.serv")
public class BConfig {

@Bean
@ConfigurationProperties(prefix="spring.datasource.bdb")
public DataSource bDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean(name="bEntityManager")
public LocalContainerEntityManagerFactoryBean mysqlEntManFactory(EntityManagerFactoryBuilder build) {
    return build.dataSource(bDataSource()).persistenceUnit("bPU").build();
}

@Bean(name="bTransactionManager")
public PlatformTransactionManager mysqlTransactionManager(@Qualifier("bEntityManager") EntityManagerFactory enManFact) {
    return new JpaTransactionManager(enManFact);
}
}

persistence.xml
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/persistence     http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
     version="2.0">
<persistence-unit name="aPU"  transaction-type="RESOURCE_LOCAL">
</persistence-unit>
<persistence-unit name="bPU" transaction-type="RESOURCE_LOCAL">
</persistence-unit>
</persistence>

Service.java
public interface Service extends CrudRepository<X, Integer> {
@Query(value = "select y from test where x = :x", nativeQuery = true)
List<Object[]> findByName(@Param("x") String x);
}

A: The problem is you have your Repository classes (Service) in the same package
@EnableJpaRepositories(entityManagerFactoryRef = "bEntityManager",
transactionManagerRef = "bTransactionManager",
basePackages = "test.serv")

basePackages = "test.serv"
Move it into seprate packages. That should work


text:
Q: Can I solve this boundary value problem using sine transform? I am looking to solve the wave equation with the following conditions:
$ \alpha^2 U_{xx}=U_{tt}, \    x>0,t>0 $
$ U(0,t)= e^{-t},\ lim_{x \to \infty} U(x,0)=0 $
$U(x,0)=0, U_{t}(x,0)=0, \ x>0$
I solved using the Laplace transform with respect to $t$ and the result was:
$H(t-\frac{x}{\alpha^2})e^{-t} $ and after that I have tried to solve using the sine transform with respect to $x$ but I get a complicated integral as the solution:
$ \int_{0}^{\infty}( \frac{-cos(wat)} {a^2w(w^2+1)} -\frac{sinwat}{a^3w^2(w^2+1)} + \frac{1}{a^2(w^2+1)})\ sinwx dw $
the result of which is:
$-\dfrac{{\pi}\mathrm{e}^{-x-at}\cdot\left(2at\mathrm{e}^{x+at}+\left(-a-1\right)\mathrm{e}^{2at}+2a\mathrm{e}^{at}-a+1\right)}{4a^3}$
I am interpreting the condition $ lim_{x \to \infty} U(x,0)=0 $ as stating that the function and its derivative vanish as x goes to $\infty$ which allows for the use of the sine transform. Therefore there is no need to take the transform of the boundary condition. Is this reasoning correct? I suspect there is something wrong with taking the sine transform on this problem like I did. Thanks in advance!


text:
Q: Is $ \ln \delta \int_0^1 \frac{f(z)}{z(\ln z)^2} dz \sim \sum_{r=1}^\infty \mu(r) f(\delta^{1/r}) $? Background
I think I can show something interesting:
$$  \ln \delta  \int_0^1 \frac{f(z)}{z(\ln z)^2} dz \sim \sum_{r=1}^\infty \mu(r) f(\delta^{1/r}) $$
where $\delta \to 0$ and $\int_0^1 \frac{f(z)}{z(\ln z)^2} dz$ converges. However, there is something that worries me. Let $\delta \to \delta^{1/k}$:
$$  \frac{1}{k}\ln \delta  \int_0^1 \frac{f(z)}{z(\ln z)^2} dz \sim
 \sum_{r=1}^\infty \mu(r)f(\delta^{1/(kr)})  $$
Summing both sides $k=1$ to $\infty$:
$$  \sum_{k=1}^\infty \frac{1}{k}\ln \delta  \int_0^1 \frac{f(z)}{z(\ln z)^2} dz  \sim f(\delta) $$
Obviously the L.H.S goes to $\infty$ where as the R.H.S is finite. Can someone spot the error (in the contradiction/proof)?
Proof
Consider:
$$ f(u) +f(u^{1/2}) + f(u^{1/3}) + \dots = g(u) $$
Now consider:
$$ I = \int_0^\infty f(e^{-1/x}) dx $$
Writing using asymptotics and using Riemann limit of a sum with $\epsilon \to 0$:
$$ I \sim (f(e^{-1/\epsilon}) + f(e^{-1/ 2 \epsilon}) + f(e^{-1/3 \epsilon}) + \dots )\epsilon$$
Now using $\epsilon = \frac{-1}{\ln \delta} \to 0$. Hence:
$$ -( \ln \delta )I \sim f(\delta) +f(\delta^{1/2}) + f(\delta^{1/3}) + \dots$$
Substituting $g(\delta)$ and $I$:
$$ -( \ln \delta ) \int_0^\infty f(e^{-1/x}) dx \sim g(\delta)$$
Using mobius inversion:
$$ -( \ln \delta ) \int_0^\infty f(e^{-1/x}) dx \sim \sum_{r=1}^\infty \mu(r)f(\delta^{1/r}) $$
Now, let $z=\exp(-1/x)$ and $dx = \frac{dz}{-z (\ln z)^2}$. Hence,
$$  \ln \delta  \int_0^1 \frac{f(z)}{z(\ln z)^2} dz \sim \sum_{r=1}^\infty \mu(r)f(\delta^{1/r}) $$
where $\delta \to 0$ and $\int_0^1 \frac{f(z)}{z(\ln z)^2} dz$ converges.

A: You write
$$
-(\log \delta) I\sim \left(f(\delta)+f(\delta^{1/2})+f(\delta^{1/3})+\ldots\right).
$$
Then
$$
-(\log\delta)\int^{\infty}_{0}f(e^{-1/x})dx\sim g(\delta)
$$
which is right. But then you say: Using Moebius inversion
$$
-(\log\delta)\int^{\infty}_{0}f(e^{-1/x})dx\sim \sum^{\infty}_{r=1}\mu(r)f(\delta^{1/r}).
$$
This is not true since it is again
$$
-(\log\delta)\int^{\infty}_{0}f(e^{-1/x})dx\sim \sum^{\infty}_{r=1}f(\delta^{1/r})
$$
and you perform no inversion. The right formula is
$$
\int^{1}_{0}\frac{f(t)}{t\log^2 t}dt=-\frac{1}{\log \delta}\sum^{\infty}_{r=1}f(\delta^{1/r})+o_{\delta}(1)\textrm{, }\delta\rightarrow 0^{+}
$$
for $\frac{f(t)}{t\log^2 t}$ continuous and bounded in $[0,1]$. Say $f(t)=\sin^2(\pi t)$, $f(t)=(t(t-1))^2$. In general holds the next
Theorem (see here). If $s_n$, $n\geq 1$ is uniformly distributed in $[a,b]$, $a<b$ and $f(x)$ is continuous and bounded in $[a,b]$, then
$$
\lim_{n\rightarrow+\infty}\frac{1}{n}\sum^{n}_{j=1}g\left(s_j\right)=\frac{1}{b-a}\int^{b}_{a}g(t)dt.
$$
And, also
$$
\int^{\infty}_{0}f(e^{-1/t})dt=\int^{b}_{0}f(e^{-1/t})dt+\int^{\infty}_{b}f(e^{-1/t})dt\sim\epsilon\sum^{N}_{k=1}f(e^{-1/k\epsilon})+\int^{\infty}_{b}f(e^{-1/t})dt,
$$
where $\epsilon=b/N$


text:
Q: iPython throwing an error when launched: "ipythonrc not found" I'm getting a strange error when I launch iPython. I'm running Snow Leopard
WARNING: Configuration file ipythonrc not found. Ignoring request.
------------------------------------------------------------
Traceback (most recent call last):
  File "/Library/Python/2.6/site-packages/IPython/ConfigLoader.py", line 66, in load
    fname = filefind(fname,incpath)
  File "/Library/Python/2.6/site-packages/IPython/genutils.py", line 555, in filefind
    ' not found in current or supplied directories:' + `alt_dirs`
IOError: File'ipythonrc' not found in current or supplied directories:u'/Users/admin_mcadminson/.ipython'

WARNING: Problems loading configuration file 'ipythonrc'
Starting with default -bare bones- configuration.

This is the error message that follows:
ImportError                               Traceback (most recent call last)

/Library/Python/2.6/site-packages/IPython/ipmaker.pyc in force_import(modname, force_reload)
     61         reload(sys.modules[modname])
     62     else:
---> 63         __import__(modname)
     64
     65

ImportError: No module named ipy_user_conf
WARNING: /Users/admin_mcadminson/.ipython/ipy_user_conf.py does not exist, please run %upgrade!
WARNING: Loading of ipy_user_conf failed.

A: It seems that your version of IPython is outdated, as IPython no longer uses ipythonrc files for configuration.  You probably should just upgrade it.
Before you do that, though, you should probably consider upgrading your python installation to 2.7 as well, since you're using 2.6.

A: The file path was not found, so you could manually create the file with the path /Users/admin_mcadminson/.ipython/ipythonrc to get around the check. I would also recommend to update ipython as a long term solution though.


text:
Q: How to create a common repository of MSBuild .proj files? Since I started using MSBuild for our projects, I've created several .proj scripts that are shared by several projects in our repository. All these shared scripts reside in a single directory.
So far I've been referring to the shared scripts by using a relative path, something like this:
<MSBuild Projects="..\..\common\build\MyScriptA.proj" Properties="ABC=XYZ"/>

However, every project also imports a common .proj script like so:
<Import Project="..\..\common\build\CommonImports.proj"/>

which <Import>s several other things and defines some properties.
This morning I thought I could replace the relative path with a variable, perhaps $(CommonDir), which would be defined by importing the CommonImports.proj mentioned above. This would enable me to call the common tasks like this:
<MSBuild Projects="$(CommonDir)\MyScriptA.proj" Properties="ABC=XYZ"/>

However, I can't figure out a way to define this $(CommonDir) variable in such a way as to make it work in all other MSBuild scripts that import CommonImports.proj, regardless of their location.
This question offers several ways of creating a property containing an absolute path from a relative path, but none of those seem to work if all I do is <Import> the script defining the property.
Question 1: I'm fairly new to MSBuild; is there a better way of creating a "library" of reusable .proj scripts I could run via the <MSBuild> task? I am aware of $(MSBuildExtensionsPath), however I would like the common tasks to reside in my checkout so that our build machine would automatically get the latest versions of the common tasks whenever it performs a checkout.
Question 2: How do I define $(CommonDir) inside CommonImports.proj so as to make it contain the absolute path to the directory containing CommonImports.proj?

A: I wonder if you shouldn't put it in the MSBuild path:
For example, this project is consumed via:
<Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>

and installs itself into:
{program files}\MSBuild\MSBuildCommunityTasks

So perhaps define your own specific sub-folder, and use from there?
<Import Project="$(MSBuildExtensionsPath)\romkyns\CommonImports.proj"/>

etc. Because the $MSBuildExtensionsPath variable is defined separately you shouldn't have as much difficulty with it. Maybe.

A: This isn't a detailed answer, but here's some notes that are generally very useful when people solve this problem. All require MSBuild 4.0 or later.
(1) The $(MSBuildThisFile) property and similar properties. It allows imported files to refer to files relative to themselves, rather than to the project they're imported in. That uncouples them from the project they're imported into.
(2) The "GetDirectoryNameOfFileAbove" function. See here. This wonderfully useful function makes it possible for projects to import files whose location they don't know. Put the shared files (or one single stub shared file that imports the others from somewhere) at the top of your source tree. Then use this function in projects below it to find that stub and import it and thus all your shared build process.
(3) Import tag allows wildcards. This makes it possible to cause a file to be imported -- in other words, extend a build process -- by simply dropping it in a particular location, and editing no existing files.

A: Here's what's worked best for us.
First, check in all reusable stuff into a /common/build/ directory in the VCS.
Then, add a /common/build/CommonImports.proj, looking something like this:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003"
         ToolsVersion="4.0">
  <Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>
  <Import Project="ILMerge.proj"/>
  <Import Project="Mage.proj"/>
  <Import Project="InnoSetup.proj"/>
  <UsingTask TaskName="RT.Tasks.AssemblyVersion" AssemblyFile="Tasks\Release\RT.Tasks.dll"/>
  <UsingTask TaskName="RT.Tasks.WaitForProcessesToTerminate" AssemblyFile="Tasks\Release\RT.Tasks.dll"/>
  <PropertyGroup>
    <BuildSingleProj>$(Root)\common\build\BuildSingle.proj</BuildSingleProj>
  </PropertyGroup>
</Project>

This imports a few projects and tasks that everything uses, and defines a property group that is shared by everything. Then, add this in every build script:
<PropertyGroup>
  <Root>..\..</Root>
  [... other global properties ...]
</PropertyGroup>
<Import Project="$(Root)\common\build\CommonImports.proj"/>

A: 10+ years later, another strategy is to put a Directory.Build.props file in the root of the repository declaring a property using $(MSBuildThisFileDirectory) to get the path to the root of the repository (or other useful place). Then all projects in the repository can use paths relative to the root instead of to themselves.
I would probably only do this if I don't mind an extra file at the root of the repository, and if the repository primarily consists of MSBuildable projects.
Example:
/Directory.Build.props
/common/build/MyScriptA.proj
/common/build/CommonImports.proj

Directory.Build.props:
<Project>
  <PropertyGroup>
    <RepoRootDir>$(MSBuildThisFileDirectory)</RepoRootDir>
    <CommonDir>$(RepoRootDir)common\build\</CommonDir>
  </PropertyGroup>
</Project>

Note that if you use nested Directory.Build.props files, they would need to import upwards using something like this: <Import Project="$([MSBuild]::GetPathOfFileAbove('Directory.Build.props', '$(MSBuildThisFileDirectory)../'))" /> since it stops after finding the first match.


text:
Q: Weekline Plugin Not Displaying Clicked Weekdays I'm trying to integrate this weekline plugin but it seems not be working.
Everything seems fine as I see no jquery error in my console but the weekdays don't show on my input field when clicked on. All other jquery codes are working perfectly.
Below is my code
Jquery:
$("#weekCal").weekLine();
      // Return selected days as labels
         $("#weekCal2").weekLine({
                mousedownSel: false,
                onChange: function () {
                        $("#kid_pickup_days").html(
                                $(this).weekLine('setSelected')
                        );
                }
         });

In the html, I have a span with id="weekCal" which shows the weekdays to be selected and an input field with id="kid_pickup_days" which is supposed to show the weekday as input value when selected, but doesn't.
Any suggestion/solution will be highly appreciated

A: You Should try this;
$("#weekCal2").weekLine({
                    mousedownSel: false,
                    onChange: function () {
                            $("#kid_pickup_days").html(
                                    $(this).weekLine('getSelected')
                            );
                    }
             });


text:
Q: Doctrine2 + Symfony2 with default Inheritance I'm currently working on a model, which doesn't quite satisfy me yet. I got a set of Objects with single-inheritance, which reference another object:
class Category
{
    /** @MongoDB\Id(strategy="auto") */
    protected $id;

    /** @MongoDB\Int */
    protected $categoryId;

    /** @MongoDB\String */
    protected $title;
}

class ProductTypeOne extends BaseProductType
{
    /** @MongoDB\Id(strategy="auto") */
    protected $id;

    /** @MongoDb\ReferenceOne(targetDocument="Category") */
    private $category;

}

The problem I'm facing at the moment, when I create an object ProductTypeOne, I actually know which category it will reference - it's always the same for this ProductType.
I could set a fix parameter, like category_id = 1 - but the architecture within Sf2 & Doctrine2 doesn't allow me to query for the Category Object from within my Entity (Document, as i'm using MongoDB).
class ProductTypeOne
{

    private $category_id = 5;

    public method getCategory()
    {
       /** how to query the CategoryObject with ID=5? */
    }
}

Open for any input, thank's in advance!

A: Just try this then:
class ProductTypeOne extends BaseProductType
{

    static $DEFAULT_CATEGORY = 5;

    // rest of the code

}

At insertion time [in the controller], you set the category:
$product = new ProductTypeOne;

// do whatever you need to fill the instance

$product -> setCategory(
    $this -> getDoctrine() -> getRepository('Category') -> findOneById( ProductTypeOne::$DEFAULT_CATEGORY )
);

// persist $product, beer time

Another approach would be writing you custom ProductTypeOneRepository, and inject the category in its methods.


text: Q: Given function of a curve, how to solve the best minimum transformation to fit a new set of points? Given function of a curve, I want to move it to fit a new set of points and keep the trend of the old curve. Minor curvature adjustments are allowed.


text:
Q: Как получить позицию слова в строке У меня есть строка: "Привет, одолжишь мне свою книгу? Хочу купить себе эти книги!". Есть ли встроенная функция, чтобы определить позицию слова в строке? Если нет, то как возможно получить позицию слова "книгу" в этой строке?

A: С++ - значит, string.
string - значит, find :)
Если char* в духе C - см. strstr

A: Если Qt то:
QString str { "Привет, одолжишь мне свою книгу? Хочу купить себе эти книги! "};
int pos { str.indexOf("книгу") };
if(pos != -1)
    qDebug() << "Позиция" << pos;
else
    qDebug() << "Нету таких";


text:
Q: Get JSON item from URL in Java I have this link: JSON file
This is stored on a online server. All fine but I want to get an item like "hood_id" or "damage_or_theft_car_id" but somehow my code crashes when I launch it. With an error Json object not found
This is what I tried:
public class JSONParser {
    private String read(BufferedReader bufferedReader) throws IOException {
        //Creates new StringBuilder to avoid escaping chars
        StringBuilder stringBuilder = new StringBuilder();
        //Gets the currentLine
        String currentLine;
        while((currentLine = bufferedReader.readLine()) !=null ){
            //Adds the currentLine to the stringBuild if the currentLine is not null
            stringBuilder.append(currentLine);
        }
        //Returns the StringBuilder is String format
        return stringBuilder.toString();
    }

public JSONObject readJsonFromUrl(String JSONurl) throws IOException, JSONException {
    InputStream url = new URL(JSONurl).openStream();
    try {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(url));
        String jsonText = read(bufferedReader);
        JSONArray jsonArray = new JSONArray("[" +jsonText + "]");
        //JSONObject json = new JSONObject(jsonText);
        JSONObject json = jsonArray.getJSONObject(0);
        return json;
    } finally {
        url.close();
    }
}

public void printJSON() throws IOException, JSONException {
    JSONObject json = readJsonFromUrl("http://test.dontstealmywag.ga/api/damage_or_theft_car.php");
    System.out.println(json.toString());
    System.out.println(json.get("hood_id"));
}

}
When I enter json.get("damage_or_theft_car"); The code works. Can anybody help me out? I think the issue is in JSONArrays and JSONOjects

A: "hood_id" is not in the top hierarchy of the json, this is why you probably get :

org.json.JSONException: JSONObject["hood_id"] not found

at the line: System.out.println(json.get("hood_id"));
Just to be sure: when you run:
System.out.println(json.get("damage_or_theft_car"));

The program will execute the line and print the json content.

If you do want to print the value of hood_id, you need to dig into each json in the list. For example:
System.out.println(json.getJSONArray("damage_or_theft_car")
                          .getJSONObject(0).get("hood_id"));


text:
Q: How to browse git branches in Trac 1.0? I set up Trac 1.0, added the entry tracopt.versioncontrol.git.* = enabled to [components] and used the Admin panel to add my repository. While branches show up in the timeline, the source browser does not provide means to browse a different branch, tag or revision like e.g. here (that site uses Trac 0.12 with the GitPlugin, which has been included into 1.0). Is there a setting I missed or does the 1.0 git integration lack this feature? The ?rev=... parameter is simply ignored when entered manually.

A: It should work, but slightly different than the GitPlugin.  They allow all kinds of repositories at the top level now.  So you need to click on the top-level repo name, and then you'll see the "Visit" dropdown box appear near the top of the page.  That will allow you to select a specific branch or tag.
You can see this in Trac's own repository.  The browser takes you too the top-level, and shows a series of repositories.  Now click on one.  For example, cboos.git.  You should see the "Visit" dropdown and be able to pick a branch.