text:
Q: How to efficiently paginate large datasets with PHP and MySQL? As some of you may know, use of the LIMIT keyword in MySQL does not preclude it from reading the preceding records.
For example:
SELECT * FROM my_table LIMIT 10000, 20;

Means that MySQL will still read the first 10,000 records and throw them away before producing the 20 we are after.
So, when paginating a large dataset, high page numbers mean long load times.
Does anyone know of any existing pagination class/technique/methodology that can paginate large datasets in a more efficient way i.e. that does not rely on the LIMIT MySQL keyword?
In PHP if possible as that is the weapon of choice at my company.
Cheers.

A: First of all, if you want to paginate, you absolutely have to have an ORDER BY clause. Then you simply have to use that clause to dig deeper in your data set. For example, consider this:
SELECT * FROM my_table ORDER BY id LIMIT 20

You'll have the first 20 records, let's say their id's are: 5,8,9,...,55,64. Your pagination link to page 2 will look like "list.php?page=2&id=64" and your query will be
SELECT * FROM my_table WHERE id > 64 ORDER BY id LIMIT 20

No offset, only 20 records read. It doesn't allow you to jump arbitrarily to any page, but most of the time people just browse the next/prev page. An index on "id" will improve the performance, even with big OFFSET values.

A: A solution might be to not use the limit clause, and use a join instead -- joining on a table used as some kind of sequence.
For more informations, on SO, I found this question / answer, which gives an example -- that might help you ;-)

A: There are basically 3 approaches to this, each of which have their own trade-offs:

*

*Send all 10000 records to the client, and handle pagination client-side via Javascript or the like. Obvious benefit is that only a single query is necessary for all of the records; obvious downside is that if the record size is in any way significant, the size of the page sent to the browser will be of proportionate size - and the user might not actually care about the full record set.

*Do what you're currently doing, namely SQL LIMIT and grab only the records you need with each request, completely stateless. Benefit in that it only sends the records for the page currently requested, so requests are small, downsides in that a) it requires a server request for each page, and b) it's slower as the number of records/pages increases for later pages in the result, as you mentioned. Using a JOIN or a WHERE clause on a monotonically increasing id field can sometimes help in this regard, specifically if you're requesting results from a static table as opposed to a dynamic query.

*Maintain some sort of state object on the server which caches the query results and can be referenced in future requests for a limited period of time. Upside is that it has the best query speed, since the actual query only needs to run once; downside is having to manage/store/cleanup those state objects (especially nasty for high-traffic websites).

A: SELECT * FROM my_table LIMIT 10000, 20;

means show 20 records starting from record # 10000 in the search , if ur using primary keys in the where clause there will not be a heavy load on my sql
any other methods for pagnation will take real huge load like using a join method

A: I'm not aware of that performance decrease that you've mentioned, and I don't know of any other solution for pagination however a ORDER BY clause might help you reduce the load time.

A: Best way is to define index field in my_table and for every new inserted row you need increment this field. And after all you need to use WHERE YOUR_INDEX_FIELD BETWEEN 10000 AND 10020
It will much faster.

A: some other options,

*

*Partition the tables per each page so ignore the limit

*Store the results into a session (a good idea would be to create a hash of that data using md5, then using that cache the session per multiple users)


text:
Q: Unprovable unprovability In general, mathematical conjectures are resolved by proof, disproof, or proof that they are neither provable nor disprovable.
Is it possible that some open conjectures cannot be settled in any of these ways? That is, are there statements that are independent of, say, $\mathrm{ZFC}$, but not provably independent?

A: There is always in increase in strength, relative to a fixed theory, to prove that something is unprovable in that theory. It follows from the incompleteness theorems that for a sufficiently strong effective theory $T$ (say ZFC), if $T$ proves "$\phi$ is not provable in $T$" for one sentence $\phi$, then $T$ proves $\text{Con}(T)$ and $T$ is inconsistent.
So whenever we want to prove "$\phi$ is not provable in $T$", we have to do so by means not formalizable in $T$. We can add an assumption such as $\text{Con}(T)$, or we can extend $T$ in other ways, for example if $T$ is Peano arithmetic we might prove the independence result in ZFC.
Thus the way that we know a sentence to be independent of ZFC is by proving that independence in some stronger theory. So, while there may be statements independent of ZFC which we have not yet proved are independent of ZFC, we will not know they are independent, so we will not be able to give them as concrete examples for the question being asked.
It is possible to give plenty of examples of particular theories $S$ extending ZFC, and sentences $\phi$ independent of ZFC, so that $S$ cannot prove that $\phi$ is independent of ZFC. The easiest way is to take $\phi$ to be $\text{Con}(S)$ for some theory $S$ whose consistency is not provable in ZFC, e.g. letting $S$ be ZFC plus the existence of a measurable cardinal. I would be interested to see whether other answerers can give more natural examples.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Could not open file for reading! File does not exist using Symfony and PHPExcel I have to insert data of the excel file in MySql table which can be selected from a location and I am using Symfony, PHPExcel and Ajax for this. I have created a file upload button in table. I click on choose files, select the file and click on Upload File then I get error on the console like Could not open "C:\fakepath\CRS_Data.xls for reading! File does not exist". I have read so many same Questions here like this but I was not able to solve the problem even after reading these. Below is my code. So please someone suggest the solution of the problem.

     Upload File

            <input type="file" name="file" id="file">

      <input type="button" id="uploadFile" name="uploadFile" value="Upload File" class="btn"></input>

And the Action is defined as:
public function executeUploadFile(sfWebRequest $request) {

    require_once('/../Classes/PHPExcel.php');
    require_once '/../Classes/PHPExcel/IOFactory.php';

    $path=$_REQUEST['file_path'];

    // path I get is as C:\fakepath\CRS_Data.xls

    $objPHPExcel = PHPExcel_IOFactory::load($path);

    foreach ($objPHPExcel->getWorksheetIterator() as $worksheet){
        $worksheetTitle = $worksheet->getTitle();
        $highestRow = $worksheet->getHighestRow();
        $highestColumn = $worksheet->getHighestColumn();
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);
    }

    //Inserting datas into db
    $i=1;
    $j=0;
    for ($row = 1; $row <= $highestRow; ++ $row)
    {
        $val=array();
        for ($col = 0; $col < $highestColumnIndex; ++ $col)
        {
            $cell = $worksheet->getCellByColumnAndRow($col, $row);
            $val[] = $cell->getValue();
        }

        // Insert data into mysql
        $sql="INSERT INTO tempbackuptable(`bir_le_id`,`bir_le_form_no`,)VALUES($val[0], $val[1])";
        $result=mysql_query($sql);

        $i=$i+1;
    }

    $this->setLayout(false);
    return sfView::NONE;
}


text:
Q: Typescript generics? I am attempting to write a directive in typescript to display a table of items. The model I am using is something like this:
export class Base implements IBase {
    prop1: number;
    prop2: string;
}

export class Concrete extends Base implements IConcrete {
    prop3: number;
    prop4: number;
}

How could I write a directive that takes the Base class and display a list of items. Basically I want a generic directive that I can use to display a list of any object that extends the Base class.

A:
that I can use to display a list of any object that extends the Base class.

You can sepecify a generic constraint using extends. E.g. the following function:
function Foo<T extends Base>(base:T){}

Will accept any base variable as long as it conforms to the structural contract offered by Base (because of T extends Base)

A:
How could I write a directive that takes the Base class and display a list of items

In the following example Displayable would be like "Base" and "TextValue" could be one such class that implements it. This is a simple example that uses Angular2 -- can't vouch for how conventional it is since I don't write much Angular2.
 import {Component, Input, ViewChild} from 'angular2/core';

 interface Displayable {
     displayValue: string;
 }

 class TextValue implements Displayable {
     get displayValue() { return this.value; }
     constructor(private value: string) { }
 }

 @Component({
     selector: 'list-thing',
     template: `

{{title}}

         {{input.displayValue}}

     `
 })
 export class OtherAppComponent<T extends Displayable> {
     @Input() title: string;
     private list: T[] = [];
     addToList(item: T): void {
         console.log('adding', item.displayValue)
         this.list.push(item);
     }
 }

 @Component({
     selector: 'my-app',
     template: `
     <input #box (keyup.enter)="entered(box.value)">
     <list-thing title='stuff you inputted'>
     </list-thing>
     `,
     directives: [OtherAppComponent]
 })
 export class AppComponent {
     @ViewChild(OtherAppComponent) listthing: OtherAppComponent<TextValue>;
     constructor() {
     }
     value: string;
     entered(valueEntered) {
         this.listthing.addToList(new TextValue(valueEntered));
     }
 }


text:
Q: django fixtures loaddata I need to run a already existing django project.
I installed all dependencies, ran syncdb,migrate. Now App is running fine. But I want to load fixtures so that I can test the app with sample data.
I have three files fixtures/first.json /fixtures/thing.yaml fixtures/good_email.yaml
when I am running ./manage.py loaddata fixtures/good_email.yaml I 'm getting this error.
IntegrityError: Problem installing fixture 'fixtures/good_email.yaml': Could not load
Myproject.MYclass(pk=78): columns kabal_id, email are not unique

How can I fix that, I don't want regenerate fixtures, but I need some fixes to my fixtures.

A: You have a unique contraint for two fields, but the data to import would violate this contraint (double value). You have to alter the data to be unique of remove the violating record.


text:
Q: Put MDC Radio Buttons on Separate Rows HTML Noob here: I am trying to get two MDC radio buttons in a form to appear aligned on separate rows (one below another). I have tried putting break tags in various places but it doesn't seem to have any effect.

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Shrine (MDC Web Example App)</title>
    <link rel="shortcut icon" href="https://material.io/favicon.ico">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.0/normalize.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700">
    <link rel="stylesheet" href="https://unpkg.com/material-components-web/dist/material-components-web.min.css">

<form action="home.html">

            <input class="mdc-radio__native-control" type="radio" id="radio-1" name="radios" checked>

        Radio 1

            <input class="mdc-radio__native-control" type="radio" id="radio-2" name="radios" checked>

        Radio 2

</form>

I can get standard radio buttons to appear on separate rows using break tags as follows:
  <input type="radio" name="gender" value="male"> Male

  <input type="radio" name="gender" value="female"> Female

  <input type="radio" name="gender" value="other"> Other

How can I get these radio-1 and radio-2 to appear on separate rows?

A: I think you just entered the brake at the wrong spot, it should be between the two divs of the "mdc-form-fields":
    Radio 1

There are other solutions with a grid system, but this is the simple one


text:
Q: Is there a way to view/access your computer over the network in boot mode For systems with no IPMI or such built in, is there a way to access them over the network to do work and access boot options?
If I am out and I have a machine doing a check disk, would there be a way to send the screen and controls over the network?

A: Yes, you need a external piece of hardware called a IP-KVM. You will commonly find this built in to enterprise class servers but you can get it as separate hardware too (expect to pay $400-$900 depending on the number of devices it can connect to and features).
What this does is act as a 3rd computer on the network that can forward keyboard, video, and mouse signals between the computer you are interested in and the machine you are connecting from via some kind of web interface (often Java or ActiveX powered)


text:
Q: How to use css custom styles in cshtml page? I created a custom css button class in my site.css file in an asp.netcore mvc web application. For some reason, this styling does not show up when I try to use it in a cshtml view. I've tried adding the link, and I've tried adding the style to the Layout page, neither of them work? What am I missing?
My site.css file has this custom button class.
.custom-button {
    background-color: #4CAF50; /* Green */
    border: none;
    color: white;
    padding: 15px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
}

This is what my view looks like.
@{
    ViewData["Title"] = "PlaylistBuilder";
}

        <link rel="stylesheet" href="~/css/site.css" />

PlaylistBuilder

        <input type="button" class="custom-button" value="Create Playlist with your top songs" onclick="location.href='@Url.Action("TopSongCreator", "Playlist")'" />
        <input type="button" class="custom-button" value="Create Playlist with recently played songs" class="btn" onclick="location.href='@Url.Action("RecentlyPlayed", "Playlist")'" />

Tried the first comment, still doesn't work. This is what my view looks like now. Do I need to change something in the layout file?
@{
    ViewData["Title"] = "PlaylistBuilder";
}

    <link rel="stylesheet" href="@(Url.Content("~/css/site.css"))" />

            Playlist Builder

        <input type="button" value="Create Playlist with your top songs" class="custom-button" onclick="location.href='@Url.Action("TopSongCreator", "Playlist")'" />
        <input type="button" value="Create Playlist with recently played songs" class="custom-button" onclick="location.href='@Url.Action("RecentlyPlayed", "Playlist")'" />

A: That view is inserted into the middle of the body element somewhere. It would malform the HTML to place a head element there, and as such the link doesn't act like you are expecting it to.
In addition, the tilde (~) is relevant to razor's helper, and doesn't mean relative to the project's top scope in normal href attributes. You should still use the helper here.
Remove the  element definition and just use the link. Use the helper.
<link rel="stylesheet" href="@(Url.Content("~/css/site.css"))" />


text:
Q: How to move html elements using Javascript? Is it possible to attach html tag to others using Javascript?

 to other
 ?
For instance, I'm creating dropdown menu.
I have div separate from the
 tag

menu1

menu2

sub1

sub2

When I click, say, a link, then I want sub menu to show up under menu1 so result would be like:

menu1

sub1

sub2

The reason why I choose
 to be separated from beginning instead of nested in
 tag is that if I set the
 "hide", it hides but it occupies the space and created big space between menu1 and any content below, so my page looks weird like:
mypage
----------------------------
| menu1
|
|                  <------ big open space div is hiding
|
|
| hello content start here

EDIT
Thanks for the tip guys, I've solved the problem with removing div and have nested
 per suggestion. The elements are still being shifted when submenu shows up but used CSS position:absolute and specifying z-index helped.

A: This is invalid HTML. A li should be contained in either a ol or a ul element. Change

sub1

sub2

to

sub1

sub2

For your main problem, there is no need to put the div (or ideally ul) outside the main ul. When you hide an element by setting its visibility to hidden, it will still take up the empty space. To complete hide it and remove any space it was taking, set the display CSS property to none.
document.getElementById('submenu1').style.display = 'none';

A: Usually you put the submenu in another
 inside an
 in your main menu (so that you get valid HTML), and hide it with display: none CSS property and show it on click.

menu item 1

sub 1

menu item 2

Then in your CSS (or added using js):
  ul.submenu {
     display: none;
  }
  a:hover + ul.submenu, ul.submenu:hover {
     display: block;
  }

This one will work on modern browsers without any js! But you can do it with js too, of course.

A: This is usually done via CSS. You have the entire menu pre-created (note that nesting
 within
 is invalid HTML):

menu1

sub1

sub2

and then you declare in CSS:
ul.submenu {
  display: none;
}

Now you can remove or add the "submenu" CSS class from the
 through JavaScript, or you set the .style.display property.
Or even more elegantly (but less cross-browser compatible, if you still care for old browsers), entirely without JavaScript through pure CSS:
ul.menu > li:hover ul.submenu {
  display: block;
}
ul.submenu:hover {
  display: block;
}

A: If you use display: none in your CSS then the hidden element doesn't need any space:
HTML:

menu1

sub1

sub2

menu2

sub1

sub2

CSS:
li ul {
  display: none;
}

li.active {
  display: block;
}

A:

menu1

sub1

sub2

menu2

Try it, this will make the div take up no space. if you use visiblity: hidden then it will take up space.


text:
Q: How to estimate the parameters of a censored exponential mixture process. I have a real world scenario that involves a process behaving as follows: there are two kinds of machines and when these machines fail, their recoveries follow exponential distributions. Let's say the first kind has rate $\lambda$ of recovering and the second has rate $\mu$. Also, there is some censor level in the data collection process where we don't see the data if it $>c$. If the data is un-censored, we know what kind it is. If it is censored, we lose this information. It could have been any of the two kinds. It's easy to generate data from such a process. We just generate some samples from an exponential with rate $\lambda$ and collect the ones below $c$ in a vector (call it $t$) and the ones above $c$ in another vector (call it $x$). Then we generate some samples from an exponential with rate $\mu$ and collect the ones below $c$ into a vector $s$ and append the ones above $c$ into $x$. Now we have three vectors, $t$, $s$ and $x$. We should be able to devise a censored mixture model and frame a maximum likelihood scheme that allows us to retrieve the values of $\lambda$, $\mu$ and $p$ (the proportion of samples generated from $exp(\lambda)$) from the data, $t$, $s$ and $x$.
Here is my attempt at this. I think it's 66% working but there is one thorn in the side.
The likelihood function will be given by:
$$L(\lambda, \mu, p) = \left(\prod\limits_{s=s_1}^{s_S} \mu e^{-\mu s}\right) \left(\prod\limits_{t=t_1}^{t_T} \lambda e^{-\lambda t}\right)\left(\prod\limits_{x=x_1}^{x_X} (p e^{-\mu x} + (1-p)e^{-\lambda x})\right)$$
Where $S$, $T$ and $X$ are the lengths of vectors $s$, $t$ and $x$. Also, we consistently censor the data at $c$. So, the entire vector $x$ is just a bunch of $c$'s. This makes the expression above:
$$L(\lambda, \mu, p) = \left(\prod\limits_{s=s_1}^{s_S} \mu e^{-\mu s}\right) \left(\prod\limits_{t=t_1}^{t_T} \lambda e^{-\lambda t}\right)\left( (p e^{-\mu c} + (1-p)e^{-\lambda c})\right)^c$$
Taking logarithm on both sides, we get the log-likelihood function:
$$l(\mu, \lambda, p) = \sum\limits_{s}\mu e^{-\mu s} + \sum\limits_{t}\lambda e^{-\lambda t} + c\log(p e^{-\mu c} + (1-p)e^{-\lambda c})$$
The derivatives w.r.t. $\mu$ and $\lambda$ are kind of making sense. However, taking derivative with respect to $p$ we get:
$$\frac{\partial l}{\partial p} = c\frac{e^{-\mu c} - e^{-\lambda c}}{(p e^{-\mu c} + (1-p)e^{-\lambda c})}$$
If we want to set this equal to $0$, we would need:
$$e^{-\lambda c} = e^{-\mu c}$$
However, this is impossible. What might I be missing here?
See code that generates data and calculates gradients with respect to parameters here: https://github.com/ryu577/survival/blob/master/distributions/expmixture.py

A: Interesting problem! The first issue is how we decide to model this situation, we can consider our observations to be drawn from bivariate distribution $(T,C)$ with a continuous and a discrete component. That is, we have $n$ iid observations $(T_i, C_i)$ defined in the following way,
$$T_i = B_i X_i + (1-B_i)Y_i $$
$$C_i = \begin{cases}B_i, \ \ T_i < c \\ 2, \ \ T_i \geq 2 \end{cases} $$
Where $X_i \sim \text{Exp} (\lambda)$,  $Y_i \sim \text{Exp} (\mu)$ and $B_i \sim \text{Bernoulli}(p)$ and they are all independent in the relevant ways. $X_i, Y_i, B_i$ are also all hidden from us, $X_i$ is the output from the first machine and is only given to us when $B_i = 0$ and $Y_i$ is the output from the second machine and is only given to us when $B_i = 1$. But when the output is greater than $c$, $C_i$ censors which machine it came from and so it outputs $2$ as we observe, otherwise we'd observe whatever $B_i$ is.
At this point instead of trying to find the density, we can use an Expectation Maximisation (EM) algorithm to estimate the paramters since this would be a classic application of such since our observations depend on hidden variables.
If we want to find the density instead we need to obtain the joint density. However it is likely that it will not be amenable to analytic solution for the MLE, I calculated the joint density by calculating,
$$f_{T,C}(t,j) = \frac{\text{d}}{\text{d}x} \mathbb{P}[ T_i \leq x, \ C_i = j]$$
We find our density to be,
$$f_{T,C}(t, j) = \begin{cases}\mu (1-p) e^{-\mu x} \cdot \mathbf{1}_{x \leq c}, \ \ j = 0 \\ \lambda p e^{-\lambda x} \cdot \mathbf{1}_{x \leq c}, \ \ j = 1 \\ (p \lambda e^{-\lambda x} + (1-p)\mu e^{-\mu x})  \cdot \mathbf{1}_{x > c}, \ \ j = 2 \end{cases} $$
This seems like it would be impossible to find an analytic solution, so instead we should use an EM algorithm to estimate the parameters of interest. I'll update this response with an explanation soon.


text:
Q: How do I clean up my Jquery code? I'm currently experimenting with JQuery and tried making my own portfolio that would change the project shown on click. I have a lot of duplicated code in there and want to clean it up, I know how I used to do it in Java but I forgot the name of the method.
In the end I would like to have something like this, but I forgot how to do It exactly:
$('.projects a[href^="#"]').on('click',function (e){

        var href = $(this).attr('href');;

        changePortfolio(String head, String text, String imgsource){
                $(".description-head").html(head);
                $(".description-text").html(text);
                $('.preview').attr('src',imgsource);
        }

        if(href == "#project-portfolio"){

            changePortfolio("Portfolio", "this is my portfolio", "bg.png");

        }

My current code:
$('.projects a[href^="#"]').on('click',function (e){

        var href = $(this).attr('href');;

        if(href == "#project-portfolio"){

            $(".description-head").html("PORTFOLIO WEBSITE");
            $(".description-text").html("This is the portfolio website description");
            $('.preview').attr('src','img/bg.jpg');

        } else if(href == "#project-preview2"){

            $(".description-head").html("PREVIEW 2");
            $(".description-text").html("This is the preview 2 description");
            $('.preview').attr('src','img/placeholder.jpg');

        } else if(href == "#project-preview3"){

            $(".description-head").html("PREVIEW 3");
            $(".description-text").html("This is the preview 3 description");
            $('.preview').attr('src','img/placeholder.jpg');

        } else if(href == "#project-preview4"){

            $(".description-head").html("PREVIEW 4");
            $(".description-text").html("This is the preview 4 description");
            $('.preview').attr('src','img/placeholder.jpg');

        }  else if(href == "#project-preview5"){

            $(".description-head").html("PREVIEW 5");
            $(".description-text").html("This is the preview 5 description");
            $('.preview').attr('src','img/placeholder.jpg');

        }
    });

Thanks for reading :)

A: Consider something like this:
const HREF_TABLE = {
    'project-portfolio': {
        'head': "PORTFOLIO WEBSITE",
        'text': 'This is the portfolio website description',
        'preview': 'img/bg.jpg'
    },
    'project-preview2': {
        'head': "PREVIEW 2",
        'text': 'This is the preview 2 description',
        'preview': 'img/placeholder.jpg'
    }
}

$('.projects a[href^="#"]').on('click', function() {
    let href = $(this).attr('href');
    let changeTo = HREF_TABLE[href.substr(1)];

    if ( changeTo !== undefined ) {
        changePortfolio(changeTo);
    }
});

In my opinion, much easy to edit this instead of using the switch-case mechanism...

A: Condensing the cosmetic changes into a function was the first step. The second step I would suggest is taking your long and messy if/else  statements and using a switch, like so:
switch (href) {
    case "#project-portfolio":
        changePortfolio(...);
        break;
    case "#project-preview2":
        changePortfolio(...);
        break;
    // correspondingly for every case
    default:
        changePortfolio(...) // whatever the 'backup' should be
                             // if none of the above cases are met
}


text:
Q: How to make test case for Constructor I am trying to make unit test cases for below class but i am getting exception when i run mvn clean test and i am not understand what is problem can some one help me how can i resolve this problem
eroor
[ERROR] Errors:
[ERROR]   ApplicationErrorHandlerTest.setUp:41 InvalidUseOfMatchers
Misplaced or misuse...

Class
public class BadRequestException extends Exception {

    private static final long serialVersionUID = 1L;

    public BadRequestException() {
        super();
    }

    public BadRequestException(final String message) {
        super(message);
    }
}

Test case
public class ApplicationErrorHandlerTest {

    @Test
    public void BadRequestExceptionTest() throws Exception  {
        BadRequestException badRequestException1 = new BadRequestException();
        BadRequestException badRequestException2 = new BadRequestException(ArgumentMatchers.anyString());
        assertNotNull(badRequestException1);
        assertNotNull(badRequestException2);
    }
}

A: You misuse ArgumentMatchers.anyString().
For your use case you don't need it, you can just pass any string and check that its value was passed to the message field correctly, for example:
   public class ApplicationErrorHandlerTest {

        @Test
        public void BadRequestExceptionTest() throws Exception  {
            BadRequestException badRequestException1 = new BadRequestException();
            Strign testMessage = "testMessage";
            BadRequestException badRequestException2 = new BadRequestExceptiontestMessage);
            assertNotNull(badRequestException1);
            assertNotNull(badRequestException2);
            assertEquals(testMessage, badRequestException2.getMessage());
        }
   }

Regarding ArgumentMatcher - it should be used when you are Mocking your instance with mockito. Please see more details in the official documentation.
In your example you don't mock anything with Mockito, just checking values with Asserts.

A: Using @Parameters annotation to create a set of input data to run our test.
You can follow the working example here.


text:
Q: Do i need to return back the image dimensions for ios in json response? I've built a website that stores images in 4 different sizes on the file system. It keeps the origional file size, medium, thumb, small image and resizes them as they upload.
We then created the web api to allow us to build the ios/android apps.
while building the apis our overseas developer then asked to provide the image dimensions along with the image file name. it took a lot of work regarding calculating the image sizes and saving them to the database.
{ "imagefilename" : "someimage.jpg", "LargeimageHeight" : "1000",
"LargeimageWidth" : "500", "mediumImageHeight" : "500",
"mediumImageWidth" :       "250",
"smallImageHeight" : "100", "smallImageWidth" : "60" }

with the amount of image sections we have in the website made it a task and i want to know if this is really nessesary. Im not an ios developer but not really sure as to why the additioanl dimensions of the image need to be saved and or really needed.
i thought the ios has the image feature (@3x) (@2x) (@3x) ??
or do i use 1 specific folder image size for ios ??
does this always happen in the ios world for images that the code needs to know the image dimensions for the best result?
thanks

A: If your iOS application show images in flow layout (like pinterest style) you must return image dimensions. Otherwise I don't think its nessesary

A: *

*Do you need the return the image dimensions:

*

*Short answer: no. You can load the image using UIImage, and call image.size.height and image.size.width.

*Long answer: maybe, depending on the interface design of your application, and if every image has different dimensions, it might take a performance toll to load the image into memory before being able to get its size (and probably do autolayout and have it render on screen). You might have issues with scrolling speed, but it will depend on the specific design and requirements.

*What is the @2x @3x iOS image feature
iPhone and iPad screens come in different pixel densities (non-retina, retina and the retina iPhone 6+ screen). If you have a local image, stored on the phone, it can preload the image with the right scale automatically, by just providing the base name of the image, if you add the right suffix to each asset like name@2x, etc.
Sadly, it doesn't work the same for remote images see this answer. You will have to check yourself for the scale and load the right image, or load one big file, and let it be resized on the device.

A: You should consider providing dimensions inside your API response.
Think design:
When you scale your app to have many images at once, or when you distribute your app to multiple devices, you may realize the advantage. Your iphone 4 may end up downloading the image (worse, images) intended for iPhone 6S, and so on. If the reverse is true, it's even scary to think about.
How about the device asking for the image it's best suited for?
As for scaling of images, Bram De Geyter is correct - you can render whatever resides on the device, not fetch the correct one from the server. So having your API giving you the right dimensions is the only solution.
I have described the whole image loading from API approach in my blog here.


text:
Q: Unbound Value for List.i I keep getting an unbound value error in this code segment:
let count element list =
  let counter = 0 in
    for i = 0 to List.length list do
      if element == List.i list then
        counter = counter + 1
      else
        counter = counter
    done ;;

The code is supposed to take a list and a value from the user and then count how many times the value appears in that list, but I keep getting this error:
Error: Unbound value List.i

I am still a beginner to Ocaml any help would be greatly appreciated.

A: List.i does not exist in Ocaml.
You are trying to check if the ith element of the list is equal to element.
List.nth does the trick:

List.nth list i

instead of
List.i list

The final code :
let count element list =
  let counter = ref 0 in
    for i = 0 to (List.length list - 1) do
      if element == List.nth list i then
        counter := !counter + 1
      else
        counter := !counter
    done ;
 !counter;;


text:
Q: Firebase dynamic link parameters are not passed to a google app script webapp webhook I have deployed a google app script as a webapp. Calling this script with different GET parameters triggers different functions. It works perfectly fine.
I have created a firebase dynamic link that points to the webapp endpoint. When I call this dynamic link with GET parameters, there is a redirection to the correct webapp endpoint, but the parameters are not passed through. I have checked that in the console.
I only observe this behavior when the target link is a webapp - if the dynamic link is pointing to a standard web page, the URL parameters are passed through...
How can I fix that, so that parameters are correctly passed from my dynamic link call to my webapp endpoint call?
Thanks for your help


text:
Q: Only include in where condition if date is not low date(01/01/0001) I have a query that has a where condition to check and find addresses that were added after a certain date. The date field is not required so I want Date field in where condition to be only considered if it is not 1/1/0001.
dtmDate is the parameter that is being passed
Query
from b in _context.customer
           join d in _context.Address on b.id equals d.Id
           join e in _context.units on d.Id equals e.Id
           where (req.dtmDate.Year != 1 && d.DateAdded >= req.dtmDate)

select new modelAddress
              {
               address= d.address
              }

But this is not working. It is not returning any rows

A: I'd leverage the fact that LINQ queries are not executed when you write them, so you can add clauses conditionally after you've created a base query:
var query = from b in _context.customer
       join d in _context.Address on b.id equals d.Id
       join e in _context.units on d.Id equals e.Id;

if(req.dtmDate.Year != 1)
  query = query.Where(d.DateAdded >= req.dtmDate);

var result = query.Select(
  new modelAddress
  {
    address= d.address
  }
);

I prefer this because I've previously run into issues, particularly with EF LINQ queries when the Where clause contains something that evaluates to true locally with in the code, rather than as something the DB will evaluate. It seems to work out better when "wildcarding" DB queries, to use a pattern of "if x is true then add-another-where-clause" rather than saying "where(local-value-of-x-equals-local-constant OR some-db-data-value-equals-y)"

A: If I understand you correctly, you have a DateTime object called req.dtmDate that may be set to a default value, and you want to return all items where the item's DateAdded field is greater than req.dtmDate, unless req.dtmDate is 1/1/0001, in which case all records should be returned.
If that's the case, I think you could just modify your existing code to:
where (req.dtmDate.Year == 1 || d.DateAdded >= req.dtmDate)


text:
Q: How to remove space after last element in list list = [1, 2, 3, 4]

for element in list:
    print(element, end=" ")

For this code, the output is: 1 2 3 4 .
But there is a space after the last element(4).How can I remove only that last space?I tried adding sep=" " before the end=" " but it doesn't work.

A: You could just use join here:
values = [1, 2, 3, 4]
output = ' '.join([str(x) for x in values])
print(output)  # 1 2 3 4

A: This would also work.
lst = [1, 2, 3, 4]
for element in lst:
    if element == lst[len(lst)-1]:
      print(element)
    else:
      print(element, end=" ")

A: You can print the first n-1 elements with space and then print the last element separately.
l = [1, 2, 3, 4]
for i in l[:-1]:
    print(i, end=" ")
print(l[-1], end="")

A: The easiest solution would be to print everything, but the last element with space, then print the last without a space:
lst = [1, 2, 3, 4]

for i in range(len(lst) - 1):
    print(lst[i], end=" ")

print(lst[len(lst) - 1])

A: You can print the list by converting it into a list and then use join()
my_list = [1,2,3,4] # Don't use keywords for naming variables (it is a bad practice)
my_list = [str(x) for x in my_list]
print(' '.join(my_list))

If you want a longer solution then
my_list = [1,2,3,4]
for i in range(len(my_list)):
    if i != len(my_list)-1:
        print(str(my_list[i]) + " ", end='')
    else:
        print(str(my_list[i]), end='')

A: The simplest way is:
print(*lst)

* operator is for unpacking, it passes individual list items to the print function like print(1, 2, 3, 4). print function use default " " space for the separator.
note: Internally print calls __str__ method of the elements, I mean it convert it to the string.
Also don't forget to not using built-in names like list.


text:
Q: Meteor alanning:roles - Error invoking Method 'updateRoles': Internal server error [500] I am trying to set the role for the logged in user (using alanning:roles package) via a method on the server. Here's what I have...
Client
var userId = Meteor.userId();
Meteor.call('updateRoles',userId,'admin');

And this is the simplified version of the method from the docs...
server/userMethods.js
Meteor.methods({
    updateRoles: function (targetUserId, roles) {
        Roles.setUserRoles(targetUserId, roles)
    }
})

No matter what I try I keep getting the following error...
Error invoking Method 'updateRoles': Internal server error [500]

A: Problem solved.
The reason was because I am using autoform (simple schema) for the 'users' collection and I needed to include the following (uncommented part) in the schema...
// Add `roles` to your schema if you use the meteor-roles package.
// Option 1: Object type
// If you specify that type as Object, you must also specify the
// `Roles.GLOBAL_GROUP` group whenever you add a user to a role.
// Example:
// Roles.addUsersToRoles(userId, ["admin"], Roles.GLOBAL_GROUP);
// You can't mix and match adding with and without a group since
// you will fail validation in some cases.
//
//roles: {
//    type: Object,
//    optional: true,
//    blackbox: true
//},
// Option 2: [String] type
// If you are sure you will never need to use role groups, then
// you can specify [String] as the type

roles: {
    type: [String],
    optional: true
},


text:
Q: Why aren't Google Docs results appearing in Chrome's omnibox results? I'm often searching for docs according to keywords in their title. Strangely, Chrome matches items from the browsing history that contain such keywords in their title but results from google docs don't appear.
Any ideas why this is happening or how to work around it?


text:
Q: CakePHP - Change the $useTable var from within the Model Question:
How do I change the $useTable from within the model?
I would like to change the $useTable value in my beforeSave (or save) method in the model based on data passed in the save. Is this possible?

What I've already tried:

*

*I tried changing $this->useTable but it didn't work. It changed the actual variable, but it turns out that useTable value is cached when $Model->save is used.

I know I can change this value from the Controller before calling save, but I would rather handle this in my model based on the data passed.
Any ideas?

A: I ended up using $this->setSource('table_name') in the beforeSave method inside the model, and it effected the final save. I had seen setSource used from a controller, but didn't think to use it inside the model.


text:
Q: How to store collection of value object in single field without creating new table in EF Core I am using EF Core as my ORM, and I am learning Domain Driven Design.
As you may already know in DDD value object have no identifier and creating a separate table for value objects is not good practice.
But I want store a collection of value object without creating a new table, so how should I do that? Look at below example:
public class User : Entity
{
      public ICollection<Address> Addresses { get; set; }
}

public class Address : ValueObject
{
     public string Country { get; set; }
     public string City { get; set; }
     // some other properties
}

A: so as alexander said , i decide to use value conversions(like below) :
public class UserConfiguration : IEntityTypeConfiguration<User>
{
    public void Configure(EntityTypeBuilder<User> builder)
    {
        builder.Property(user => user.Addresses)
            .HasConversion(
            a => (string)JsonConvert.SerializeObject(a),
            a => JsonConvert.DeserializeObject<List<Address>>(a));
        /*builder.HasData(Data.GetData<User>());*/
    }
}

and now a collection of address will store in single field


text:
Q: Type 'Subject' is not assignable to type 'boolean' I want to add a load in my aplication, but my HTML has a problem.
I declared the variable like that:
public loading: Subject<boolean> = this.loaderService.isLoading

and that's my HTML:
<ngx-loading [show]="loading" | async></ngx-loading>

The error occurs in "[show]"

A: Change
<ngx-loading [show]="loading" | async></ngx-loading>

to
<ngx-loading [show]="loading | async"></ngx-loading>


text:
Q: is SimpleStringSchema from the two path in jar the same? In intellij,SimpleStringSchema can be imported from two places.
import org.apache.flink.streaming.util.serialization.SimpleStringSchema;
import org.apache.flink.api.common.serialization.SimpleStringSchema;
are they always the same for our project?
Thanks for your help

A: Their behavior should be the same because the one in org.apache.flink.streaming.util.serialization extends the one in org.apache.flink.api.common.serialization. I am not exactly sure why there were two classes created though.
It's worth mentioning that You should use only org.apache.flink.api.common.serialization.SimpleStringSchema as the other one has been deprecated.


text:
Q: Cannot get the URL parameter correct for Google-Apps-Script REST API into firestsore From here
https://cloud.google.com/firestore/docs/reference/rest/v1/projects.databases/get
I keep getting the error:
The requested URL /v1/projects/transaction1-111/databases/data/test1 was not found on this server. That's all we know.
My database id: transaction1-111
Database: data
collection: test1
However it does not go through.
Yes I authorized
Yes I include the correct scopes
function example5() {

var options = {
  headers: { 'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken() },
  method:'GET',
  payload: JSON.stringify({fields: { title: { stringValue: 'newTitle' } } }),
  contentType: "application/json",
  muteHttpExceptions:true
}

var response = UrlFetchApp.fetch('https://firestore.googleapis.com/v1/projects/transaction1-111/databases/data/test1', options);

Logger.log(response.getContentText());

}

Also how do I know what version I am using ie rest/v1 or rest/v2 or rest/beta...


text:
Q: AWS Cloudsearch: cs-configure-from-batches Resource not found I am attempting to add index fields to a cloudSearch domain I have just created, but I am getting errors doing so.
I create the domain using:
aws cloudsearch create-domain --domain-name test-run

If I view information about the domain using the below command I get results including indication the the domain has been created.
aws cloudsearch describe-domains --domain-name test-run

I can also view this information using  the CloudSearch console.
However, when I try to run
cs-configure-from-batches --domain-name test-run --source scripts/SeedFile.json -c ~/.aws/credentials

I get the below error
Domain not found: test-run (Service: AmazonCloudSearchv2; Status Code: 409; Error Code: ResourceNotFound;

A: Solution:
the endpoint defaults to a us east endpoint. I needed to specify us-west with --endpoint on the command


text:
Q: Extending the Dirac delta to $L^p$ In this question the Dirac delta is extended from $\mathcal C^0([-1,1])$ to $L^\infty([-1,1])$ by the Hahn-Banach theorem.
My question is: why can't it be extended to an arbitrary $L^p([-1,1])$ for $p \geq 1$?

A: To extend $\delta$ to act on $L^p$ along the idea you mention, you need to consider $C[-1,1]$ as a subspace of $L^p[-1,1]$. In that case $\delta $ is not bounded, so Hahn Banach does not apply.
For instance let $f_n(t)=\max\{0,1-n|t|\}$. Then $\delta(f_n)=1$ for all $n$, while $$\|f_n\|_p=\frac{2^{1/p}}{(p+1)^{1/p}}\,\frac1{n^{1/p}}\to0.
$$

A: $f \to f(0)$ is a continuous linear functional on $C[0,1]$ with the norm from $L^{\infty}$. So Hahn Banach Theorem shows that it extends to a continuous linear functinal on $L^{\infty}$. However, $f \to f(0)$ is not continuous on $C[0,1]$ w.r.t the $L^{p}$ norm. It does not extend to a an element of $L^{p'}=(L^{p})^{*}$.
[Let $f_n(x)=1-nx$ for $0 \leq x \leq \frac  1 n$ and $0$ for $x >\frac  1 n$. Then $f_n$'s are continuous, $f_n \to 0$ in $L^{p}$ but $f_n(0)=1$ for all $n$].


text:
Q: Spring Security Google Sign In With Session Rest Service I am new to Spring ecosystem, and with the limited knowledge I had with Spring, I understood how Spring Security OAuth2 works.
I need the following functionality, and I think OAuth2 is not what I should be looking at

*

*Client sends the id_token received from Google sign in via a POST request to /register endpoint.

*Backend service validates the id_token and identifies user details from Google's Java SDK.

*Backend service responds with a set-cookie header upon successful id_token verification.

*Further client requests containing the cookie should be authenticated.

I am even fine with the service authenticating every request using id_token
I want the service to be consumable by any client (not only browsers). So, I think OAuth2 is not the right way.
I have watched a lot of videos on youtube and read this and got really confused. Please help me understand how to implement this functionality, or at least point me to the right resource to read and understand.

A: If you want to access from different types of clients (browser, mobile, etc) then the one approach is to go with JSON Web Token(JWT).
refer


text:
Q: complete css form reset So there are a lot of resets out there, and there are a lot of form stylers for cross-browser forms. My issue is that none of the resets I can find fully reset forms!
Formalize is great, but I want to style it myself from the ground up, where formalize simply has it already styled.
Is there any reset.css that has full capabilities to reset every form element? If so, where?

A: This may not be the most informative answer ever but I would strongly recommend creating your own form reset if you can't find one online. A lot of the resets aim to cover just 90% of the browser styling in order to keep code overhead down.
To do it yourself use current resets as inspiration and use the Chrome Inspector tool to find out why a form is styled by default in a particular way and counteract it. Then work with other browsers (with Firebug for Firefox etc) until your form is as consistently styled as possible. You can always add to this reset in future projects if you find things are missing.
If you do decide to create one you should share it on GitHub for others who may need it in the future.


text:
Q: Speed up (not turn off) animations in windows 10? Is there a way to increase the speed of all animations in Windows 10?
I know you can disable it entirely through the System > Advanced Settings > Performance Settings > Visual Effects tab. But I like the animations and just want them to happen faster.

A: Damn this old, but I found an article explaining how to achieve that. Heres the sauce.
Warning
First of all the standard warning, that this will include changing a registry-entry which, when done wrong, may be able to brick Windows. So be careful and pay attention.
Solution

*

*First open the registry editor: Press "Windows + R" and type in regedit, then hit ok. You should be prompted for admnistrative rights from the UAC, hit yes on that and continue

*In the new window find your way to HKEY_CURRENT_USER\Control Panel\Desktop (you can copy & paste this path in the box above, easier then to go through everything yourself)

*Now select the entry called MenuShowDelay in the right pane, right-click it and modify the value from (default) 400 to anything you'd like. I would suggest changing it to 250
Congratulations, you have successfully changed the animation speed in Windows!

Please note, that the changes won't take effect until you have rebooted your machine


text:
Q: Delete/Drop columns using hibernate I am using Oracle Timesten 11 DB and I have to drop a column from my application. I tried using SchemaUpdate in the beginning but it didn't work. Then I used SchemaExport's execute method to drop the column; Though the drop column was succesful, it ended up deleting all the records in the table. Also, I am using a .jar file as input to do create/delete/modify tables. Kindly help me fixing this issue.

A: From my perspective JDBC is the way to go if DDL operations are what you want to perform from your application. SchemaUpdate's purpose should be performing synchronization between your business model and database physical structure.
EDIT
Just now figured out that you probably updated your business model (entities) by removing field(s), and are wondering why it isn't reflected on your DB. SchemaUpdate will create new columns (and tables) but it will not drop those removed from your entities.
EDIT2

Then I used SchemaExport's execute method to drop the column; Though
  the drop column was succesful, it ended up deleting all the records in
  the table.

It seems that you used schema export strategy that doesn't 'update', instead it drops existing tables and creates new ones when SessionFactory gets created (see Hibernate property hibernate.hbm2ddl.auto, most likely value was set to create-drop).


text:
Q: EditText calls onFocusChanged three times instead of once I have to do a ListView that contains on each item an EditText. If the EditText receives focus, I have to display a dialog - the condition is strictly for when the EditText receives focus and not when is pressed because it can be selected even if it is not pressed...
To do this I use a focus listener on the EditText but the onFocusChanged gets called three times instead on only one when the user presses the EditText, this means the dialog gets called twice...
This is the sequence of the calls:

*

*Has focus

*Lost focus

*Has focus
I don't have any other special handling of the ListView or EditText .. so it should be from the system somehow, maybe because I am using the EditText on the ListView which is a focusable View too..
Does anyone have any ideas why is this happening and how can I "fix" this?
Thank you in advance.


text:
Q: Using Tikz Fit to draw a node covering a Tikz chains A chain of nodes is drawn using tikz chains.  I would like to draw a rectangle node covering the chain nodes (or, multiple rectangle nodes covering subsets of them). I am using tikz fit.
Unfortunately, by the way I use it, the rectangle nodes are considered part of the chains. As a result, additional join edges are drawn to the rectangle positions are kind of messed up. The following are the MWE:
\documentclass[border=5pt]{standalone}

\usepackage{tikz}
\usetikzlibrary{chains, fit}

\begin{document}
\begin{tikzpicture}[start chain, node distance=5mm, every node/.style={draw, on chain, join}, every join/.style=->]
  \node (a)  {a};
  \node (b)  {b};
  \node  (c)  {c};
  \node  (d)  {d};
  \begin{scope} [start branch=numbers, every join/.style=<-]
    \node (1) [on chain=going above] {1};
    \node (2) [on chain=going above] {2};
  \end{scope}
  \node  (e)  {e};
  \node (fit2) [draw, inner sep=2pt, fit=(a) (b) ] {};
  \node (fit1) [draw, inner sep=2pt, fit=(d) (1) (e)] {};
\end{tikzpicture}
\end{document}

The result, without and with the covering rectangles, are

A: Don't include the last two nodes in the scope where you say every node/.style=on chain or overwrite the every node style again.
Code A
\documentclass[border=5pt, tikz]{standalone}
\usetikzlibrary{chains, fit}

\begin{document}
\begin{tikzpicture}[node distance=5mm]
 \begin{scope}[start chain, every node/.style={draw, on chain, join}, every join/.style=->]
  \node (a)  {a};
  \node (b)  {b};
  \node  (c)  {c};
  \node  (d)  {d};
  \begin{scope} [start branch=numbers, every join/.style=<-]
    \node (1) [on chain=going above] {1};
    \node (2) [on chain=going above] {2};
  \end{scope}
  \node  (e)  {e};
 \end{scope}
  \node (fit2) [draw, inner sep=2pt, fit=(a) (b) ] {};
  \node (fit1) [draw, inner sep=2pt, fit=(d) (1) (e)] {};
\end{tikzpicture}
\end{document}

Code B
\documentclass[border=5pt, tikz]{standalone}
\usetikzlibrary{chains, fit}

\begin{document}
\begin{tikzpicture}[node distance=5mm, start chain, every node/.style={draw, on chain, join}, every join/.style=->]
  \node (a)  {a};
  \node (b)  {b};
  \node  (c)  {c};
  \node  (d)  {d};
  \begin{scope} [start branch=numbers, every join/.style=<-]
    \node (1) [on chain=going above] {1};
    \node (2) [on chain=going above] {2};
  \end{scope}
  \node  (e)  {e};
  \tikzset{every node/.style={draw, inner sep=+2pt}}
  \node (fit2) [fit=(a) (b) ] {};
  \node (fit1) [fit=(d) (1) (e)] {};
\end{tikzpicture}
\end{document}


text:
Q: File upload in asp.net mvc using ajax I have a simple html form with two controls:
input-text and input-file
I need to write an ajax query (using jquery is better) to send data (file and value from text field to mvc acton)
I wrote
$.ajax({
    type: "POST",
    url: "/controller/acton",
    enctype: 'multipart/form-data',
    data: 'text=' + $("#text").val() + '&file=' + $("#file").val()
...

and in controller:
 [HttpPost]
  public ActionResult StoreItem(FormCollection forms)
  {
     foreach (string inputTagName in Request.Files)
  ...

this returns null in Request.

A: http://www.plupload.com is awesome

A: You can't POST a file using only javascript.
Look at http://www.uploadify.com/ or something like http://www.swfupload.org/


text:
Q: How to correctly create a configurable product with multiple attributes and images I'm trying to create some configurable products programmatically, but I think I'm missing a step somewhere. I'm basing my code mostly off of inchoo's tutorial, but also off of about 2 dozen other questions/articles.
At this point in my code, I have all of the attributes and simple products containing each combination of variations already created. I'm just trying to create the configurable product:
// Do the normal product creating bit:
$prod = Mage::getModel('catalog/product');
$prod->setWebsiteIds([1])
    ->setAttributeSetId($set_id)        // Ex: 100
    ->setTypeId('configurable')
    ->setCreatedAt(strtotime('now'))
    ->setUpdatedAt(strtotime('now'))
    ->setSku($sku)                      // Ex: 'foo_bar'
    ->setName($name)                    // Ex: 'Foo Bar'
    ->setWeight($weight)                // Ex: 11.22
    ->setStatus(1)
    ->setTaxClassId(4)
    ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)
    ->setPrice($price)                  // Ex: 19.49
    ->setDescription($description)      // Ex: 'Description Here!'
    ->setShortDescription($name)        // Ex: 'Foo Name'
    ->setCategoryIds($categories)       // Ex: [200, 201, 202, 203]
    ->setStockData([
        'use_config_manage_stock' => 0,
        'manage_stock' => 1,
        'is_in_stock' => 1,
    ]);

// This seems a bit silly to me, but it's the only way I've found to both add an image
// to a product AND give it a label at the same time.
foreach ($attributes as $attribute) {
    $prod->addImageToMediaGallery($attribute['image_url'], null, false, false);
    $gallery = $prod->getData('media_gallery');
    $lastImage = array_pop($gallery['images']);
    $lastImage['label'] = $attribute['text'] . '-swatch';
    array_push($gallery['images'], $lastImage);
    $prod->setData('media_gallery', $gallery);
}

// The main image gets added last or it messes everything up.
$prod->addImageToMediaGallery($main_image, ['image', 'small_image', 'thumbnail'], false, false);

// $attr_ids contains the attributes used in the configurable attributes from $set_id
$prod->getTypeInstance()->setUsedProductAttributeIds($attr_ids);
$config_data = $prod->getTypeInstance()->getConfigurableAttributesAsArray();
$prod->setCanSaveConfigurableAttributes(true);
$prod->setConfigurableAttributesData($config_data);
// Shown below
$prod->setConfigurableProductsData($variation_infos);
$prod->save();

The $variation_infos array looks like this: [product_id] => [ 0 => [data] ]:
Array
(
    [141] => Array
        (
            [0] => Array
                (
                    [label] => Red
                    [attribute_id] => 158
                    [value_index] => 307
                    [is_percent] => 0
                    [pricing_value] => 0
                )

        )

    [142] => Array
        (
            [0] => Array
                (
                    [label] => Green
                    [attribute_id] => 158
                    [value_index] => 308
                    [is_percent] => 0
                    [pricing_value] => 0
                )

        )
)

Using this code, the configurable product is created, however, when logging into the back-end and clicking on the configurable product that was just made, I'm greeted with this:

I thought the whole $prod->getTypeInstance()->setUsedProductAttributeIds($attr_ids); line was supposed to select those attributes.
Anyways, I check color and hit continue, and everything else looks right at first glance. Going through the 'images' tab shows all of the images as being added correctly. Going to 'associated products' also shows that all of the simple products I selected are there. However, when going to the front end of the site, the default placeholder image is used and I'm not given any dropdowns to select the different attributes.
I've been stuck on this for a few days. Any help would be appreciated.
Thanks!

A: try it
    //this $data - array
    $sku_config = $data['sku']."_config";
    Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);
    $website_ids = array(1);
    $array_category_id = Mage::helper('parser/categorylist')->getCategoryArray();

    $configProduct = Mage::getModel('catalog/product');
    try {
        $configProduct
            ->setStoreId(self::STORE_ID)//you can set data in store scope
            ->setWebsiteIds($website_ids)//website ID the product is assigned to, as an array
            ->setAttributeSetId(self::ATTRIBUTE_SET)//ID of a attribute set named 'default'
            ->setTypeId(self::PRODUCT_TYPE_CONFIGURABLE)//product type
            ->setCreatedAt(strtotime(self::PRODUCT_TIME_CREATED))//product creation time
            ->setSku($sku_config)//SKU
            ->setName($data['name'])//product name
            ->setWeight($data['characteristic']['weight'])
            ->setStatus(self::PRODUCT_STATUS_ENABLED)//product status (1 - enabled, 2 - disabled)
            ->setTaxClassId(self::PRODUCT_TAXT_CLASS_NONE)//tax class (0 - none, 1 - default, 2 - taxable, 4 - shipping)
            ->setVisibility(Mage_Catalog_Model_Product_Visibility::VISIBILITY_BOTH)//catalog and search visibility
            ->setManufacturer($this->hasAttribute('manufacturer', $data['brand'])) //manufacturer id
            ->setPrice($data['price'])//price in form 11.22
            ->setCost($data['price'])//price in form 11.22
            ->setDescription($data['description'])
            ->setShortDescription($this->getShortDescriptions($data['description']))
            ->setCategoryIds(array($array_category_id[$name_cat]))
            ->setStockData(array(
                    'use_config_manage_stock' => 0, //'Use config settings' checkbox
                    'manage_stock' => 1, //manage stock
                    'is_in_stock' => 1 //Stock Availability
                )
            );
        if(isset($data['spec_price']) && !empty($data['spec_price'])){
            $configProduct->setSpecialPrice($data['spec_price']);
        }

        // add image to media gallery
        $importDir = Mage::getBaseDir('media') . DS . 'catalog' . DS . 'product' . DS;
        foreach ($data['url_img_small'] as $key => $fileName) {
            $filePath = $importDir . $fileName;
            $type = ($key == 1) ? array('image', 'thumbnail', 'small_image') : null;
            if (file_exists($filePath)) {
                try {
                    $configProduct->addImageToMediaGallery($filePath, $type, true, false);
                } catch (Exception $e) {
                    Mage::log($e->getLine()."::".$e->getMessage(), null, 'error_download_img.log');
                }
            }
        }
        //magic it's here
        if(isset($data['color']) && !isset($data['size_data'])) {
            $colorAttributeId = Mage::getModel('eav/entity_attribute')->getIdByCode('catalog_product', 'color');// ID = 92

            $configProduct->getTypeInstance()->setUsedProductAttributeIds(array($colorAttributeId)); //attribute ID of attribute 'color' in my store
            $configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();
            $configProduct->setCanSaveConfigurableAttributes(true);
            $configProduct->setConfigurableAttributesData($configurableAttributesData);

            $configurableProductsData = array();
            foreach ($data['color'] as $key => $val) {
                $simple_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $key);
                $simple_product_id = $simple_product->getId();
                $configurableProductsData[$simple_product_id] = array( //['920'] = id of a simple product associated with this configurable
                    '0' => array(
                        'label' => $simple_product->getAttributeText('color'), //attribute label
                        'attribute_id' => $colorAttributeId, //attribute ID of attribute 'color' in my store
                        'value_index' => (int)$simple_product->getColor(), //value of 'Green' index of the attribute 'color'
                        'is_percent' => '0', //fixed/percent price for this option
                        'pricing_value' => $data['price']  //value for the pricing
                    ),
                );
            }
        }

        if(isset($data['color']) && isset($data['size_data']) && isset($data['prod_id'])) {
            $sizeAttributeId   = Mage::getModel('eav/entity_attribute')->getIdByCode('catalog_product', 'size');
            $colorAttributeId  = Mage::getModel('eav/entity_attribute')->getIdByCode('catalog_product', 'color');

            $configProduct->getTypeInstance()->setUsedProductAttributeIds(array($sizeAttributeId,$colorAttributeId)); //attribute ID of attribute 'color' in my store
            $configurableAttributesData = $configProduct->getTypeInstance()->getConfigurableAttributesAsArray();
            $configProduct->setCanSaveConfigurableAttributes(true);
            $configProduct->setConfigurableAttributesData($configurableAttributesData);

            $configurableProductsData = array();
            $array_sku = $data['prod_id'];
            foreach ($array_sku as $key => $val) {
                $simple_product = Mage::getModel('catalog/product')->loadByAttribute('sku', $val);
                $simple_product_id = $simple_product->getId();
                $configurableProductsData[$simple_product_id] = array( //['920'] = id of a simple product associated with this configurable
                    '0' => array(
                        'label' => $simple_product->getAttributeText('size'), //attribute label
                        'attribute_id' => $sizeAttributeId, //attribute ID of attribute 'color' in my store
                        'value_index' => (int)$simple_product->getSize(), //value of 'Green' index of the attribute 'color'
                        'is_percent' => '0', //fixed/percent price for this option
                        'pricing_value' => $data['price']  //value for the pricing
                    ),
                    '1' => array(
                        'label' => $simple_product->getAttributeText('color'), //attribute label
                        'attribute_id' => $colorAttributeId, //attribute ID of attribute 'color' in my store
                        'value_index' => (int)$simple_product->getColor(), //value of 'Green' index of the attribute 'color'
                        'is_percent' => '0', //fixed/percent price for this option
                        'pricing_value' => $data['price']  //value for the pricing
                    )
                );
            }
        }
        $configProduct->setConfigurableProductsData($configurableProductsData);
        $configProduct->save();

    } catch (Exception $e) {
        Mage::log($e->getLine()."::".$e->getMessage(),null,"error_create_config_product.log");
    }
}

also need attribute properties seting "Use To Create Configurable Product" - YES


text:
Q: How to concatenate multiple rows in flexibleSearch query in Hybris My query is returning multiple rows for each group that the user is assigned to, example below:

I need to concatenate each group on a single row for each user, like: groupA, groupB, groupC
I tried using SUBSTRING, SUB SELECT, GROUP_CONCAT.. Nothing worked so far.
Here is the query that returned the example image
SELECT DISTINCT { customer.uid } AS email,
{ customer.lastLogin } AS lastLogin,
{ customer.company } AS company,
{ unit.topLevel } AS site,
{group.uid} AS groups

FROM { B2BCustomer AS customer
JOIN CustomerCMSSiteRelation AS site
ON { site.source } = { customer.PK }
JOIN B2BUnit AS unit
ON {customer.defaultB2BUnit} = {unit.pk}
JOIN PrincipalGroupRelation AS rel ON {customer:PK} = {rel:source}
JOIN UserGroup AS group ON {rel:target} = {group:PK} }

WHERE {unit.topLevel} = 'AR'

A: *

*if string_agg() doesn't work replace it with group_concat
with main as (

SELECT DISTINCT { customer.uid } AS email,
{ customer.lastLogin } AS lastLogin,
{ customer.company } AS company,
{ unit.topLevel } AS site,
{group.uid} AS groups

FROM { B2BCustomer AS customer
JOIN CustomerCMSSiteRelation AS site
ON { site.source } = { customer.PK }
JOIN B2BUnit AS unit
ON {customer.defaultB2BUnit} = {unit.pk}
JOIN PrincipalGroupRelation AS rel ON {customer:PK} = {rel:source}
JOIN UserGroup AS group ON {rel:target} = {group:PK} }

WHERE {unit.topLevel} = 'AR'
)

select
email,
lastLogin,
company,
site,
STRING_AGG(groups,',') as groups_combined
from main
group by 1,2,3,4


text:
Q: How to set quotes for third layer of nesting in yaml for hass.io? I have a simple TTS application that should respond with one of a few possible sentences after commanding the lights to turn on or off (trigger.event.data.state).
Unfortunately it currently reads literally "turning left curly bracket left curly bracket trigger dot event dot data dot state right curly bracket right curley bracket".
payload: '{{ ["ok", "turning \"{{ trigger.event.data.state }}\" "] | random }}'

I do need the outer ' ' quotes for home assistant.
I also seem to need the " " quotes for the individual elements in the array.
How can I have a third level of quotes to get the trigger.event value in, so it reads "turning on" or "turning off" depending on the event?
I tried '' "" \" /", +, &, all sort of things to stitch that sentence together.
Any ideas?

A: Use a block scalar:
payload: >-
  '{{ ["ok", "turning \"{{ trigger.event.data.state }}\" "] | random }}'

> starts a folded block scalar.
All subsequent lines that are more indented are parsed literally without processing any special characters. Multiple lines are concatenated via a space character (unless separated with empty lines, which generate a newline character). The - modifier causes the final newline character of the last line to be stripped away (rather than being preserved, which is the default behavior).


text:
Q: MySQL 'cant reopen (temporary) table) Attempting to normalize a column (wgt) by joining to the result of an inline query as follows:
select a.monthEnd, ticker, wgt/totWgt
from hold a
inner join (
            select monthEnd, sum(wgt*(1+totRet)) as totWgt
            from hold
            group by monthEnd ) tot
            on a.monthEnd = tot.monthEnd

Get the following error:
Error Code: 1137. Can't reopen table: 'a'  0.00023 sec
I'm coming from SQL Server and not acquainted.  What exactly is the issue and/or workaround here?  Both tables referenced are temporary tables created within a stored proc and running MySQL 8.0.

A: Please use WITH clause,
WITH hold as
(SELECT monthEnd, wgt, totWgt , totRet, ticker FROM <actual table>)
select a.monthEnd, ticker, wgt/totWgt
from hold a inner join
(select monthEnd, sum(wgt*(1+totRet)) as totWgt from hold group by monthEnd ) tot
on a.monthEnd = tot.monthEnd;


text:
Q: AJAX jQUERY to pass data in POST to codeigniter Controller I want to pass data to my controller in POST method using AJAX and Jquery.
It looks some thing like this: https://jsfiddle.net/10bhsd2o/
I have bootstrap drop-down that displays records from database.

  Your Sites

<?php

foreach($sites as $site)
{

echo "
site_key'>".$site->site_key."
";
}?>

Now I want to send the data to my controller,the item i select from dropdown of the

 tag.
This is my script:

HTML GENERATED

54th-65hy

HT45-YT6T

Controller
public function index()
{

    var_dump($_POST);
    print_r($_POST);
    $this->data['subview'] = 'customer/dashboard/index';
    $this->load->view('customer/_layout_main',$this->data);
}

Now my my alerts are correct i get proper url in alert i get proper data in alert.
But in my controller when i do print_r($_POST); i get blank array WHY? Where am i going wrong?

A: Change your html markup.  since your looping inside an anchor

      Your Sites

        <?php
          foreach($sites as $site)
          {
            echo "
site_key'>".$site->site_key."
";
          }
        ?>

Then change your click function
    $( ".specialLink" ).click(function() {
        var value = this.id;
        var url= "<?php echo base_url('customer/dashboard/index') ?>";
        alert(url)
         //get value for throw to controller
        alert(value);
        $.ajax({
            type: "POST", //send with post
            url: "<?php echo base_url('customer/dashboard/index') ?>",
            data: {value:value},
            success:function(data){
            alert(data)
            }
        });
    });

I don't know if your using the index function for other views but for testing purposes.  Try this first
    public function index()
    {
        if(!empty($_POST)){
            var_dump($_POST);
            print_r($_POST);
        }else{
            $this->data['subview'] = 'customer/dashboard/index';
            $this->load->view('customer/_layout_main',$this->data);
        }
    }

Let me know what you get on your 3rd alert

A: You Just Change in You Javascript
You remove $("#specialLink").submit(function(){ and });

A: $( ".specialLink" ).click(function() {
        var value = this.id;
        var url= "<?php echo base_url('customer/dashboard/index') ?>";
        alert(url)
        alert(value);
    $.post(url,{value:value},function(data){alert(data)});
  });


text:
Q: Paging using ldapsearch I am searching an LDAP directory that has a much larger number of results than the sizelimit currently set,500, by slapd.conf that for all intents and purposes cannot be changed)
My idea was to keep running ldapsearch but from a different offset each time (501, 1001, etc.) until all results have been obtained.
I have seen the man pages for ldapsearch, and it appears that this is handled for you using the -E options:
-E [!]<ext>[=<extparam>] search extensions (! indicates criticality)
         [!]domainScope              (domain scope)
         [!]mv=<filter>              (matched values filter)
         [!]pr=<size>[/prompt|noprompt]   (paged results/prompt)
         [!]subentries[=true|false]  (subentries)
         [!]sync=ro[/<cookie>]            (LDAP Sync refreshOnly)
                 rp[/<cookie>][/<slimit>] (LDAP Sync refreshAndPersist)

So i tried:
ldapsearch -h $HOST -p $PORT -x -L -b "$BASE" '*' '+' -E pr=$SIZE
However when the results (even paged results with size = 50 for example) hit 500, I get the same error as if the results were not paged:
Size limit exceeded (4)
I have seen in the man pages there is another option for virtuallistview but have been unable to find examples for it, and as well I dont think my version of ldapsearch has this option.
The goal here is to create a backup using ldapsearch and the -L option to create an ldif file that is suitable for restoring the database.
A few google searches show up with the same problem I'm having, but none have an applicable solution..

A: ldapsearch -LLL  -x -h $LDAPHOST -b"dc=whatever" -D${LDAPUSER} -w"${LDAPPASW}" objectclass=* -E pr=2147483647/noprompt

The important part is at the end: -E pr=2147483647/noprompt. I implemented this today, so I know it works, at least with Active Directory's LDAP backend. For me, this was able to bypass server limits.
From your example, it looks like you may be missing a /noprompt or /prompt. The difference is that with /prompt, it stops between each page.
I am not sure why the number 2147483647 works, but it does.
My source: http://www.commandlinefu.com/commands/view/2779/bypass-1000-entry-limit-of-active-directory-with-ldapsearch

A: The directory server administrator is free to impose a limit on the number of entries that can be returned in the response to a search request. The LDAP client can request a size limit, but this client-requested limit cannot override the server-imposed limit. The paging is working correctly: paging simply sends multiple search responses, each the size requested by the client, but still cannot exceed the size limit imposed by the server. The Virtual list View is similar to the simple paging, except that the LDAP client can start and resume anywhere, whereas in simple paged results, the LDAP client must read through results sequentially.

A: ApacheDS can do the paged searches you are looking for.  At least against Active Directory.


text:
Q: How to "BindTo" Kendo Grid AutoComplete to Razor MVC Model List I am trying to bind the Kendo AutoComplete to the model of a view. I cannot seem to get it set right. This is how i am trying to bind to the model property list
The property is a collection of the model as below:
@Html.ColumnDropDownFor(z => z.Owner, Model.OwnerList.ToKeyValueSelectList())
This is the HTML View:
 @(Html.Kendo().AutoComplete()
          .Name("countries")
          .Filter("startswith")
          .Placeholder("--Select Owner--")
          .BindTo("@z.OwnerList")
          .Separator(", ")
    )

I currently get the control rendered but know values found in the autotype. This colelction property does work when i use a control like below so i know there are values in it.
@Html.ColumnDropDownFor(z => z.Recipient, Model.OwnerList.ToKeyValueSelectList())

A: The BindTo method expects a collection of objects, but you are passing a string instead. Try this:-
.BindTo(Model.OwnerList.ToKeyValueSelectList())


text:
Q: one hot representation behaving differently for two cases I am using following function for one hot representation.
def dense_to_one_hot(labels_dense, num_classes=2):
    num_labels = labels_dense.shape[0]
    print("num_labels")
    index_offset = numpy.arange(num_labels) * num_classes
    print("index_offset: ",index_offset )
    labels_one_hot = numpy.zeros((num_labels, num_classes))
    print(labels_one_hot.shape)
    print(labels_dense.ravel())
    labels_one_hot.flat[index_offset + labels_dense.ravel()] = 1
    print(labels_one_hot)
    return labels_one_hot

I am getting the error of unsupported iterator index.
train_label_1 = np.load(os.path.join("Input","train_label.npy"))
    train_label = train_label_1[0:10]
    print("train_label")
    print(train_label)
    labels_one_hot = dense_to_one_hot(train_label)
    print("label_one_hot")
    print(labels_one_hot)

When I print train_label, I get following result.
[0. 1. 0. 1. 0. 0. 1. 0. 0. 1.]

When I convert this into numpy array and then call dense_to_one_hot  function it works fine But When I simply load train label from file and call this function it starts giving me error of unsupported iterator index. Can some one please guide me how to fix it.


text:
Q: How to add a leading 0 to the output of shuf if the result is a single digit? Let's say I run this command:
shuf -i 0-12 -n 1

If the result is 0 - 9, I want the result changed to 00 - 09.
If the result is 10 - 12, leave the result as is.
How can I do this?
Thanks

A: Just check if the number is less than ten and modify it as a string, accordingly. If shuf returns a string & not an int, then you could check string length instead.  I think string length is len=${num#}, then you'd check if len is -eq 1
num=$(shuf ...)

if [[ $shuf -lt 10 ]]; then
    num="0${num}"
fi


text:
Q: Best practice for adding Resistor to PLC cabinet My Micro-step drive and PLC need a simple resistor network between their i/o ports.The optocouplers in the stepper drive have a max input current of 15mA, while the controller needs to output at least 20mA to give valid signals. The circuit below satisfies these requirements.

simulate this circuit – Schematic created using CircuitLab
What is a good way to mount these resistors in my PLC cabinet?
Are there terminal blocks that accommodate through hole resistors nicely, or would panel/chassis mount resistors be a better solution?
I have looked at some of the terminal blocks out there, but I haven't seen an elegant solution for adding through hole components. I have looked at panel mount resistors as well, but the power ratings are often much greater than I need.

A: A search for "DIN rail component carrier" throws up images such as this.

Figure 1. A user-configurable PCB with screw terminals and DIN rail mount. Image source: Google image search.
For just one or two resistors or diodes it's common to connect them using standard DIN terminals.

A: I know this is an old question, but I found a couple more options for this while looking for something similar:
I found this from one supplier, haven't found anyone else that makes them.
Ocean Controls 2 x 2K2 Resistor module

As mentioned above, the various big terminal block manufacturers have options for soldering in components - for example, these are all from Phoenix Contact:

Those are PTME 6-BE, UDK 4-DUR, PTTB 2,5-2BE
Phoenix also sell a solderless component holder that uses a spring clamp system to hold & connect through-hole components:

This replaces the blade in a disconnect terminal block - so you need 3 bits - the resistor, the component holder (P-CO), and a disconnect terminal block (e.g. ST 2,5-TG)


text:
Q: How to profile execution of Android apps without slowing down execution? I'm interested in getting what the cpu is doing in each of the time taken when running my apps.
I know of tracedump method profiling or using ddms but it seems that it dramatically slows down the app, making the profiling not accurate.
Is there any tool like sampling every a few ms the execution of the app so that we can analyze our app without much performance overhead?

A: Profiling tools do not count the time they spend themselves. So the only inaccuracy is the tiny overhead in transferring control between your code and the tool's code.


text:
Q: Side by side configuration I have got this error on my Windows 8.1 for every application:

Error: The application has failed to start because the side by side
  configuration is incorrect please see the application event log or use
  the command line sxstrace.exe tool for more detail

I have see on some forum that I should reinstall c++ runtime packages, but also the installers give this error message. I can not run anything.


text:
Q: React does not load local svg I need to load a local SVG calling as a string './MySvg.svg', but it just works if i call it as a component, like <MySvg />.
I followed this tutorial https://blog.logrocket.com/how-to-use-svgs-in-react/, installed file-loader but the problem persists.
I'm trying to put a custom svg on the nodes of a graph with react-d3-graph, but it needs the svg locally as string and will not accept as a component.
Svgteste just exports the svg tag of svgFile.svg
An example with a component
import * as React from 'react';
import { PageSection, Title } from '@patternfly/react-core';
import { Svgteste } from './Svgteste'
import { Test } from './svgFile.svg'
const Dashboard: React.FunctionComponent = () => {

  return(
    <PageSection>
        <Svgteste /> {/*this works*/}
         {/*this won't work*/}
         {/*neither this*/}
    </PageSection>
  )
}

export { Dashboard };

My webpack
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin');
const Dotenv = require('dotenv-webpack');
const BG_IMAGES_DIRNAME = 'bgimages';

module.exports = env => {

  return {
    entry: {
      app: path.resolve(__dirname, 'src', 'index.tsx')
    },
    module: {
      rules: [
        {
          test: /\.(tsx|ts|jsx)?$/,
          use: [
            {
              loader: 'ts-loader',
              options: {
                transpileOnly: true,
                experimentalWatchApi: true,
              }
            }
          ]
        },
        {
          test: /\.(svg|ttf|eot|woff|woff2)$/,
          // only process modules with this loader
          // if they live under a 'fonts' or 'pficon' directory
          use: {
            loader: 'file-loader',
            options: {
              // Limit at 50k. larger files emited into separate files
              limit: 5000,
              outputPath: 'fonts',
              name: '[name].[ext]',
            }
          }
        },
        {
          test: /\.svg$/,
          include: input => input.indexOf('background-filter.svg') > 1,
          use: [
            {
              loader: 'url-loader',
              options: {
                limit: 5000,
                outputPath: 'svgs',
                name: '[name].[ext]',
              }
            }
          ]
        },
        {
          test: /\.svg$/,
          // only process SVG modules with this loader if they live under a 'bgimages' directory
          // this is primarily useful when applying a CSS background using an SVG
          include: input => input.indexOf(BG_IMAGES_DIRNAME) > -1,
          use: {
            loader: 'svg-url-loader',
            options: {}
          }
        },
        {
          test: /\.svg$/,
          // only process SVG modules with this loader when they don't live under a 'bgimages',
          // 'fonts', or 'pficon' directory, those are handled with other loaders

          include: input => (
            (input.indexOf(BG_IMAGES_DIRNAME) === -1) &&
            (input.indexOf('fonts') === -1) &&
            (input.indexOf('background-filter') === -1) &&
            (input.indexOf('pficon') === -1)
          ),

          use: {
            loader: 'raw-loader',
            options: {}
          }
        },
        {
          test: /\.(jpg|jpeg|png|gif)$/i,
          use: [
            {
              loader: 'url-loader',
              options: {
                limit: 5000,
                outputPath: 'images',
                name: '[name].[ext]',
              }
            }
          ]
        },
        {
          test: /\.svg$/,
          use: ['@svgr/webpack'],
        },
        {
        test: /\.(png|jp(e*)g|svg|gif)$/,
        use: [
          {
            loader: 'file-loader',
            options: {
              //name: 'images/[hash]-[name].[ext]',
            },
          },
        ],
      },

      ]
    },
    output: {
      filename: '[name].bundle.js',
      path: path.resolve(__dirname, 'dist')
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: path.resolve(__dirname, 'src', 'index.html')
      }),
      new Dotenv({
        systemvars: true,
        silent: true
      })
    ],
    resolve: {
      extensions: ['.js', '.ts', '.tsx', '.jsx'],
      plugins: [
        new TsconfigPathsPlugin({
          configFile: path.resolve(__dirname, './tsconfig.json')
        })
      ],
      symlinks: false,
      cacheWithContext: false
    }
  }
};

A: I think, you have to remove the curly braces in the import. The curly braces indicate that you want to import a component that is exported with the given name, which is not the case when you import an svg.
import Test from './svgFile.svg'


text:
Q: (Model/View/Controller)MVC what is the MVC and why i use it in Struts

A: MVC is a design pattern on which Struts is based. You can read more about it here.

A: MVC is one of the architectural pattern (see: http://en.wikipedia.org/wiki/Architectural_pattern_(computer_science) )
It is used because it allowe to separate application logic from GUI (in fact this is little more complicated). Thanks to that each part of the application (GUI and app logic) can be developed separately.
Whole pattern is very well described on Wikipedia: http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller


text:
Q: How can I compare two classes base their methods? I want to find out the missing properties in one class by comparing the other class
public class User
{
    public int UserID { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

public class UserDTO
{

    public string UserName { get; set; }
    public string FirstName { get; set; }

}

Above I should get the output like "UserID, "LastName" properties are missing in UserDTO.

A: Use reflection to get the properties, see Type.GetProperties. Then compare both property lists to find the missing ones.
var UserProperties = typeof(User).GetProperties().Select(p => p.Name);
var UserDTOProperties = typeof(UserDTO).GetProperties().Select(p => p.Name);

var missingProperties = UserProperties.Except(UserDTOProperties);

Take into account that all inherited properties will also be present in these lists, unless yous specify BindingFlags.DeclaredOnly to the GetProperties() method, see BindingFlags.

A: var list = typeof(User).GetProperties().Select(x => x.Name)
           .Except(typeof(UserDTO).GetProperties().Select(y => y.Name))
           .ToList();

EDIT
Including suggestions in comments and public Fields
public static IEnumerable<string> Diff(Type t1, Type t2)
{
    return t1.GetProperties().Select(p1 => new { Name = p1.Name, Type = p1.PropertyType })
            .Concat(t1.GetFields().Select(f1 => new { Name = f1.Name, Type = f1.FieldType }))
            .Except(t2.GetProperties().Select(p2 => new { Name = p2.Name, Type = p2.PropertyType })
                    .Concat(t2.GetFields().Select(f2 => new { Name = f2.Name, Type = f2.FieldType })))
            .Select(a => a.Name);
}


text:
Q: Show custom post archive when custom post not specified I have a custom post type called produce set up in WordPress and a custom taxonomy called produce_category.
The URL format for posts in this custom post type is in this format http://mywebsite/produce/%produce_category%/%postname%/. Of course %produce_category% and %postname% get substituted accordingly, a working example url would be http://mywebsite/produce/fruits-and-vegetables/avocado.
What I would like to do is show the produce_category custom taxonomy archive if a user visits http://mywebsite/produce/%produce_category%, without specifying post name at the end, e.g http://mywebsite/produce/fruits-and-vegetables to show all produce in fruits-and-vegetables produce_category.
Besides that when a user visits http://mywebsite/produce/ I would like to show all the produce archive. EDIT: I have this working now.
I know how to create the archive pages totally fine and have no problem with that. I am stuck at creating permalinks. When I visit http://mywebsite/produce/%produce_category% I get a 404 error.
I'm looking for advise on the best way to implement this. Currently I am using Custom Post Type Permalinks and CPTUI.
The CPTUI custom taxonomy settings interface does not allow me to have a blank in the custom rewrite slug. It defaults to the custom taxonomy slug, produce_category, when I don't fill in anything.

This gives the front-side produce_category taxonomy archive url as http://mywebsite/produce/produce_category/%produce_category%/ e.g. http://mywebsite/produce/produce_category/fish-and-seafood/ when what I want for the archive is http://mywebsite/produce/fish-and-seafood/.
Please help with suggestion on the best way I can achieve the custom taxonomy url.
Thank you all.

A: Try this code. It will help you to achieve your url structure... Make sure you update permalinks after saving it to functions.php
function custom_produce_category_link( $link, $term, $taxonomy )
{
    if ( $taxonomy !== 'produce_category' )
        return $link;

    return str_replace( 'produce_category/', '', $link );
}
add_filter( 'term_link', 'custom_produce_category_link', 10, 3 );


text:
Q: Python exec NameError I have a string variable containing a function. the function looks like this:
def program():
    x[0] = y[1]
    z[0] = x[0]
    out = z[0]

This is within a method:
def runExec(self, stringCode):
    x = [1,2,3,4]
    y = [5,6,7,8]
    z = [6,7,8,9]
    exec stringCode
    return out

I am receiving a NameError, it seems x, y and z are not accessible from the stringCode exec ?
How can I make these variables accessible, do I have to pass them in some way ?
Thanks

A: Assuming you have a good reason to use exec, which is an assumption you should double-check.
You need to supply the global and local scope for the exec function.  Also, the "program" string needs to actually run instead of just defining a function.  This will work:
prog = """
x[0] = y[1]
z[0] = x[0]
out = z[0]
"""

def runExec(stringCode):
    x = [1,2,3,4]
    y = [5,6,7,8]
    z = [6,7,8,9]
    exec(stringCode, globals(), locals())
    return out

print runExec(prog)

A: Why do you need to use exec? The following code should work the same way, just without exec:
def program(x, y, z):
    x[0] = y[1]
    z[0] = x[0]
    out = z[0]
    return out

def runExec(self, func):
    x = [1,2,3,4]
    y = [5,6,7,8]
    z = [6,7,8,9]
    out = func(x, y, z)
    return out

self.runExec(program)

A: You can make them global.
global x,y,z
def runExec(self, func):
    x = [1,2,3,4]
    y = [5,6,7,8]
    z = [6,7,8,9]
    out = func(x, y, z)
    return out


text:
Q: Issue with Google Test in Visual Studio 2017 I am trying to use Visual Studio 2017 to create a C++ project and then test it with Google Test. I followed this guide to create my project and set Google Test for it: https://learn.microsoft.com/en-us/visualstudio/test/how-to-use-google-test-for-cpp
My solution has two projects Matrix and Matrix-Test (Google Test project). Project Matrix contains a class called Table. Project Matrix-Test contains a single test where a Table object is declared. Everything looks like this:

If I try to build the solution I get the following errors:
However, if I don't declare the Table object in the test, then the solution builds successfully.

Please let me know if you have any idea why I get these errors. Thank you!

A: The walkthrough https://learn.microsoft.com/en-us/cpp/windows/walkthrough-creating-and-using-a-static-library-cpp?view=vs-2017 will guide you through the process of making your project Matix a static library.
Then you can add this library (e.g. Matrix.lib) as an input to the linker in the Matrix-Test project. This will solve the unresolved external symbol error in regard to your Table class.


text:
Q: ES6 - call anonymous generator with the arrow syntax How I can call generator like this:
const scenarioProvider = (function*() {
    ....
}).bind(this)();

By the arrow function syntax. I mean to replace the 'bind(this)' by the new 'lexical this'.

A: This is not currently possible and is not likely to be included in future versions of ecmascript.

Just to let everyone know (meeting notes, coming soon, will make this clear), we agreed not to do generator arrows. Too much trouble of the kind identified here...

source: Brendan Eich @esdiscuss

A: Arrow functions by definition are lexically scoped. You cannot use a generator with an arrow function
Note however than you cannot bind an arrorw function.
MDN states:

An arrow function expression (also known as fat arrow function) has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous.


text:
Q: Need help for array field This script works fine for me:

<form action="ProvideMedicinProcess.php" class="register" method="POST">

                    <input type="checkbox" required="required" name="chk[]" checked="checked" />
                    <input type="datetime-local" required="required" name="VisitDate[]">

                        <input class="form-control"type="text" required="required" placeholder="Symptoms" name="Symptoms[]">

                        <input class="form-control" type="text" required="required"  placeholder="GivenMedicin" name="GivenMedicin[]">

                        <input id="a1" class="form-control" type="text" required="required" placeholder="UnitePrice" name="UnitePrice[]" onblur="calculate()" >

                        <input id="a2" class="form-control" type="text" required="required" placeholder="Quentity" name="Quentity[]" onblur="calculate()" >

                        <input id="a3" class="form-control" type="text" required="required" placeholder="SubTotal" name="SubTotal[]" >

        <input type="button" value="Add" onClick="addRow('dataTable')" />
        <input type="button" value="Remove" onClick="deleteRow('dataTable')"  />
        <input class="submit" type="submit" value="Confirm" />
        <input type="hidden" value="<?php echo $PatientIDSearch ?>" name="PatientIDSearch" />
</form>

But I need to calculate All Subtotal

A: Some issues:

*

*If you add rows, you'll have to avoid that you get duplicate id property values in your HTML. It is probably easiest to just remove them and identify the input elements via their names, which does not have to be unique

*It is bad practice to assign to a non-declared variable. Use var, and in the case of functions, you can just use the function calculate() { syntax.

*Make the subtotal input elements read-only by adding the readonly attribute, otherwise the user can change the calculated total.

*Instead of responding on blur events, you'll get a more responsive effect if you respond to the input event. And I would advise to bind the event handler via JavaScript, not via an HTML attribute.

*I would fix some spelling errors in your elements (but maybe they make sense in your native language): Quantity with an 'a', UnitPrice without the 'e'.

You can use querySelectorAll to select elements by a CSS selector, and then Array.from to iterate over them.
See below snippet with 2 rows:

function calculate(){
    var unitPrices = document.querySelectorAll('[name=UnitPrice\\[\\]]');
    var quantities = document.querySelectorAll('[name=Quantity\\[\\]]');
    var subTotals = document.querySelectorAll('[name=SubTotal\\[\\]]');
    var grandTotal = 0;
    Array.from(subTotals, function (subTotal, i) {
        var price = +unitPrices[i].value * +quantities[i].value;
        subTotal.value = price;
        grandTotal += price;
    });
    // Maybe you can also display the grandTotal somehwere.
}

document.querySelector('form').addEventListener('input', calculate);
input { max-width: 7em }
<form action="ProvideMedicinProcess.php" class="register" method="POST">

            <input type="checkbox" required="required" name="chk[]" checked="checked" />
            <input type="datetime-local" required="required" name="VisitDate[]">
            <input class="form-control" type="text" required="required" placeholder="Symptoms" name="Symptoms[]">
            <input class="form-control" type="text" required="required" placeholder="Given Medicin" name="GivenMedicin[]">
            <input class="form-control" type="text" required="required" placeholder="Unit Price" name="UnitPrice[]">
            <input class="form-control" type="text" required="required" placeholder="Quantity" name="Quantity[]">
            <input class="form-control" type="text" required="required" placeholder="SubTotal" readonly name="SubTotal[]" >

            <input type="checkbox" required="required" name="chk[]" checked="checked" />
            <input type="datetime-local" required="required" name="VisitDate[]">
            <input class="form-control" type="text" required="required" placeholder="Symptoms" name="Symptoms[]">
            <input class="form-control" type="text" required="required" placeholder="Given Medicin" name="GivenMedicin[]">
            <input class="form-control" type="text" required="required" placeholder="Unit Price" name="UnitPrice[]">
            <input class="form-control" type="text" required="required" placeholder="Quantity" name="Quantity[]"" >
            <input class="form-control" type="text" required="required" placeholder="SubTotal" readonly name="SubTotal[]" >

</form>


text:
Q: An Isomorphism of Rings Let $R$ be the ring of Quaternions over $\Bbb{Z}_{(3\Bbb{Z})}$ ($\Bbb{Z}$ localized in $3\Bbb{Z}$). Is it true that  $\frac{R}{J(R)}$ can be represented as  $M_2(\Bbb{Z}_3)$ ?
($\Bbb{Z}_3$ is the integers modulo 3).

A: $\def\ZZ{\mathbb{Z}}$Let us write, for every ring $R$,  $Q(R)$ for the quaternion algebra with coefficients in $R$.
The surjective map $f:\ZZ_{(3)}\to\ZZ/3$ induces a surjective map $F:Q(\ZZ_{(3)}\to Q(\ZZ/3)$. Since $\ZZ/3$ is a field, the ring $Q(\ZZ/3)$ is semisimple, and therefore the Jacobson radical $J(Q(\ZZ_{(3)})$ is contained in $\ker F$, which is the ideal generated by $3$ in $Q(\ZZ_{(3))}$. I claim that in fact $\ker F$ is the Jacobson radical.
To check this, it is enough to show that whenever $x$ is in $\ker F$ the element $1-x$ is invertible in $Q(\ZZ_{(3)})$, because this implies that $\ker F$ is contained in $J(Q(\ZZ_{(3)})$ (see, for example, I.M.Isaacs, Algebra, Theorem 13.4) Now if $x\in\ker F=3Q(\ZZ_{(3)})$, you can easily check that the norm of $1-x$, which is an element of $\ZZ_{(3)}$, is congruent to $1$ modulo $3\ZZ_{(3)}$ so it is in fact invertible in $\ZZ_{(3)}$: it follows from this that $1-x$ is invertible in $Q(\ZZ_{(3)})$.
So now we know that $Q(\ZZ_{(3)})/J(Q(\ZZ_{(3)}))$ is isomorphic to $Q(\ZZ/3)$. Now the quaternion algebra $Q(\ZZ/3)$ is isomorphic to $M_2(\ZZ/3)$, by the usual criterion for this to happen (it is given in this page, for example)